Python Revision Material - CH.1,2.3.5.9
Python Revision Material - CH.1,2.3.5.9
21. Name the Python Library modules which need to be imported to invoke the following
functions: (i) ceil( ) (ii) randrange( )
22. What will be the output of the following expression: print(24//6%3, 24//4//2, 20%3%2)
23. Evaluate following expressions:
a) 18 % 4 ** 3 // 7 + 9
b) 2 > 5 or 5 == 5 and not 12 <= 9
c) 16%15//16
d) 51+4-3**3//19-3
e) 17<19 or 30>18 and not 19==0
24. Expand the following terms:
a. HTML b. ITA c. SIP d. GSM
e. PPP f. PAN g. POP3 h. FTP
84
SOLUTIONS: GENERAL THEORY
Ans1. The round( ) function is used to convert a fractional number into whole as the nearest next
whereas the floor( ) is used to convert to the nearest lower whole number.
E.g. round(5.8) = 6 and floor(5.8)= 5
Ans3. Default arguments are used in function definition, if the function is called without the argument,
the default argument gets its default value.
Ans 4. Actual parameters are those parameters which are used in function call statement and formal
parameters are those parameters which are used in function header (definition).
e.g. def sum(a,b): # a and b are formal parameters
return a+b
x, y = 5, 10
res = sum(x,y) # x and y are actual parameters
Ans 6: Built in functions can be used directly in a program in python, but in order to use modules, we have
to use import statement to use them.
Ans 7.
Sno. LOCAL VARIABLE GLOBAL VARIABLE
1 It is a variable which is declared within a It is a variable which is declared outside
function or within a block. all the functions.
2 It is accessible only within a function/ block in It is accessible throughtout the
which it is declared. program.
For example,
def change():
n=10 # n is a local variable
x=5 # x is a global variable
print( x)
Ans 8. i) using the function is easier as we do not need to remember the order of the arguments.
ii) we can specify values of only those parameters which we want to give, as other parameters
have default argument values
Ans9. Scope of variables refers to the part of the program where it is visible, i.e, the area where you can
use it
Ans10. (i)
85
2. QUESTIONS - ERROR FINDING
Q1. Find error in the following code(if any) and correct code by rewriting code and
underline the correction;-
x= int(“Enter value of x:”)
for y in range [0,10]:
if x=y
print( x + y)
else:
print( x-y)
Q2. Rewrite the following program after finding and correcting syntactical errors and
underlining it.
a, b = 0
if (a = b)
a +b = c
print(c)
Q3. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
250 = Number
WHILE Number<=1000:
if Number=>750
print (Number)
Number=Number+100
else
print( Number*2)
Number=Number+50
Q4. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Val = int(rawinput("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
if C%2=0:
Print (C*10)
Else:
print (C*)
print (Adder)
Q5. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
25=Val
for I in the range(0,Val)
if I%2==0:
print( I+1):
Else:
print [I-1]
Q6. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))
86
Q7. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=int{input("ENTER FIRST NUMBER")}
b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c
print("A IS GREATER")
if b>a and b>c:
Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)
Q8. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
i==1
a=int(input("ENTER FIRST NUMBER"))
FOR i in range[1, 11];
print(a,"*=", i ,"=",a * i)
Q9. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=”1”
while a>=10:
print("Value of a=",a)
a=+1
Q10. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Num=int(rawinput("Number:"))
sum=0
for i in range(10,Num,3)
Sum+=1
if i%2=0:
print(i*2)
Else:
print(i*3 print Sum)
Q11. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
weather='raining'
if weather='sunny':
print("wear sunblock")
elif weather='snow':
print("going skiing")
else:
print(weather)
Q12. Write the modules that will be required to be imported to execute the following
code in Python.
def main( ):
for i in range (len(string)) ):
if string [i] = = ‘’ “
print
else:
c=string[i].upper()
print( “string is:”,c)
print (“String length=”,len(math.floor()))
87
Q13. Observe the following Python code very carefully and rewrite it after removing all
syntactical errors with each correction underlined.
DEF execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()
Q14. Rewrite the following code in python after removing all syntax error(s).Underline
each correction done in the code
x=integer(input('Enter 1 or 10'))
if x==1:
for x in range(1,11)
Print(x)
Else:
for x in range(10,0,-1):
print(x)
Q15. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
else
print (K+3)
88
Ans 4. Val = int(raw_input("Value:")) # Error 1
Adder = 0
for C in range(1,Val,3) : # Error 2
Adder+=C
if C%2==0 : # Error 3
print( C*10 ) # Error 4
else: # Error 5
print (C ) # Error 6
print(Adder)
Also range(0,8) will give a runtime error as the index is out of range. It shouldbe range(0,7)
i=1
a=int(input("ENTER FIRST NUMBER"))
for i in range(1,11):
print(a,"*=",i,"=",a*i)
a=1
while a<=10:
print("Value of a=",a)
a+=1
90
Q4. Find out the output of the Following –
for a in range(3,10,3):
for b in range(1,a,2):
print(b, end=’ ‘)
print( )
Q10. Find and write the output of the following python code:
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print (Msg3)
91
Q11. Find and write the output of the following python code :
def Changer(P,Q=10):
P=P/Q
Q=P%Q
print (P,"#",Q)
return P
A=200
B=20
A=Changer(A,B)
print (A,"$",B)
B=Changer(B)
print (A,"$",B)
A=Changer(A)
print (A,"$",B)
Q12. Find and write the output of the following python code:
Data = ["P",20,"R",10,"S",30]
Times = 0
Alpha = ""
Add = 0
for C in range(1,6,2):
Times= Times + C
Alpha= Alpha + Data[C-1]+"$"
Add = Add + Data[C]
print (Times,Add,Alpha)
Q13. Find and write the output of the following python code:
Text1="AISSCE 2018"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print (Text2)
Q14. Find and write the output of the following python code:
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print(TOTAL)
CNT-=1
92
Q15. Find output generated by the following code:
line = "I'll come by then."
eline = ""
for i in line:
eline += chr(ord(i)+3)
print(eline)
1. t1=("sun","mon","tue","wed")
print(t1[-1])
2. t2=("sun","mon","tue","wed","thru","fri")
for i in range (-6,2):
print(t2[i])
3. t3=("sun","mon","tue","wed","thru","fri")
if "sun" in t3:
for i in range (0,3):
print(t2[i])
else:
for i in range (3,6):
print(t2[i])
5. t5=("sun",2,"tue",4,"thru",5)
if "sun" not in t4:
for i in range (0,3):
print(t5[i])
else:
for i in range (3,6):
print(t5[i])
6. t6=('a','b')
95
t7=('p','q')
t8=t6+t7
print(t8*2)
7. t9=('a','b')
t10=('p','q')
t11=t9+t10
print(len(t11*2))
8. t12=('a','e','i','o','u')
p, q, r, s, t=t12
print("p= ",p)
print("s= ",s)
print("s + p", s + p)
9. t13=(10,20,30,40,50,60,70,80)
t14=(90,100,110,120)
t15=t13+t14
print(t15[0:12:3])
2. t1=(10,20,30,40,50,60,70,80)
i=t1.len()
Print(T1,i)
3. t1=(10,20,30,40,50,60,70,80)
t1[5]=55
t1.append(90)
print(t1,i)
4. t1=(10,20,30,40,50,60,70,80)
t2=t1*2
t3=t2+4
print t2,t3
5. t1=(10,20,30,40,50,60,70,80)
str=””
str=index(t1(40))
print(“index of tuple is ”, str)
str=t1.max()
print(“max item is “, str)
1. d1 ={"john":40, "peter":45}
2. d2 ={"john":466, "peter":45}
3. d1 > d2
a) True b) False
c) ERROR d) None
Q9. What will be the error of the following code Snippet?
Lst =[1,2,3,4,5,6,7,8,9]
Lst[::2]=10,20,30,40,50,60
Print[Lst]
Q10. Find the error in following code. State the reason of the error
aLst={‘a’:1,’b’:2,’c’:3}
print(aLst[‘a’,’b’])
98
Q13. What will be the output of the following Code Snippet?
a = {(1,2):1,(2,3):2}
print(a[1,2])
A. Key Error B. 1 C. {(2,3):2} D. {(1,2):1}
Ans 4. list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009]
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]
Ans 10. The above code produce KeyError, the reason being that there is no key same as the
list[‘a’,’b’] in dictionary aLst
Ans 15. B
99
QUESTIONS : FUNCTIONS - OUTPUT AND ERROR
b) def main ( )
print ("hello")
c) def func2() :
print (2 + 3)
func2(5)
def calcSquare(a):
a = power (a, 2)
return a
n=5
result = calcSquare(n)
print (result)
100
Q4. Find the output of the following-
import math
print (math. floor(5.5))
Q. 10. a=10
def call( ):
global a
a=15
b=20
print(a)
call( )
11. Write a user defined function GenNum(a, b) to generate odd numbers between a and b
(including b).
101
12. Write definition of a method/function AddOdd(VALUES) to display sum of odd values
from the list of VALUES.
13. Write definition of a Method MSEARCH(STATES) to display all the state names from a list of
STATES, which are starting with alphabet M.
For example:
If the list STATES contains [“MP’,”UP”,”MH”,”DL”,”MZ”,”WB”]
The following should get displayed
MP
MH
MZ
14. Write a python function generatefibo(n) where n is the limit, using a generator function
Fibonacci (max)( where max is the limit n) that produces Fibonacci series.
15. Write a definition of a method COUNTNOW(PLACES) to find and display those place names,
in which here are more than 7 characters.
For example:
If the list PLACES contains. ["MELBORN","TOKYO","PINKCITY","BEIZING","SUNCITY"]
The following should get displayed : PINKCITY
3. output: 25 4. output: 6
5. output: [0,1] 6. output: 4
[3,2,1,0,1,4]
[0,1,0,1,4]
7. output: 36 8. output: python
easyeasyaesy
9. Output: 33 10. 15
32
53
102
13. Ans def MSEARCH(STATES):
for i in STATES:
if i[0]==’M’:
print(i)
Q1. Which operator is used in the python to import all modules from packages?
(a) . operator
(b) * operator
(c) -> symbol
(d) , operator
Q2. Which file must be part of the folder containing python module file to make it importable
python package?
(a) init.py
(b) ____steup__.py
(c) __init ___.py
(d) (d) setup.py
Q4. Which is the correct command to load just the tempc method from a module called usable?
(a) import usable,tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc
103
SECTION B (2 MARK QUESTION)
Q1. How can you locate environment variable for python to locate the module files imported into a
program?
Q2. What is the output of the following piece of code?
#mod1
def change (a):
b=[x*2 for x in a]
print (b)
#mod2
def change (a) :
b =[x*x for x in a]
print (b)
from mode 1 import change
from mode 2 import change
#main
S= [1,2,3]
Change (s)
Note: Both the modules mod1 and mod 2 are placed in the same program.
(a) [2,4,6] (b) [1,4,9]
(c) [2,4,6][1,4,9] (d) There is a name clash
Q3. What happens when python encounters an import statement in a program? What would happen, if
there is one more important statement for the same module, already imported in the same program?
104
Fill in the blanks for the following code:
1. Math _operation #get the name of the module.
2. print (_______) #output: math_operation
# Add 1and 2
3. print(_______(1,2) ) # output 3
Q2. Consinder the code given in above and on the basis of it, complete the code given below:
# import the subtract function
#from the math_operation module
1.________________________ #subtract 1from 2
2.print(_______(2,1) ) # output : 1
# Import everything from math____operations
3._______________________________
print (subtract (2,1) ) # output:1
print (add (1,1) ) # output:2
105
SECTION B (2 MARK ANSWERS )
Ans 1. Pythonpath command is used for the same. It has a role similar to path. This variable tells the
python interpreter where to locate the module files imported into a program.It should include the
python source library ,directory containing python source code.
Ans 2. (d)
Ans 4. In the “from–import” from of import, the imported identifiers (in this case factorial ()) become
part of the current local namespace and hence their module’s name aren’t specified along with the
module name. Thus, the statement should be:
print( factorial (5) )
Ans 5. There is a name clash. A name clash is a situation when two different entities with the same name
become part of the same scope. Since both the modules have the same function name, there is a
name clash, which is an error..
Ans 4. The possible outputs could be (ii), (iii) (v) and (vi).
The reason being that randint( ) would generate an integer between range 2…4, which is then
raised to power 2.
106
The above program saves a dictionary in binfile.dat and prints it on console after reading it from
the file binfile.dat
QUESTIONS (1 MARK)
Q3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive
Q5. How many file objects would you need to manage the following situations :
(a) To process four files sequentially
(b) To process two sorted files into third file
Q6. When do you think text files should be preferred over binary files?
QUESTIONS (2 MARK)
Q1. Write a single loop to display all the contens of a text file file1.txt after removing leading
and trailing WHITESPACES
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close( )
open('output.txt').read( )
Q2. Read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
if the file contains 'GOOD' before execution, what will be the content of the file after
execution of the code
Q1. Write a user defined function in python that displays the number of lines starting with 'H'in
the file para.txt
Q2. Write a function countmy() in python to read the text file "DATA.TXT" and count the
number of times "my" occurs in the file. For example if the file DATA.TXT contains-"This is
my website. I have diaplayed my preference in the CHOICE section ".-the countmy()
function should display the output as:"my occurs 2 times".
Q3. Write a method in python to read lines from a text file DIARY.TXT and display those lines
which start with the alphabets P.
Q4 write a method in python to read lines from a text file MYNOTES.TXT and display those
lines which start with alphabets 'K'
Q5 write a program to display all the records in a file along with line/record number.
Q6. consider a binary file employee.dat containing details such as
empno:ename:salary(seperator ':') write a python function to display details of those
employees who are earning between 20000 and 30000(both values inclusive)
Q7. write a program that copies a text file "source.txt" onto "target.txt" barring the lines
starting with @ sign.
Ans1. w mode opens a file for writing only. it overwrites if file already exist but 'a mode appends the
existing file from end. It does not overwrites the file
Ans2 binary file are easier and faster than text file.binary files are also used to store binary data such as
images, video files, audio files.
Ans3 f1=open(“c:\school\sample.dat”,’r’)
108
Ans4 d) f.readlines()
Ans5 a)4 b)3
Ans6 Text file should be preferred when we have to save data in text format and security of file is not
important
(2 MARKS QUESTIONS)
Ans1 for line in open(“file1.txt”):
print(line.strip())
Ans2 The file would now contains “Bye”only because when an existing file is openend in write mode .it
truncates the existing data in file .
Ans3 i) Text file
ii) f1.write(“abc”)
Ans4 Line1
Line3
Line 6
Line 4
Ans5 ab and a+b mode
Ans7 No Output
Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer at the
end of file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF and,
thus,print statement prints nothing.
Q1. Sunita writing a program to create a csv file “a.csv” which contain user id and name of the
beneficiary. She has written the following code. As a programmer help her to successfully
execute the program.
import ______________ #Line 1
with open('d:\\a.csv','w') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(['user_id','beneficiary'])
newFileWriter.________________([1,'xyz']) #Line2
newFile.close()
with open('d:\\a.csv','r') as newFile:
newFileReader = csv._______________(newFile) #Line 3
for row in newFileReader:
print (row) #Line 4
newFile.____________ #Line 5
a) Name the module he should import in Line 1
b) Fill in the blank in line 2 to write the row.
c) Fill in the blank in line 3 to read the data from csv file.
d) Write the output while line 4 is executed.
110
e) Fill in the blank in line 5 to close the file.
Q2. MOHIT is writing a program to search a name in a CSV file “MYFILE.csv”. He has written the
following code. As a programmer, help him to successfully execute the given task.
import _________ # Statement 1
f = open("MYFILE.csv", _______) # Statement 2
data = ____________ ( f ) # Statement 3
nm = input("Enter name to be searched: ")
for rec in data:
if rec[0] == nm:
print (rec)
f.________( ) # Statement 4
2. (a) csv.
(b) “r”?
111
(c) data = csv.reader(f)
(d) f.close()
(e) Comma Separated Values
3. def AddCustomer(Customer):
CStake.append(Customer)
if len(CStack)==0:
print (“Empty Stack”)
else:
print (CStack)
4. def DeleteCustomer():
if (CStack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,CStack.pop())