Python Module-1 QB Solution (21EC643)
Python Module-1 QB Solution (21EC643)
Module -1
2. List the rules to declare the variable in python. Demonstrate at least 3 types of variables
uses with an example program
x$=4 #contains $
SyntaxError: invalid syntax
if=10 # if is a keyword
SyntaxError: invalid syntax
1. Integer
# An integer assignment
Roll_number = 45
print(“Roll number”, Roll_number)
type(Roll_number)
output
Roll number: 45
int
2. float
# A floating point
height = 5.8
print('height:', height)
type(height)
3. String
# A string
name = "Sachin Tendulkar"
print (‘name:’, name)
type(name)
Output:
name: Sachin Tendulkar
str
• Parentheses: have the highest precedence in any expression. The operations within
parenthesis will be evaluated first.
Examples: 2 * (3-1) => Output= 4
(1+1)**(5-2) => Output= 8
The addition has to be done first and then the sum is multiplied with c
• Exponentiation: It has the 2nd precedence and Right to left Associative. That is, if there are
two exponentiation operations continuously, it will be evaluated from right to left
Examples: 2**1+1 => Output= 3
3*1**3 => Output= 3
2**3**2 => Output= 512
• Multiplication and division, modulus : The Multiplication and Division have same priority
& 3rd precedence and left-to-right associative. If there are two or more
Multiplication/Division operations continuously, then evaluated from left-to-right.
Examples: 2*3-1 => Output= 5
5-2*2 => Output= 1
5*2/4 => Output= 2.5
• Addition and Subtraction:
The Addition and Subtraction have same priority & 4th precedence (least priority) and left-
to-right associative.
Examples: 5-3-1 => Output= 1
5-2+2 => Output= 5
6-(3+2) => Output= 1
4. Describe the Python functions int ( ), float ( ) and str ( ) with example
str():
This function Converts a value to string form.
Examples:
>>> str(0)
Output : '0'
>>> str(-3.14)
Output : '-3.14'
int()
This function converts a value to its integer form.
Examples:
>>> int('42')
Output : 42
>>> int('-99')
Output : -99
>>> int(1.25)
Output: 1
>>> int(1.99)
Output: 1
float():
This function converts a value to its floating-point form.
Examples:
>>> float('3.14')
3.14
>>> float(10)
10.0
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'
>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'
Example Program :
print('What is your age?') # ask for their age
myAge = int (input())
print('You will be ' + str(myAge + 1) + ' in a year.')
Output
If the user enters: ‘4’
myAge : 4 #integer
myAge+1 = 5.
str(myAge+1) converts 5 to string '5'.
Final output: "You will be 5 in a year.
5. Write a python program to find the best of two test average marks out of 3 tests marks
accepted from the user
else: (# This covers the case where m3 >= m1 and m1 >= m2)
total = m1 + m3
Avg = total / 2
print ("The average of the best two test marks is: ",Avg)
Output :
Enter the marks in the first test: 20
Enter the marks in the second test: 15
Enter the marks in the third test: 22
The average of the best two test marks is: 21.0
• Errors that occur at runtime (after passing the syntax test) are called exceptions
Handling an exception
Python can handle exceptions using try & except statements
• try block: If the code is suspicious or prone to runtime error, then put this code within the try
block.
• except block: Put the remedy code or information about what may go wrong and what is the
way to come of it.
• During the execution, first try block will be executed, if something goes wrong within try
block, then except block will be executed. Otherwise, the except-block will be skipped.
Example 1:
• For example, consider the following code segment
a=int(input("Enter value for a:"))
b=int(input("Enter the value for b:"))
c=a/b
print(c)
• Let us run the above code, and see output
Output :
Enter value for a:5
Enter the value for b:0
--------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
ZeroDivisionError: division by zero
• Here because of the wrong input, during runtime, error has occurred and error message is
generated, but for the user, it is difficult to understand the such type of system-generated error
messages and handle the errors.
• By using try and except statements, we can display our own messages or solution to the user so
that problem can be handled or solved easily.
except:
print ("Division by zero is not possible, enter non zero value for b")
Output:
Enter value for a:5
Enter the value for b:0
Division by zero is not possible, enter non zero value for b
7. Write a single user defined function named “solve” that returns remainder and quotient
on division of two numbers accepted from the user. Print remainder and quotient
separately on the console
def solve(a,b):
rem=a%b
div=a/b
return[rem, div] #if multiple values to be returned use []
Output
Enter the first value: 5
Enter the first value: 2
Remainder = 1
Division= 2.5
i. (200-70)*10/5
ii. not “false” = False
iii. 5*1**2 = 5
iv. 2**1+1=3
i. (200-70)*10/5 = 260
Justification:
• First parenthesis, so (200-70)= 130.
• The Multiplication and Division have same priority & so evaluated from left-to-right.
• So, then 130*10 = 1300, and finally 1300/5 = 260.0.
iv. 5*1**2 = 5
Justification:
This expression has * (multiplication) & ** (exponentiation) operators.
The ** has higher precedence than the operator * .
Therefore, the exponentiation expression is evaluated first; 1**2 =1. Then, multiplication
operation is performed; 5*1=5.
v. 2**1+1=3
9. List and explain the different comparison and Boolean operators, along with examples
Comparison operators
• Comparison operators return Boolean values by comparing two values.
• Essential for making decisions in flow control statements (if, while).
• Used widely beyond flow control, such as in loops and conditions.
Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean values.
• Used in conditional statements (if, elif, else), loops (while, for), and other decision-
making contexts.
(4 < 5) and (5 < 6) Both are True, so the result is True TRUE
Example 2: Write program to Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count = count +1
Output:
1
2
3
Explain this example in your own words
for loop
• for loops are used to repeat the block of code for fixed number of times. This is count
controlled loop.
• In case of for loop, we know number of times the block of code to be executed or repeated
in prior, so this is called as a definite loop. But in case of while loop, it repeats, until some
condition becomes False, so it is called as indefinite loop
• The for-loop is always used in combination with an iterable object, like range or sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
Syntax:
Examples
Example1:
for loop using range function
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example2
Iterating over a list
seq= [2,5,8,18,10] #List is created with name seq
for i in seq:
print(i)
Output:
2
5
8
18
10
11. Write a python program to demonstrate the counting, summing, and average of n
natural numbers using loops
i=0
sum=0
while i<n:
sum=sum+i
i=i+1
average = sum/n
print('Sum of n numbers is :' , sum)
print('Average of n numbers is :', average)
print('Count is :', i)
Output :
Enter the number : 5
Sum of n numbers is : 10
Average of n numbers is : 2.0
Count is : 5
12.Explain the local and global scope of the variable with a suitable example.
Scope refers to the area of code where a variable is accessible. In Python, there are two main types
of scopes: global scope and local scope.
• Global Scope: Variables defined outside of any function have global scope. They can be
accessed from anywhere within the program.
• Local Scope: Variables defined inside a function have local scope. They are only accessible
within that function.
def func():
print("Inside func():", global_var) # Accessing global_var
13. List and give syntax of all python supported conditional statements (if, if else, if elif )
along with its usage with an example program to check whether given number is positive
or negative or zero
• Conditional statements are also called decision-making statements. We use these statements,
when we want to execute a block of code, only if the given condition is met (true or false).
1. if statements
2. Alternative Execution (if else)
3. Chained Conditionals: if elif else
4. Nested Conditionals
if statements
• There is no limit for, the number of statements in the if body, but there must be at least one.
• Here, when the condition is true, one set of statements will be executed and when the
condition is false, another set of statements will be executed.
• The syntax and flowchart are as given below
else:
print("Negative number")
Nested Conditionals
• One conditional statement can be nested within another conditional statement.
Example
gender=input("Enter gender:")
age=int(input("Enter age:"))
if gender ==’M’
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F" :
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")
Using function
def largest(num1, num2, num3):
if (num1 >= num2) and (num1 >= num3):
return num1
13. Illustrate the flow of execution of python user define function with an example program
to convert given Celsius to Fahrenheit temperature
def convert(c):
F = (9/5)*c + 32
return (F)
14. Write a python program to calculate the area of square, rectangle and circle. Take the
input from user
15. Mention the uses of continue statement. Write program to compute only even numbers
sum within the given natural number using continue statement.
16. With syntax explain the finite and infinite looping constructs in python. What is the need
for break and continue statements?
Finite loop:
Example :
Write program to Print even numbers from 0 to 10 using while loop.
i=0
while i <= 10:
print(i)
i = i +2
Here loop terminates once the condition is met, ie after finite number of iterations.
Infinite Loop:
• Infinite Loop is loop, in which condition never becomes false, hence block of code will be
executed infinite number of times.
• Example 1
n = 10
while True:
print(n)
n = n -1
Here, in this example, the condition specified is the constant value True, so all the time it
is true, no way to make it false, so once it gets into loop, it will never get terminated.
While, break
• In case of infinite loop, we can use the break statement to jump out of the loop.
• The break statement terminates the current loop and passes the control to the next statement,
which is immediately after the body of loop
while True:
print(n)
n = n -1
if n= =5:
break
Here break statement is placed within loop, after the if statement & break statement
provides chance to exit the loop, when external condition is generated.
while, continue
• The continue statement in returns the control to the beginning of the while loop.
• The continue statement rejects or skips all the remaining statements in the current loop and
moves the control back to the top of the loop.
i=0
while i<=5
i=i+1
if i == 3:
continue
print(i)
17. What is the user defined function? How we pass parameters in user defined functions,
explain with program?
User defend function: set of statements to perform specific task, is known as user defined
function.
Example:
def fun_add(x, y): # x and y are parameters
z=x+y
return z
• In the above example, the function fun_add () takes two arguments and returns the result to
the calling function. Here returned value to calling function is stored in the variable s.
• When a function returns something and if it is not stored using the variable, then the return
value will vanish and not be available for the future use.
• Here in case, if we just use the statement fun_add(num1, num2) instead of
s= fun_add(num1, num2), then the value returned from the function is of no use.
19. Write python program to calculate the labour Pay from the hours and rate. The values of hour and
rate have to be taken from user.
(Hint: pay= hour*rate).
Rewrite the above program using try and except, so that your program handles nonnumeric input
gracefully by printing a message and exiting the program. The following shows two executions of the
program
Enter Hours: 20
Enter rate: nine
Error, please enter the numeric input
Enter Hours: forty
Error, please enter the numeric input
Normal program
hour=int(input("Enter Hours:"))
rate=int(input("Enter Rate:"))
pay = hours *rate
print("Pay:", pay)
try:
hour=int(input("Enter Hours:"))
rate=int(input("Enter Rate:"))
pay = hours *rate
print("Pay:", pay)
except:
print("Error, Error, please enter the numeric input”)
exit()
Example:
n=1
while n>0:
print(n)
n = n +1
if n==8:
break
i=0
while i<=5
i=i+1
if i == 3:
continue
print(i)
22. Write the python program to generate and print prime numbers from numbers between
2 to 50
lower = 2
upper = 50