PAP_module-1
PAP_module-1
4. Computer Networks
Computer networking refers to interconnected computing devices that can exchange da and
share resources with each other.
Logic errors
A logic error is when the program has good syntax but there is a mistake in the order of the
statements or perhaps a mistake in how the statements relate to one another. The order of the
statement is not proper.
Example:
# initialize the marks variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
output: ZeroDivisionError: division by zero
Semantic errors
A semantic error when the program is syntactically perfect and in the right order, but there is
simply a mistake in the program. The program is perfectly correct but it does not do what you
intended for it to do.
Example:
num1 = input('Enter a number:')
num2 = input('Enter another number:')
sum = num1 + num2
print('The sum of', num1, 'and', num2, 'is', sum)
The program contains a semantic error. The error is that the program performs concatenation
instead of addition, because the programmer failed to write the code necessary to convert the
inputs to integers.
Q5. Define high level language and machine language. List out the differences between
Compiler and Interpreter. (8/6 marks)
High-level language A programming language like Python that is designed to be easy for
humans to read and write.
1. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an output of low-
level language i.e., machine or assembly language.
A compiler is more intelligent than an assembler it checks all kinds of limits, ranges, errors,
etc.
But its program run time is more and occupies a larger part of memory. It has a slow speed
because a compiler goes through the entire program and then translates the entire program into
machine codes.
2. Interpreter:
An interpreter is a program that translates a programming language into a comprehensible
language. –
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
The compiler scans the whole Translates the program one statement at a
1. program in one go. time.
It converts the source code into object It does not convert source code into object
4. code. code instead it scans it line by line
Any change in source program after Any change in source program during the
the compilation requires recompiling translation does not require’s retranslation
11. of entire code. of entire code.
if import in is
yield
import keyword
# printing all keywords at once using "kwlist()"
print ("The list of keywords is : ")
print(keyword.kwlist)
Problems
Ex1: Solve 2+7×8-5
Solution: 53
Ex2: Find the value of the expression: (8 × 6 – 7) + 65
Solution: 106
Ex3: Evaluate 8/4 × 6/3 × 7 + 8 – (70/5 – 6)
Solution:
Evaluate 8/ 4 × 6/3 × 7 + 8 – (70/5 – 6 )
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 8
Ex5:
Evaluate 2 ** 2 ** 3 * 3
2 ** 2 ** 3 * 3
2 ** 8 * 3
256 * 3
768
Q2. Explain the built-in data types in python with example. (6 marks)
Data type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'
x = "Python is "
y = "awesome"
z= x+y
print(z)
output: HelloWorld
String Replication
The * operator is used for string multiplication. But when the * operator is used on one string
value and one integer value, it becomes the string replication operator.
Example
st='Alice'
print(st*3)
output: AliceAliceAlice
Q6. Explain variable names, keywords and expressions with examples (6marks)
An expression is a combination of operators and operands that is interpreted to produce some
other value. In any programming language, an expression is evaluated as per the precedence
of its operators.
Examples:
# Constant Expressions
x = 15 + 1.3
# Arithmetic Expression
x = 40
y = 12
A=x + y
# Logical Expressions
P = (10 == 9)
Q = (7 > 5)
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 10
== Equal x == y
!= Not equal x != y
2. input() Function
The input() function waits for the user to type some text on the keyboard
and press enter.
Example:
myName = input('enter your name')
output: 'enter your name' Alice
----------------------------------------------------------------------------------------------------------------
Q12. Explain the concept of type conversion functions and math functions in python with
examples. (5 marks).
Type conversion functions
1. int (a, base): This function converts any data type to integer. ‘Base’ specifies the base
in which string is if the data type is a string.
2. float (): This function is used to convert any data type to a floating-point number.
3. str () : Used to convert integer into a string.
>>> int ('32')
32
>>> int ('Hello')
Value Error: invalid literal for int () with base 10: 'Hello'
if x > 0 :
print('x is positive')
ii) if-else statement (alternative execution)
if x%2 = = 0 :
print('x is even')
else :
print('x is odd')
iii) if-elif-else ladder(chained conditionals)
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
iv) Nested if else (nested Conditional statement)
if x = = y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 14
Q12. What is exception handling? How Exceptions are handled in Python? Write a
python program with exception handling code to solve divide-by-zero situation (6 marks).
Or
How Python handles Exceptions. Explain with programming Example.
Error in Python can be of two types i.e., Syntax errors and Exceptions. Syntax Errors are the
problems in a program due to which the program will stop the execution
Exceptions: Exceptions are raised when the program is syntactically correct, but the code
results in an error. This error does not stop the execution of the program; however, it changes
the normal flow of the program.
Common Python Exceptions
1) Type Error: occurs when the data type of objects in an operation is inappropriate.
Example:
X=” apple”
Y=10
Z=X+Y
2) Value Error: Python Value Error is raised when a function receives an argument of the
correct type but an inappropriate value.
Example:
>>import math
X=math.sqrt(-11)
3) AttributeError: occurs when an invalid attribute reference is made. This can happen if an
attribute or function not associated with a data type is referenced on it.
Example:
# Python program to demonstrate
# AttributeError
X = 10
# Raises an AttributeError
X.append(6)
# Python code to illustrate
# working of try and Exception
x=int (input (“enter the value of dividend”))
y=int (input (“enter the value of divisor”))
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print ("the quotient is :", result)
except:
print ("Sorry ! You are dividing by zero ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Q13. Explain the concept of short circuit evaluation of logical expression in python.
When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates the
expression from left to right.
Because of the definition of and, if x is less than 2, the expression x >= 2 is False and so the
whole expression is False regardless of whether (x/y) > 2 evaluates to True or False.
When Python detects that there is nothing to be gained by evaluating the rest of a logical
expression, it stops its evaluation and does not do the computations in the rest of the logical
expression. When the evaluation of a logical expression stops because the overall value is
already known, it is called short-circuiting the evaluation.
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Iteration
>>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called
a decrement.
----------------------------------------------------------------------------------------------------------------
Q14: Explain while loop and for loop with example. (4marks)
The while statement
With the while loop we can execute a set of statements as long as a condition is true.
n=5
while n > 0:
print(n)
n=n-1
print('Blastoff!')
The flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at
the next statement.
3. If the condition is true, execute the body and then go back to step 1.
Q15. With syntax and example code, explain the working of definite loop in python. (5
marks)
Output:
apple
cherry
output:
2
3
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 17
4
5
for x in range(2, 30, 5):
print(x)
output:
2
7
12
17
22
27 2------------
22
Q16: With syntax, explain the finite and infinite looping constructs in python. (4marks)
Q3: Explain Break and Continue statement with an example in Python. (4 marks)
Mention the advantages of continue statement. Write a program to compute only even
number sum within the given natural number using continue statement. (8marks)
Break statement
• The break statement is used to terminate the loop or statement in which it is present.
• After that, the control will pass to the statements that are present after the break statement, if
available.
• If the break statement is present in the nested loop, then it terminates only those loops which
contains break statement.
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done! out of while loop’ )
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 18
output
> hello there
hello there
> finished
finished
> done
Done! out of while loop
The loop condition is True, which is always true, so the loop runs repeatedly until
it hits the break statement.
Continue statement
• Continue is also a loop control statement just like the break statement.
• continue statement is opposite to that of break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop.
• As the name suggests the continue statement forces the loop to continue or execute the next
iteration.
• When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and the next iteration of the loop will begin.
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done! Out of while loop')
output
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done! Out of while loop
All the lines are printed except the one that starts with the hash(#) sign because when the
continue is executed, it ends the current iteration and jumps back to the while statement
to start the next iteration, thus skipping the print statement.
Q17. Write a python program to read the numbers repeatedly until the user enters ‘done’.
Once ‘done is entered print out total, count and average of numbers (6 marks)
count = 0
tot = 0.0
while True:
number = input("Enter a number")
if number == 'done':
break
num1 = float(number)
count= count+1
tot = tot + num1
Avg=tot/count
print (tot,num,Avg)
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
output: Who are you?
Joe
Hello, Joe. What is the password? (It is a fish.)
swordfish
Access granted.
importing modules
Python comes with a set of modules called the standard library. Each module is a Python
program that contains a related group of functions that can be embedded in your programs. For
example, the math module has mathematics- related functions, the random module has random
number–related functions, and so on.
Before the use of functions in a module, you must import the module with an import statement.
In code, an import statement consists of
the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
Example 1:
for i in range (5):
print (random.randint(1, 10))
output:
4
1
8
4
1
Example 2:
#Ending a Program early with sys.exit()
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.
Random numbers
• Python defines a set of functions that are used to generate or manipulate random
numbers through the random module.
• The random module provides functions that generate pseudorandom numbers
• The function random returns a random float between 0.0 and 1.0 (including 0.0
but not 1.0). Each time you call random, you get the next number in a long series.
Method Description
import random
for i in range (10):
x = random.random()
print(x)
This program produces the following list of 10 random numbers between 0.0 and
up to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867
he function randint takes the parameters between low and high (including both)
>>> random.randint (5, 10)
output
5
>>> random.randint (5, 10)
output
9
To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice (t)
output
2
>>> random.choice(t)
output
3
>>mylist = ["apple", "banana", "cherry"]
>>random.shuffle(mylist)
>>print(mylist)
>>['apple', 'cherry', 'banana']
>> print (random.uniform(20, 60))
>>23.680525894591096
#To list all the functions listed under math module
import math
print(dir(math))
Method Description
math. sin() Returns the sine of a number
math. cos() Returns the cosine of a number
math.tan() Returns the tangent of a number
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
Example:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
Functions________________________________________________________________
Q18. What is a function? How to define a function in python? Define with suitable
example. (6 marks).
_____________________________________________________________
A function is a reusable block of programming statements designed to perform a certain task.
To define a function, Python provides the def keyword. The following is the syntax of
defining a function.
def mult_Num(num1):
return num1 * 8
result = mult_Num(8)
print(result)
# Output:
----------------------------------------------------------------------------------------------------------------
Q19. Differentiate between argument and parameter. Illustrate the flow of execution of
a Python function with an example program to convert given Celsius to Fahrenheit
temperature. (8 marks)
Argument Parameter
Arguments are also known as Actual Parameters are also called Formal
Parameters. Parameters
# Creation of Function
def add_no (a, b):
c=a+b
# Returning the value
return c;
# Function call
d = add_no (3, 4);
print(d)
Void Functions
1. Void functions are those that do not return any value after their calculation is
complete.
2. These types of functions are used when the calculations of the functions are not
needed in the actual program.
3. These types of functions perform tasks that are crucial to successfully run the program
but do not give a specific value to be used in the program.
# Creation of Function
Q22.How can you force a variable in a function to refer to the global variable?
To create a global variable inside a function, you can use the global keyword.
Example:
def spam():
global eggs
eggs = 'spam'
spam()
print(eggs)
output: spam
Programs:
Exercise 1: Write a program that uses input to prompt a user for their name and
then welcomes them.
name = input ("Enter your name")
print ('Hello!’, name)
output: Enter your name Marry
'Hello! Marry
Exercise 2: Write a program to prompt the user for hours and rate per hour to
compute gross pay.
#Compute gross pay bye hours and rate per hour
hours=input ("Enter Hour:")
rate=input ("Enter Rate per Hour:")
pay=float(hours)*float(rate)
print ("Pay is:", pay)
output: Enter Hour 20
Enter Rate per Hour: 2
Pay is 40.0
Exercise 3: Assume that we execute the following assignment statements:
width = 17
height = 12.0
Calculate
1. width//2
>>8
2. width/2.0
>>8.5
3. height/3
>>4.0
4. 1 + 2 \* 5
>>SyntaxError: unexpected character after line continuation character
Exercise 4: Write a program which prompts the user for a Celsius temperature, convert
the temperature to Fahrenheit, and print out the converted temperature.
F = (°C × 9 /5 ) + 32.
°C = [(°F-32) ×5]/9
Celsius =float (input (“enter temperature in Celsius”))
Fahrenheit = (Celsius * 1.8) + 32
print (“the given temperature in degree Fahrenheit is ", Fahrenheit)
output:
enter temperature in Celsius 40
the given temperature in degree Fahrenheit is 104.0
----------------------------------------------------------------------------------------------------------------
Exercise 5: Write a python program to calculate area of circle, rectangle and triangle.
print the results.
#Area of circle
R=int (input ("Enter the radius of the circle"))
Cir_area=float ((3.14) *R*R)
# Area of rectangle
Rw=int (input ("Enter the width of the rectangle"))
Rh=int (input("Enter the height of the rectangle"))
Rect_area=float (Rw*Rh)
#Area of triangle
Th=int (input ("Enter the height of the triangle"))
Tb=int (input ("Enter the breadth of the triangle"))
T_area=float ((0.5) *(Tb)*(Th))
#print results
Exercise 6: Rewrite your pay computation to give the employee 1.5 times the hourly rate
for hours worked above 40 hours.
Exercise 7: Rewrite your pay program using try and except so that your pro-gram handles
non-numeric input gracefully by printing a message and exiting the program. The
following shows two executions of the program:
Exercise 8: Write a program to prompt for a score between 0.0 and 1.0. If the
score is out of range, print an error message. If the score is between 0.0 and 1.0,
print a grade using the following table:
Score Grade
>=0.9 A
>=0.8 B
>=0.7 C
>=0.6 D
<0.6 F
Use Try and Except so that your program handles non-numeric input gracefully by
printing a message and exit the program.
Exercise 9: Write a python program to calculate student score based on 2 exams, 1 sport
event and 3 activities conducted in a college with weightage of the activity =30% and
sports=20% for 50 marks.
Exercise 11: write a python program to find best of two average marks out of three
test's marks accepted from user.
Exercise 12: Rewrite your pay computation with time-and-a-half for overtime and create
a function called computepay which takes two parameters (hours and rate)
def computepay(hr,rt):
if hr<=40:
gross_pay=hr*rt
elif hr>40:
gross_pay=(hr-40)*rt*1.5+40*rt
return gross_pay
Exercise 13: Rewrite your pay computation with time-and-a-half for overtime and
create a function called computepay which takes two parameters (hours and rate).
def comutegrade(score):
try:
sc=float(sc)
if sc>0.9:
grade='A'
elif sc>0.8:
grade='B'
elif sc>0.7:
grade='C'
elif sc>0.6:
grade='D'
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 32
elif sc<=0.6:
grade='Fail'
return print("grade is ",grade)
except:
print('bad score')
sc=input("enter the grade between 0.0 and 1.0\n")
comutegrade(sc)