Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

Practice Sheet

Revision Tour, Function, File Handling


M Upadhyay

Page. 1
Python revision tour class 12 – 1 Mark Questions c. dictionary
d. string
[1] Find the invalid identifier from the following: Ans.: b. tuple
a) MyName [10] Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80,
b) True 90). What will be the output of print (tup1 [3:7:2])?
c) 2ndName a. (40,50,60,70,80)
d) My_Name b. (40,50,60,70)
Ans.: b) True and c) 2ndName c. [40,60]
[2] Given the lists L=[1,3,6,82,5,7,11,92] , write the d. (40,60)
output of print(L[2:5]).
Ans.: [6, 82, 5] Ans.: d) (40, 60)
[3] Identify the valid arithmetic operator in Python
from the following. [11] Which of the following operator cannot be used
a) ? with string data type?
b) < a. +
c) ** b. in
d) and c. *
d. /
Ans. c) **
[4] Suppose a tuple T is declared as T = (10, 12, 43, 39), Ans.: d) /
which of the following is incorrect? [12] Consider a tuple tup1 = (10, 15, 25, and 30).
a) print(T[1]) Identify the statement that will result in an error.
b) T[2] = -29 a. print(tup1[2])
c) print(max(T)) b. tup1[2] = 20
d) print(len(T)) c. print(min(tup1))
d. print(len(tup1)
Ans.: b) T[2] = -29
[5] Write a statement in Python to declare a dictionary Ans.: b. tup1[2] = 20
whose keys are 1, 2, 3 and values are Monday, Tuesday [13] Which one of the following is the default
and Wednesday respectively. extension of a Python file?
a. .exe
Ans.: d={1:’Monday’,2:’Tuesday’,3:’Wednesday’} b. .p++
[6] A tuple is declared as T = (2,5,6,9,8) What will be c. .py
the value of sum(T)? d. .p

Ans.: 30 Ans.: c) .py


[7] If the following code is executed, what will be the [14] Which of the following symbol is used in Python
output of the following code? for single-line comment?
name="ComputerSciencewithPython" a. /
print(name[3:10]) b. /*
c. //
Ans. : puterSc d. #
[8] Find the invalid identifier from the following:
a. none Ans.: d) #
b. address [15] Which of these about a dictionary is false?
c. Name a) The values of a dictionary can be accessed using
d. pass keys
Ans.: d. pass b) The keys of a dictionary can be accessed using
[9] Consider a declaration L = (1, ‘Python’, ‘3.14’). values
Which of the following represents the data type of L? c) Dictionaries aren’t ordered
a. list d) Dictionaries are mutable
b. tuple

Page. 2
Ans.: c) Dictionaries aren’t ordered lst1.insert( 2, 3)
[16] What is the output of the following code: print (lst1[-5])
T=(100) a. 2
print(T*2) b. 3
a. Syntax error c. 4
b. (200,) d. 20
c. 200
d. (100,100)
Ans.: b) 3
Ans.: c) 200 Watch this video for a clear understanding:
[17] Identify the output of the following Python [21] Evaluate the following expression and identify the
statements. correct answer.
x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]] 16 – (4 + 2) * 5 + 2**3 * 4
y = x[1][2] a. 54
print(y) b. 46
a. 12.0 c. 18
b. 13.0 d. 32
c. 14.0
d. 15.0
Ans.: c) 18
[22] State True or False “Variable declaration is implicit
Ans. : d) 15.0 in Python.”
[18] Identify the output of the following Python
statements.
x=2 Ans.: True
while x < 9: [23] Which of the following is an invalid datatype in
print(x, end='') Python?
x=x+1 (a) Set
a. 12345678 (b) None
b. 123456789 (c) Integer
c. 2345678 (d) Real
d. 23456789

Ans. : d) Real
Ans.: c) 2345678 [24] Given the following dictionaries :
[19] Identify the output of the following Python dict_exam={"Exam":"AISSCE", "Year":2023}
statements. dict_result={"Total":500, "Pass_Marks":165}
b=1 Which statement will merge the contents of both
for a in range(1, 10, 2): dictionaries?
b += a + 2 a. dict_exam.update(dict_result)
print(b) b. dict_exam + dict_result
a. 31 c. dict_exam.add(dict_result)
b. 33 d. dict_exam.merge(dict_result)
c. 36
d. 39
Ans.: a) dict_exam.update(dict_result)
[25] Consider the given expression:
Ans.: c) 36 not True and False or True
[20] Identify the output of the following Python Which of the following will be the correct output if the
statements. given expression is evaluated?
lst1 = [10, 15, 20, 25, 30] (a) True
lst1.insert( 3, 4) (b) False

Page. 3
(c) NONE a. Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(d) NULL b. Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
c. Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
d. Day={1’monday’,2’tuesday’,3’wednesday’]
Ans..: a) True
[26] Select the correct output of the code: Ans.: a) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
a = "Year 2022 at All the best" [31] Kunj has declared a variable as follows:
a = a.split('2') L=[1,45,’hello’,54.6]
b = a[0] + ". " + a[1] + ". " + a[3] Identify L?
print (b) a. List
(a) Year . 0. at All the best b. Tuple
(b) Year 0. at All the best c. Dictionary
(c) Year . 022. at All the best d. Function
(d) Year . 0. at all the best
Ans.: a) List
[32] Write the output of following:
Ans.: (a) Year . 0. at All the best x = "abcdef"
[27] Which of the following statement(s) would give an i = "a"
error after executing the following code? while i in x:
S="Welcome to class XII" # Statement 1 print(i, end = " ")
print(S) # Statement 2 a. abcdef
S="Thank you" # Statement 3 b. abcde
S[0]= '@' # Statement 4 c. bcde
S=S+"Thank you" # Statement 5 d. infinite loop
(a) Statement 3
(b) Statement 4
(c) Statement 5 Ans.: d. inifinte loop
(d) Statement 4 and 5 [33] Observe the following code written by Rupal. She
has used ++ in place of the exponential operator.
Rewrite the correct code after removing all errors.
Ans.: b) Statement 4 r=3.5,h=2.5
[28] What will the following expression be evaluated to area=2*pi*r*h+2*(r++2)
in Python? print(15.0 / 4 + (8 + 3.0)) print (area)
(a) 14.75 Which of the following operator will replace ++?
(b)14.0 a. //
(c) 15 b. *
(d) 15.5 c. **
d. %

Ans.: a) 14.75
[29] What will be the output of the following code? Ans.: c) **
tup1 = (1,2,[1,2],3) [34] Given is a Python string declaration:
tup1[2][1]=3.14 myexam="@@CBSE Examination 2022@@"
print(tup1) Write the output of: print(myexam[::-2])
a. (1,2,[3.14,2],3) a. @20 otnmx SC@
b. (1,2,[1,3.14],3) b. @@CBSE Examination 2022
c. (1,2,[1,2],3.14) c. @2202 noitanimaxE ESBC
d. Error Message d. None of these

Ans.: b) (1, 2, [1, 3.14], 3)


[30] Which is the correct form of declaration of Ans. : a. @20 otnmx SC@
dictionary? [35] Write the output of the code given below:

Page. 4
my_dict = {"name": "Aman", "age": 26} print (L)
my_dict['age'] = 27 a) [10, 20, 30, 40, 50, 5]
my_dict['address'] = "Delhi" b) [15, 25, 35, 45,55]
print(my_dict.items()) c) [5,10, 20, 30, 40, 50]
a. dict_items([(‘name’, ‘Aman’), (‘age’, 27), (‘address’, d) Error
‘Delhi’)])
b. dict_items([(‘name’,’Aman’),(‘age’,26)])
c. dict_items({name:’Aman’,age:27,’address’:’Delhi’}) Ans.: d) Error
d. Error Message [41] What will be the output for the following Python
statements:
D={ "AMIT" :90, "RESHMA" : 96,”SUKHBIR”:92,
Ans.: a) dict_items([(‘name’, ‘Aman’), (‘age’, 27), “JOHN”:95}
(‘address’, ‘Delhi’)]) print(“JOHN” in D, 90 in D, sep=’#’)
Watch this video for more understanding: a) True#False
[36] For the given declaration in Python as b) False#True
s=’WELCOME’: c) True#True
Which of the following will be the correct output of d) False#False
print(S[1::2])?
a) WEL Ans.: a) True#False
b) COME [42] Nitish has declared a tuple T in Python as follows:
c) WLOE T = (10, 20, 30)
d) ECM Now, he wants to insert an element 40 after these
three elements of T so that the tuple may contain
Ans.:d) ECM (10,20, 30, 40).
[37] Which of the following is the correct output for Which of the following statements shall Nitish write to
the execution of the following Python statement? accomplish the above task?
print (5 + 3 ** 2 /2) a) T = T + 40
a) 82 b) T = T+ (40)
b) 9.5 c) T = T + (40,)
c) 8.0 d) Nitish cannot insert 40 into the tuple since Tuples
d) 32.0 are immutable

Ans.: b) 9.5 Ans.: d) Nisitsh cannot insert 40 into the tuple since
[38] Which of the following is not a Tuple in Python? Tuples are immutable
a) (1,2,3) [43] Identify the output of the following Python
b) (“One”,”Two”, “Three”) statements:
c) (10,) L = []
d) (“one”) for i in range (4):
L.append (2*i+1)
Ans.: d) (“One”) print (L[::-1])
[39] Which of the following is not a valid Python string a) [4,3,2,1]
operation? b) [9,7,5,3]
a) ‘Welcome’ + ’10’ c) [7,5,3,1]
b) Welcome’ * 10 d) [1,2,3,4]
c) ‘Welcome’ * 10.0
d) “10” + ‘Welcome” Ans.: c) [7,5,3,1]

Ans.: c) ‘Welcome’*10.0 [44] Identify the output of the following Python


[40] What will be the output for the following Python statements:
statements? D={}
L =[10, 20, 30, 40, 50] T= ("ZEESHAN", "NISHANT", "GURMEET" , "LISA")
L=L+5 for i in range (1,5):

Page. 5
D[i]=T[i-1]
print (D) Ans.: c) [2,3]
a) {“ZEESHAN”, “NISHANT”, “GURMEET”,”LISA”} [48] What will be the output of the following Python
b) “ZEESHAN”, “NISHANT”, ” GURMEET”,”LISA” code ?
c) [1, “ZEESHAN”], [2, “NISHANT”], [3, “GURMEET”], L = [10, 201]
[4,” LISA”] L1=[30,40]
d) {1:” ZEESHAN” , 2:”NISHANT”, 3: “GURMEET” , 4: L2=[50,60]
“LISA”} L.append (L1)
L.extend (L2)
print (L)
Ans.: d) {1:” ZEESHAN” , 2:”NISHANT”, 3: “GURMEET” , a) [60, 50, 40, 30, 20, 10]
4: “LISA”} b) [10, 20, 30, 40, 50, 60]
[45] Identify the output of the following Python c) [10, 20, 30, 40, [50, 60]]
statements : d) [10, 20, [30, 40], 50, 60]
L1, L2= [10, 15, 20, 25], []
for i in range (len (L1)):
L2. insert( i,Ll.pop ()) Ans. : d) [10, 20, [30, 40], 50, 60]
print (LI, L2, sep="&" ) [49] Find and write the output of the following python
a) [] & [25, 20, 15, 10] code :
b) [10, 15, 20, 25] & [25, 20, 15,10] for Name in ['John', 'Garima','Seema','Karan']:
c) [10, 15, 20, 25]&[10, 15, 20, 25] print(Name)
d) [25, 20, 15, 10]&[] if Name[0]=='S':
break
else:
Ans.: a) [] & [25,20,15,10] print ('Completed!')
[46] Which of the following option can be the output print('Weldone!')
for the following Python code? a) John
Ll= [10,20,30,20,10] Completed
L2=[] Garima
for i in Ll: Completed
if i not in L2: Seema Completed
L2.append (i) b) John
print (Ll, L2,sep="&") Completed!
a) [10,20,30,20,10]&[10,20,30, 20,10] Garima
b) [10,20,30,20,10] [10,20,30,20,10]& Completed!
c) [10,20,30,20,10]&[30,20,10] Seema
d) [10,20,30,20,10]&[10,20,30] Weldone!
c) John Completed!
Garima Completed!
Ans.: d) [10,20,30,20,10]&[10,20,30] Seema Weldone!
[47] Identify the output of the following Python code: d) Error
D={1:"One", 2:"Two", 3: "Three"}
L=[] Answer b)
for K,V in D. items (): John
if V[0l=="T": Completed!
L.append (K) Garima
print (L) Completed!
a) [1,2,3] Seema
b) [“One”, “Two”, “Three”] Weldone!
c) [2,3]
d) [“Two”, “Three”]
Ans. b)

Page. 6
John
Completed! Ans.:
Garima 1) /= : Assignment Operator
Completed! 2) ==: Relational Operator
Seema 3) =: Assignment Operator
Weldone! 4) and: Logical Operator
[50] What will be the output of the following Python [4] Identify only arithmetic operators from the
code? following:
S="UVW" ;L=[10,20,301] //=,//,**,==,%,+
D={}
N=len (S) Ans.:
for I in range (N): //, **, %, +
D[I] = S[I] [5] Yashvi has given the following symbols and word to
for K,V in D.items (): identify which types of tokens are they, help her to
print (K,V, sep="*" ,end="") identify them:
a) U*10,V*20,W*30, If
b) 10*U, 20*v, 30*W, r_no
c) 10,20,30,u*v*w* True
d) Error in

Ans.:b) 10*U,20*V,30*W, Ans.:


Watch this video for more understanding: 1) If: identifier
Python revision tour class 12 – 2 Marks Questions 2) r_no: identifier
[1] What do you understand by the term Iteration? 3) True: Boolean Literal, Keyword
Write the types of iterative statements supported by 4) in: Membership operator, Keyword
python. [6] Rewrite the following code after removing errors:
30=To
for i in range(0,To)
Ans. : Term iteration refers to repeating some IF i%4==0
statements in execution based on certain conditions. If print (i*4) -
the condition is evaluated to be false, the iteration will Else
be terminated. print (i+3)
It is also known as a loop. Ans.:
There are two types of iterative statements supported To=30
by python. for i in range(0,To):
1) while if i%4==0:
2) for print(i*4)
[2] What is a dictionary? How to create a dictionary in else:
python? print(i+3)
[7] Find the output for the following:
Ans.: Dictionary is one of the data types created in l = [6 , 3 , 8 , 10 , 4 , 6 , 7]
python. It contains a key:value pair. print( '@', l[3] - l[2])
The keys are identical and the values are different. for i in range (len(l)-1,-1,-2) :
To create a dictionary in python, follow this syntax: print( '@',l[i],end='' )
dict_obj={key1:val1,key2:val2,…..}
Example: Ans.:
d={‘Name’:’Jayesh’,’From’:’Bharuch’,’Age’:40} @2
[3] Write type of operators from the following: @ 7@ 4@ 8@ 6
/= [8] Evaluate the following expressions:
== a) 6 * 3 + 4**2 // 5 – 8
= b) 10 > 5 and 7 > 12 or not 18 > 3
and

Page. 7
elif (s[i] >= 'n' and s[i] <= 'z'):
Ans.: m = m +s[i-1]
a) 6 * 3 + 4 **2 // 5 – 8 elif (s[i].isupper()):
= 6 * 3 + 16 // 5 – 8 m = m + s[i].lower()
= 18 + 16 // 5 -8 else:
=18 + 3 – 8 m = m +'&'
= 21-8 print(m)
= 13
b) 10 > 5 and 7 > 12 or not 18 > 3
= True and False or False Ans.: sELCcME&Cc
= False or False [12] Find and write the output of the following python
= False code :
[9] Rewrite the following code in Python after for Name in ['John', 'Garima','Seema','Karan']:
removing all syntax error(s). Underline each correction print(Name)
done in the code. if Name[0]=='S':
Value=30 break
for VAL in range(0,Value) else:
If val%4==0: print('Completed!')
print (VAL*4) print('Weldone!')
Elseif val%5==0:
print (VAL+3)
else Ans.:
print(VAL+10) John
Ans: Completed!
Value=30 Garima
for VAL in range(0,Value): Completed!
if VAL%4==0: Seema
print (VAL*4) Weldone!
elif VAL%5==0: [13] Write a program in python to display the elements
print (VAL+3) of list twice, if it is a number and display the element
else: terminated with ‘*’ if it is not a number. For example, if
print(VAL+10) the content of list is as follows :
[10] Predict the output of the Python code given MyList=[‘RAMAN’,’21’,’YOGRAJ’,’3′,’TARA’]
below: The output should be
tuple1 = (11, 22, 33, 44, 55 ,66) RAMAN*
list1 =list(tuple1) 2121
new_list = [] YOGRAJ*
for i in list1: 33
if i%2==0: TARA*
new_list.append(i) Ans.:
new_tuple = tuple(new_list) MyList=['RAMAN','21','YOGRAJ','3','TARA']
print(new_tuple) for i in MyList:
if i.isdigit():
print(i*2)
Ans.: Ans.: (22, 44, 66) else:
[11] Predict the output of the code given below: print(i+'*')
s="welcome2cs"
n = len(s) [14] Rewrite the following code in Python after
m="" removing all syntax errors. Underline the corrections.
for i in range(0, n): for Name in [Ramesh, Suraj, Priya]
if (s[i] >= 'a' and s[i] <= 'm'): IF Name[0]=’S’:
m = m +s[i].upper() print(Name)

Page. 8
Ans.: Val = int(Textl[I])
for Name in [Ramesh, Suraj, Priya]: Val = Val + 1
if Name[0]==’S’: Text2=Text2 + str(Val)
print(Name) elif Textl[I]>="A" and Textl[I] <="Z":
[14] Find the output of the following: Text2=Text2 + (Text1[I+1])
values = [10,20,30,40] else :
for v in values: Text2=Text2 + "*"
for i in range(1, v%9): I=I+1
print(i,’*’,end=’’) print(Text2)
print()

Ans.: SCE *3134


Ans.: [18] Write the names of any four data types available
1* in Python.
1 *2 *
1 *2 *3 *
[15] Find and write the output of the following Python Ans.:
code : 1 Integer
Data = ["P",20,"R",10,"S",30] 2 float
Times = 0 3 string
Alpha = "" 4. Boolean
Add = 0 [19] Rewrite the following code in python after
for C in range(1,6,2): removing all syntax error(s). Underline each correction
Times = Times + C done in the code.
Alpha = Alpha + Data[C-1]+"$" 250 = Number
Add = Add + Data[C] WHILE Number<=1000:
print (Times,Add,Alpha) if Number=>750:
Ans.: 9 60 P$R$S$ print Number
Number=Number+100
[16] Rewrite the following code in python after else
removing all syntax error(s). Underline each correction print Number*2
done in the code. Number=Number+50
25=Val Ans.:
for I in the range(0,Val) Number = 250
if I%2==0: while Number<=1000:
print I+1 if Number=>750:
Else: print(Number)
print I–1 Number=Number+100
Ans.: else:
Val=25 print(Number*2)
for I in the range(0,Val): Number=Number+50
if I%2==0: [20] Find and write the output of the following python
print(I+1) code :
else: Msg1="WeLcOME"
print(I–1) Msg2="GUeSTs"
[17] Find and write the output of the following python Msg3=""
code : for I in range(0,len(Msg2)+1):
Text1="SSCE 2023" if Msg1[I]>="A" and Msg1[I]<="M":
Text2=" " Msg3=Msg3+Msg1[I]
I=0 elif Msg1[I]>="N" and Msg1[I]<="Z":
while I<len(Text1): Msg3=Msg3+Msg2[I]
if Textl[I]>="0" and Textl[I]<="9": else:

Page. 9
Msg3=Msg3+"*" else:
print(Msg3) value = value - N
print(value, end="#")
display(20)
Ans.: G*L*TME print(value)
Watch this video for more understanding: a. 50#50
Functions computer science class 12 previous year b. 50#5
questions c. 50#30
Now in the next section of computer science class 12 d. 5#50#
previous year questions I am going to cover questions
from Functions. From this topic functions 1 mark, 2
marks, 3 marks and 4 marks will be asked. Ans.:b) 50#5
Let us begin with 1 marks questions. Here we go [5] What will be the output of the following code?
Functions Class 12 Computer Science 1 Marks import random
Questions List=["Delhi","Mumbai","Chennai","Kolkata"]
[1] Which of the following function header is correct? for y in range(4):
a. def cal_si(p=100, r, t=2) x = random.randint(1,3)
b. def cal_si(p=100, r=8, t) print(List[x],end="#")
c. def cal_si(p, r=8, t) a. Delhi#Mumbai#Chennai#Kolkata#
d. def cal_si(p, r=8, t=2) b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
Ans.: d) def cal_si(p, r=8, t=2)
[2] Which of the following is the correct way to call a
function? Ans.: b) Mumbai#Chennai#Kolkata#Mumbai#
a. my_func() [6] What is the output of the following code snippet?
b. def my_func() def ChangeVal(M,N):
c. return my_func for i in range(N):
d. call my_func() if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
Ans.: a) my_func() M[i]//=3
[3] What will be the output of the following code? L = [25,8,75,12]
def my_func(var1=100, var2=200): ChangeVal(L,4)
var1+=10 for i in L:
var2 = var2 - 10 print(i,end="#")
return var1+var2 a) 5#8#15#4#
print(my_func(50),my_func()) b) 5#8#5#4#
a. 100 200 c) 5#8#15#14#
b. 150 300 d) 5#18#15#4#
c. 250 75
d. 250 300
Ans.: b) 5#8#5#4
[7] Find the output of the following code:
Ans. d) 250 300 def convert():
[4] What will be the output of the following code? Name="PythoN3.10"
value = 50 R=""
def display(N): for x in range(len(Name)):
global value if Name[x].isupper():
value = 25 R=R+Name[x].lower()
if N%7==0: elif Name[x].islower():
value = value + N R=R+Name[x].upper()

Page. 10
elif Name[x].isdigit(): (c) A is True but R is False
R=R+Name[x-1] (d) A is false but R is True
else:
R=R+"#"
print(R) Ans.: (c) A is True but R is False
a. pYTHOn##10 [11] Which of the following is not correct in the context
b. pYTHOnN#1 of Positional and Default parameters in Python
c. pYTHOn#.1 functions?
d. pYTHOnN#.1 a) Default parameters must occur to the right of
Positional parameters
b) Positional parameters must occur to the right of
Ans.: d. pYTHOnN#.1 Default parameters
[8] What will be the output of the following code? c) Positional parameters must occur to the left of
x=3 Default parameters
def myfunc(): d) All parameters to the right of a Default parameter
global x must also have default values
x+=2
print(x, end=' ')
print(x, end=' ') Ans.: b) Postional parameters must occur to the right
myfunc() of default parameters
print(x, end=' ') [12] For a function header as follows:
a. 3 3 3 def Calc (X, Y=20)
b. 3 4 5 Which of the following function calls will give an Error?
c. 3 3 5 a) Calc (15,25)
d. 3 5 5 b) Calc (X=15,Y=25)
c) Calc (Y=25)
d) Calc (X=25)
Ans.: d) 3 5 5
[9] What will be the output of the following Python
code? Ans.: c) Calc(Y=25)
def add (num1, num2): [13] Which of the following is not correct in the context
sum = num1 + num2 of scope of variables ?
sum = add(20,30) a) global keyword is used to change the value of a
print(sum) global variable in a local scope
a. 50 b) local keyword is used to change the value of a local
b. 0 variable in a global scope
c. Null c) global variables can be accessed without using the
d. None global keyword in a local scope
d) local variables cannot be used outside its scope

Ans.: d) None
[10] Assertion (A):- If the arguments in function call Ans.: b) local keyword is used to change the values of a
statement match the number and order of arguments local variable in a global scope
as defined in the function definition, such arguments [14] Which of the following is not a function/method of
are called positional arguments. the random module in Python?
Reasoning (R):- During a function call, the argument list a) randfloat ()
first contains default argument(s) followed by b) randint ()
positional argument(s). c) random()
(a) Both A and R are true and R is the correct d) randrange ()
explanation for A
(b) Both A and R are true and R is not the correct
explanation for A Ans.:a) randfloat()

Page. 11
[15] Identify the output of the following Python d) LE*NO*ON*
statements:
S =”GoOD MORNING”
print (S.capitalize (),s.title () ,end=”! “) Ans.: a) EC*NB*IS*
(a) GOOD MORNING !Good morning [19] What will be the output of the following Python
(b) Good Morning!Good morning code ?
(c) Good morning! Good Morning! def FunStr (S):
(d) God morning Good Morning! T=''
for i in S:
if i.isdigit ():
Ans.: d) Good morning Good Morning! T = T +i
[16] What will be the output of the following Python return T
code? X= "PYTHON 3.9"
S="WELcOME" Y = FunStr (X)
def Change (T) : print (X, Y, sep="*")
T="HELLO" a) PYTHON 3.9
print (T, end='@') b) PYTHON 3.9*3.9
Change (S) c) PYTHON 3.9*39
print (S) d) Error
a) WELcOME@ HELLO
b) HELLO@HELLO
c) HELLO@WELcOME Ans. : c) PYTHON 3.9*39
d) WELCOME@WELCOME [20] What will be the output of the following Python
code?
V=50
Ans.: c) HELLO@WELcOME def Change (N):
[17] Identify the correct possible output for the global V
following Python code : V, N = N, V
import random print (V, N, sep="#",end="@")
for N in range (2,5,2): Change (20)
print (random. randrange (1,N) ,end="#") print (V)
a) 1#3#5# a) 20#50@20
b) 2#3# b) 50@20#50
c) 1#4# c) 50#50#50
d) 1#3# d) 20@50#20

Ans.: d) 1#3# Ans.: a) 20#50@20


[18] What are the possible outcome(s) executed from [21] What is the output of the following Python code
the following code? Also specify the maximum and ?ff
minimum values that can be assigned to variable def ListChange () :
COUNT. for i in range (len (L)):
TEXT="CBSEONLINE" if L[i]%2 == 0:
COUNT=random.randint(0,3) L[i]=L[i]*2
C=9 if L[i]%3==0:
while TEXT[C]!='L': L[i]=L[i]*3
print (TEXT[C]+TEXT[COUNT]+'*', end='') else:
COUNT=COUNT+1 L[i]=L[ij*5
C=C-1 L = [2,6,9,10]
a) EC*NB*IS* ListChange ()
b) NS*IE*LO* for i in L:
c) ES*NE*IO* print (i,end="#")

Page. 12
a) 4#12#27#20# Functions Class 12 Computer Science 2 Marks
b) 20#36#27#100# Questions
c) 6#18#27#50# [1] Rewrite the following code in python after
d) Error removing all syntax error(s). Underline each correction
done in the code.
def Sum(Count) #Method to find sum
Ans. : b) 20#36#27#100# S=0
[22] What will be the output of the following Python for I in Range(1,Count+1):
code? S+=I
V = 25 RETURN S
def Fun (Ch): print (Sum[2]) #Function Call
V=50 print (Sum[5])
print (V, end=Ch) Ans.:
V *= 2 def Sum(Count): #Method to find sum
print (V, end=Ch) S=0
print (V, end="*") for I in range(1,Count+1):
Fun ("!") S+=I
print (V) return S
a) 25*50! 100 !25 print (Sum(2)) #Function Call
b) 50*100 !100!100 print (Sum(5))
c) 25*50! 100!100 [2] Find the output for the following:
d) Error def fun(s):
k=len(s)
m=" "
Ans.: a) 25*50! 100 !25 for i in range(0,k):
[23] Predict the output of the Python code given if(s[i].isupper()):
below: m=m+s[i].lower()
def Diff(N1,N2): elif s[i].isalpha():
if N1>N2: m=m+s[i].upper()
return N1-N2 else:
else: m=m+'#'
return N2-N1 print(m)
NUM= [10,23,14,54,32] fun('BoardExam@2K23')
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1] Ans. :
print(Diff(A,B),'#', end=' ') bOARDeXAM##k##
a) 22 # 40 # 9 # 13 # [3] Find and write the output of the following python
b) 9 # 22 # 13 # 53 # code :
c) 9 # -30 # 22 # 22 def Changer(P,Q=10):
d) Error P=P/Q
Q=P%Q
print(P,"#",Q)
Ans. : a) 22 # 40 # 9 # 13 return P
Watch this video for more understnading: A=200
In the next section of computer science class 12 B=20
previous year questions I am going to cover 2 marks A=Changer(A,B)
questions from functions class 12 computer science. print( A,"$",B)
This section includes questions such as definitions, B=Changer(B)
differetiates, output and error based questions. Here print( A,"$",B)
we go! A=Changer(A)
print (A,"$",B)

Page. 13
Example:
a=4
Ans.: def add():
10.0 # 10.0 global a
10.0 $ 20 return a+5
2.0 # 2.0 print(add())
10.0 $ 2.0 [8] Find and write the output of the following Python
1.0 # 1.0 code:
1.0 $ 2.0 def Display(str):
[4] What possible outputs(s) are expected to be m=""
displayed on screen at the time of execution of the for i in range(0,len(str)):
program from the following code? Also specify the if(str[i].isupper()):
maximum values that can be assigned to each of the m=m+str[i].lower()
variables FROM and TO. elif str[i].islower():
import random m=m+str[i].upper()
AR=[20,30,40,50,60,70] else:
FROM=random.randint(1,3) if i%2==0:
TO=random.randint(2,4) m=m+str[i-1]
for K in range(FROM,TO+1): else:
print (AR[K],end=”#“) m=m+"#"
(i) 10#40#70# print(m)
(ii) 30#40#50# Display('Fun@Python3.0')
(iii) 50#60#70#
(iv) 40#50#70#
Ans.: fUN#pYTHONn#.
[9] Rao has written a code to input a number and check
Ans.: whether it is prime or not. His code is having errors.
Output: (ii) 30#40#50# Rewrite the correct code and underline the corrections
The maximum value for from is : 3 and 2 is : 4 made.
[6] Differentiate between actual parameter(s) and def prime():
formal parameter(s) with a suitable example for each. n=int(input("Enter number to check :: ")
Ans.: for i in range (2, n//2):
if n%i=0:
Actual Parameters Formal Parameters print("Number is not prime \n")
break
Can be specified in the Can be specified in else:
function calls function headers print("Number is prime \n’)
Ans.:
Can be either variable or def prime():
Can be a variable
constant or any n=int(input("Enter number to check :: "))
only
expression for i in range (2, n//2):
if n%i==0:
Ex. a=1 Ex.: print("Number is not prime \n")
b=3 def add(a,b): # break
add(a,b) # Actual Formal Parameter else:
Parameter return a + b print("Number is prime \n")
break
[7] Explain the use of a global keyword used in a [10] Write the output of the code given below:
function with the help of a suitable example. p=5
def sum(q,r=2):
global p
Ans.: The global keyword is used to access the variable p=r+q**2
written in top level statement or outside the function.
Page. 14
print(p, end= '#') call()
a=10
b=5
sum(a,b) Ans.: 15
sum(r=5,q=1) [14] What do you understand by local and global scope
of variables? How can you access a global variable
inside the function, if function has a variable with same
Ans.: 105#6# name.
[11] Write a Python method/function SwapParts(Word)
to swap the first part and the second part of the string
Word. Assuming there are an even number of letters in Ans.:
the string Word. The function should finally display the Local scope refers to access of variable withing a
changed Word. function. A variable declared inside a function having
For example : limited scope of access inside function only.
If Word = ‘Elephant’ then the function should convert Global scopre refers to access of variable thorughout
Word to ‘hantElep’ and display the output as: the program. A variable declared outside function in
Changed Word is hantElep top level statement i.e. __main__ is called global
Ans.: variable.
def SwapParts(word): In pyton global keyword is used to define global
l=len(word) variable.
hf=l//2 [15] Write the definition of a method/function
nw='' AddOddEven(VALUES) to display sum of odd and even
if l%2==0: values separately from the list of VALUES.
nw=word[hf:]+word[:hf] For example :
return nw If the VALUES contain [15, 26, 37, 10, 22, 13]
w=input("Enter the word:") The function should display
print(SwapParts(w)) Even Sum: 58
[12] Write a Python method/function Noun2Adj(Word) Odd Sum: 65
which checks if the string Word ends with the letter ‘y’. Ans.:
If so, it replaces the last letter ‘y’ with the string ‘iful’ def AddOddEven(VALUES):
and then displays the changed Word. For example if esum=0
the Word is “Beauty”, then the Word should be osum=0
changed to “Beautiful”. Otherwise it should display for i in VALUES:
Not ending with “y”. if i%2==0:
Ans.: esum+=i
def Nount2Adj(word): else:
nw='' osum+=i
rw='iful' print("Even Sum:",esum)
if word.endswith('y'): print("Odd Sum:",osum)
word=word[:-1]+rw n=int(input("Enter no. of elements:"))
else: l=[]
print("Word not ending with y.") for i in range(n):
return word v=int(input("Enter Value to add:"))
w=input("Enter word endwith y") l.append(v)
print(Nount2Adj(w)) AddOddEven(l)
[13] Write the output for the following: Functions Class 12 Computer Science 3 Marks
a=10 Questions
def call(): Now its turns to 3 marks questions from the topic
global a function computer science class 12. Mostly in 3 marks
a=15 questions, output and error-based questions as well as
b=20 write-a-function type questions will come. So here we
print(a) go!

Page. 15
[1] Write a method in python to find and display the [4] Write a python method/function Scroller(Lineup) to
composite numbers between 2 to N. Pass N as an scroll all the elements of a list Lineup by one element
argument to the method. ahead and move the last element to the first. Also,
Ans.: display the changed content of the list. For Example: If
def dis_CompoSite(N): the list has the following values in it [25,30,90,110,16]
print("Composite Numbers between 2 to N:",end='') After changing the list content should be displayed as
for i in range(2,N+1): [16,25,30,90,110]
count=0 Ans.:
for j in range(2,i//2+1): def Scroller(Lineup):
if i%j==0: Lineup=Lineup[-1:]+Lineup[:-1]
count+=1 print(str(Lineup))
if count>=1: n=int(input("Enter the value:"))
print(i,end=',') l=[]
n=int(input("Enter the value:")) for i in range(n):
dis_CompoSite(n) v=int(input("Enter Name to add:"))
[2] Write the definition of a method/function l.append(v)
TenTimesEven(VALUES) to add and display the sum of Scroller(l)
ten times the even values present in the list of [5] Write a python method/function
VALUES. REVERSAR(Number) to find a new number Reverse
For example, If the Nums contain [5,2,3,6,3,4] from Number with each of the digits of Number in
The method/function should display Sum: 120 reversed order and display the content of Reverse on
Ans.: screen.
def TenTimesEven(VALUES): For Example:
s=0 If the value of Number is 3451
for i in VALUES: The method/function should be displayed as 1543
if i%2==0: Ans.:
s=s+(i*10) def REVERSAR(number):
print("Sum:",s) r=0
n=int(input("Enter the value:")) while number!=0:
l=[] r=(number%10)+(r*10)
for i in range(n): number//=10
v=int(input("Enter value:")) print("Reverse:",r)
l.append(v) n=int(input("Enter the value:"))
TenTimesEven(l) REVERSAR(n)
[3] Write the definition of a method/function [6] Write the definition of a method/function
EndingA(Names) to search and display those strings HowMany(ID,Val) to count and display number of
from the list of Names, which are ending with ‘A’. times the value of Val is present in the list ID.
For example, If the Names contain For example : If the ID
[“JAYA”,”KAREEM”,”TARUNA”,”LOVISH”] contains [115,122,137,110,122,113] and Val contains
The method/function should display JAYA TARUNA 122
Ans.: The function should display 122 found 2 Times
def EndingA(names): Ans.:
for i in names: def HowMany(ID,val):
if i.endswith('a'): c=0
print(i,end=' ') for i in ID:
n=int(input("Enter the value:")) if i==val:
l=[] c+=1
for i in range(n): print(val, "found ",c," time")
v=input("Enter Name to add:") n=int(input("Enter total no. of values:"))
l.append(v) s=int(input("Enter number to search:"))
EndingA(l) l=[]
for i in range(n):

Page. 16
v=int(input("Enter Number to add:")) print( P,"#",Q)
l.append(v) return (P)
HowMany(l,s) R=150
[7] Write a python method/function S=100
Swapper(Numbers) to swap the first half of the content R=Change(R,S)
of a list of Numbers with the second half of the content print(R,"#",S)
of the list of Numbers and display the swapped values. S=Change(S)
Note : Assuming that the list has even number of Ans.;
values in it. 250 # 150
For example : 250 # 100
If the list Numbers contains [35,67,89,23,12,45] 130 # 100
After swapping the list content should be displayed as [10] Write a function LShift(Arr,n) in Python, which
[23,12,45,35,67,89] accepts a list Arr of numbers and n is a numeric value
Ans.: by which all elements of the list are shifted to left.
def swapper(Numbers): Sample Input Data of the list Arr= [ 10,20,30,40,12,11],
if len(Numbers)%2 == 0: n=2
start = 0 Output Arr = [30,40,12,11,10,20]
else: Ans.:
start = 1 def Lshift(Arr,n):
hf = len(Numbers)//2 print(Arr[n:]+Arr[:n])
for i in range(hf): l=[]
temp = Numbers[i] m=int(input("Enter no. of elements"))
Numbers[i] = Numbers[i+hf+start] n=int(input("Enter no. shift elements:"))
Numbers[i+hf+start] = temp for i in range(m):
n=int(input("Enter no. of elements:")) v=int(input("Enter value to add into the list:"))
l=[] l.append(v)
for i in range(n): Lshift(l,n)
v=int(input("Enter value to append:")) [11] Write a function INDEX_LIST(L), where L is the list
l.append(v) of elements passed as argument to the function. The
swapper(l) function returns another list named ‘indexList’ that
print(l) stores the indices of all Non-Zero Elements of L.
[8] Write a python method/function Count3and7(N) to For example: If L contains [12,4,0,11,0,6]
find and display the count of all those numbers which The indexList will have – [0,1,3,5]
are between 1 and N, which are either divisible by 3 or Ans.:
by 7. def index_list(L):
For example : il=[]
If the value of N is 15 for i in range(len(L)):
The sum should be displayed as 7 (as 3,6,7,9,12,14,15 if L[i]!=0:
in between 1 to 15 are either divisible by 3 or 7) il.append(i)
Ans.: return il
def Count3and7(N): l=[]
c=0 n=int(input("Enter no. of elements"))
for i in range(1,N+1): for i in range(n):
if i%3==0 or i%7==0: v=int(input("Enter value to add into the list:"))
c+=1 l.append(v)
print("Numbers divisible by 3 and 7 are:",c) print(index_list(l))
n=int(input("Enter a number:")) [12] Write the output of the following:
Count3and7(n) def Convert(X=45,Y=30) :
[9] Find the output for the following: X=X+Y Y=X–Y
def Change(P ,Q=30): print(X,"&",Y)
P=P+Q return X
Q=P-Q A=250

Page. 17
B=150 The mouse went up the clock
A=Convert(A,B) F = open ("Rhymes. txt")
print (A,"&",B) L = F. readlines ()
B=Convert(B) X = ["the", "ock"]
print(A,"&",B) for i in L:
A=Convert(A) for W in i.split () :
print(A,"&",B) if W in X:
Ans.: print (W, end = "*")
400 & 250 a) the*
400 & 150 b) Dock*The*the*clock*
180 & 150 c) Dock*the*clock*
400 & 180 d) Error
430 & 400
430 & 180
That’s all from topic function computer science class 12 Ans.: a) the*
questions asked in the previous year’s board exams. [3] Suppose the content of “Rhymes.txt” is:
Now let us move ahead with the next topic data file Good Morning Madam
handling. Here we go! What will be the output of the following Python code?
Data file handling computer science class 12 previous F = open ("Rhymes.txt")
year questions L = F.read ().split ()
Data file handling computer science class 12 is another for W in L:
important topic in the curriculum of computer science. if W.lower () == W[::-1].lower ():
From this chapter 1 mark, 2 marks, 3 marks, 4 marks print (W)
and 5 marks questions were asked in board exams. So a) Good
let us see the questions asked in the previous year’s b) Morning
board exam. Let’s begin! c) Madam
Data file handling 1 mark questions computer science d) Error
class 12
[1] Consider the following directory structure.
The link ed image cannot be display ed. The file may hav e been mov ed, renamed, or deleted. Verify that the link points to the correct file and location.

Ans.: c) Madam
[4] Suppose the content of “Rhymes.txt” is:
One, two, three, four, five
Once. I caught a fish alive.
What will be the output of the following Python code?
F = open ("Rhymes.txt")
S = F.read ()
print (S.count('e',20))
a) 20
b) 1
c) 3
Suppose the present working directory is MyCompany. d) 6
What will be the relative path of the file
Transactions.Dat?
a) MyCompany/Transactions.Dat Ans.: c) 3
b) MyCompany/Accounts/Transactions.Dat [5] Suppose the content of “Rhymes.txt” is:
c) Accounts/Transactions.Dat Baa baa black sheep
d) ../Transactions.Dat have you any wool?
What will be the output of the following Python code?
F = open ("Rhymes.txt")
Ans.: c) Accounts/Transactions.Dat S = F.read ()
[2] Suppose the content of “Rhymes.txt” is: L = S.split ()
Hickory Dickory Dock for i in L:

Page. 18
if len (i)%3!=0: b) quit talking and begin doing
print (i, end= " ") c) The way to get started is to quit talking and begin
a) Baa baa you any doing
b) black have wool? d) gniod nigeb dna gniklat tiuq ot si detrats teg ot yaw
c) black sheep, have wool? ehT
d) Error
[6] Suppose the content of a text file “Rhymes.txt” is as
follows: Ans.: b) quit talking and begin doing
Jack & Jill [10] Which of the following is the default character for
went up the hill the newline parameter for a csv file object opened in
What will be the output of the following Python code ? write mode in Python IDLE ?
F = open ("Rhymes.txt") a) \n
L = F.readlines () b) \t
for i in L: c) ,
S=i.split() d) ;
print (len (S) ,end="#")
a) 2#4#
b) 3#4# Ans.: a) \n
c) 2# [11] If the following statement is used to read the
d) 7# contents of a textfile object F: X-F.readlines( )
Which of the following is the correct data type of x?
a) list
Ans.: 3#4# b) dictionary
[7] Which of the following function is used with the csv c) string
module in Python to read of the contents a csv file into d) tuple
an object?
a) readrow()
b) readrows() Ans.: a) list
c) reader() [12] Which of the following is the correct expansion of
d) load() CSV ?
”Show_Answer” a) Comma Separated Values
b) Centrally Secured Values
Ans.: c) reader() c) Computerised Secured Values
[8] Which of the following Python modules is imported d) Comma Secured Values
to store and retrieve objects using the process of
serialization and deserialization?
a) csv Ans.: a) Comma Separated Values
b) binary [13] What is the significance of the seek() method?
c) math a) It seeks the absolute path of the file
d) pickle b) It tells the current byte position of the file pointer
within the file
c) It places the file pointer at the desired offset within
Ans.: d) pickle the file
[9] Suppose the content of a text file Notes.txt is: d) It seeks the entire content of the file
The way to get started is to quit talking and begin ”Show_Answer”
doing
What will be the output of the following Python code? Ans.: c) It places the file pointer at the desired offset
F = open ("Rhymes.txt") within the file
F.seek (29) [14] Which of the following statement is incorrect in
S= F.read () the context of pickled binary files?
print (S) a) csv module is used for reading and writing objects in
a) The way to get started is to binary files

Page. 19
b) pickle module is used for reading and writing objects a) We can write content into text file opened using ‘w’
in binary files mode
c) load () of the pickle module is used to read objects b) We can write content into text file opened using
d) dump () of the pickle module is used to write objects ‘w+’ mode
c) We can write content into text file opened using ‘r’
mode
Ans.: a) csv module is used for reading and writing d) We can write content into text file opened using ‘r+’
objects in binary files mode
[15] Which of the following option is the correct usage
for the tell() of a file object?
a) It places the file pointer at the desired offset in a file Ans.: c) We can write content into text file opened
b) It returns the entire content of a file using ‘r’ mode
c)It returns the byte position of the file pointer as an [20] Which of the following is a function/method of the
integer pickle module?
d) It tells the details about the file a) reader()
b) load()
c) writer()
Ans.: c)It returns the byte position of the file pointer as d) read()
an integer
[16] A text file opened using following statement:
MyFile =open(‘Notes.txt’) Ans.: b) load()
Which of the following is the correct statement to Watch this video for more understanding:
close it? [21] Suppose content of ‘Myfile.txt’ is :
a) MyFile=close(‘Notes.txt’) Ek Bharat Shreshtha Bharat
b) MyEile.close ( ‘Notes.txt’) What will be the output of the following code?
c) close.MyFile () myfile = open("Myfile.txt")
d) MyFile.close () vlist = list("aeiouAEIOU")
vc=0
x = myfile.read()
Ans.: d) MyFile.close () for y in x:
[17] Which of the following is not a correct python if(y in vlist):
statement to open a text file “Notes.txt” to write vc+=1
content into it? print(vc)
a) F = open(“Notes.txt”,”w”) myfile.close()
b) F = open(“Notes.txt”,”a”) a. 6
c) F = open(“Notes.txt”,”A”) b. 7
d) F = open(“Notes.txt”,”w+”) c. 8
d. 9

Ans.: c) F = open(“Notes.txt”,”A”)
[18] Which of the following is the correct python Ans. b) 7
statement to read and display the first 10 characters [22] Which of the following statement is incorrect in
from a text file Notes.txt? the context of binary files?
a) F = open(“notes.txt”);print(F.load(10)) a. Information is stored in the same format in which
b) F = open(“notes.txt”);print(F.dump(10)) the information is held in memory.
c) F = open(“notes.txt”);print(F.read(10)) b. No character translation takes place
d) F = open(“notes.txt”);print(F.write(10)) c. Every line ends with a new line character
d. pickle module is used for reading and writing

Ans.: c) F = open(“notes.txt”);print(F.read(10))
[19] Which of the following statement is not correct? Ans. : c) Every line ends with a new line character
[23] Which of the following statement is not true?

Page. 20
a. pickling creates an object from a sequence of bytes b. reader()
b. pickling is used for object serialization c. writer()
c. pickling is used for object deserialization d. writerow()
d. pickling is used to manage all types of files in Python

Ans.: a) read()
Ans.: d. pickling is used to manage all types of files in [29] Which of the following statement opens a binary
Python file record.bin in write mode and writes data from a list
[24] Syntax of seek function in Python is lst1 = [1,2,3,4] on the binary file?
myfile.seek(offset, reference_point) where myfile is a. with open(‘record.bin’,’wb’) as myfile:
the file object. What is the default value of pickle.dump(lst1,myfile)
reference_point? b. with open(‘record.bin’,’wb’) as myfile:
a. 0 pickle.dump(myfile,lst1)
b. 1 c. with open(‘record.bin’,’wb+’) as myfile:
c. 2 pickle.dump(myfile,lst1)
d. 3 d. with open(‘record.bin’,’ab’) as myfile:
pickle.dump(myfile,lst1)

Ans.: a) 0
[25] Which of the following character acts as default Ans.: with open(‘record.bin’,’wb’) as myfile:
delimiter in a csv file? pickle.dump(lst1,myfile)
a. (colon) : [30] Suppose the content of ‘Myfile.txt’ is:
b. (hyphen) – “Twinkle twinkle little star
c. (comma) , How I wonder what you are
d. (vertical line) | Up above the world so high
Like a diamond in the sky “
What will be the output of the following code?
Ans.: c) (comma), myfile = open("Myfile.txt")
[26] Syntax for opening Student.csv file in write mode data = myfile.readlines()
is myfile = open(“Student.csv”,”w”,newline=”). What is print(len(data))
the importance of newline=”? myfile.close()
a. A newline gets added to the file a. 3
b. Empty string gets appended to the first line b. 4
c. Empty string gets appended to all lines c. 5
d. EOL translation is suppressed d. 6

Ans. : d) EOL translation is sppressed Ans.: b) 4


[27] What is the correct expansion of CSV files? [31] Raghav is trying to write a tuple tup1 = (1,2,3,4,5)
a. Comma Separable Values on a binary file test.bin. Consider the following code
b. Comma Separated Values written by him.
c. Comma Split Values import pickle
d. Comma Separation Values tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle._______ #Statement 1
Ans. : b) Comma Separated Values myfile.close()
[28] Which of the following is not a function / method Identify the missing code in Statement 1.
of csv module in Python? a. dump(myfile,tup1)
a. read() b. dump(tup1, myfile)
c. write(tup1,myfile)
d. load(myfile,tup1)

Page. 21
Ans.: b. dump(tup1, myfile)
[32] A binary file employee.dat has the following data :

empno ename salary

101 Anuj 50000

102 Arijita 40000

103 Hanika 30000

104 Firoz 60000

105 VijayLakshmi 40000

def display(eno):
f=open("employee.dat","rb")
totSum=0
try:
while True:
R=pickle.load(f)
if R[0]==eno:
__________ #Line1
totSum=totSum+R[2]
except:
f.close()
print(totSum)
When the above-mentioned function, display (103) is executed, the output displayed is 190000.
Write an appropriate jump statement from the following to obtain the above output.
a. jump
b. break
c. continue
d. return

Ans.: break
[33] A text file student.txt is stored in the storage device. Identify the correct option out of the following
options to open the file in reading mode.
i. myfile = open(‘student.txt’,’rb’)
ii. myfile = open(‘student.txt’,’w’)
iii. myfile = open(‘student.txt’,’r’)
iv. myfile = open(‘student.txt’)
a. only i
b. both i and iv
c. both iii and iv
d. both i and ii

Page. 22
Ans.: c) both iii and iv
[34] Suppose content of ‘Myfile.txt’ is
Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
All the king’s horses and all the king’s men
Couldn’t put Humpty together again
What will be the output of the following code?
myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()
a. 24
b. 25
c. 26
d. 27

Ans.: c) 26
[35] Suppose content of ‘Myfile.txt’ is
Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()
a. 5
b. 25
c. 26
d. 27

Ans.: d) 27
[36] Suppose the content of ‘Myfile.txt’ is :
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a. 2
b. 3
c. 4
d. 5

Ans.: b) 3
[37] Suppose the content of ‘Myfile.txt’ is :

Page. 23
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("MyFile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()
a. 2
b. 3
c. 4
d. 5

Ans.: a) 2
[38] Which of the following mode in the file opening statement results or generates an error if the file
does not exist?
(a) a+
(b) r+
(c) w+
(d) None of the above

Ans. b) r+
[39] The correct syntax of seek() is:
(a) file_object.seek(offset [, reference_point])
(b) seek(offset [, reference_point])
(c) seek(offset, file_object)
(d) seek.file_object(offset)

Ans.: (a) file_object.seek(offset [, reference_point])


[40] Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text
file.
Reason (R): The information is organized with one record on each line and each field is separated by
comma.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A (c) A is True but R is False
(d) A is false but R is True

Ans.: a) Both A and R are true and R is the correct explanation for A
[41] Consider the following directory structure:

Page. 24
Suppose root directory (School) and present working directory are the same. What will be the absolute
path of the file Syllabus.jpg?
a. School/syllabus.jpg
b. School/Academics/syllabus.jpg
c. School/Academics/../syllabus.jpg
d. School/Examination/syllabus.jpg

Ans.: b) School/Academics/syllabus.jpg
[42] Assume the content of the text file, ‘student.txt’ is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()
a. string
b. list
c. tuple
d. dictionary

Ans.: b) list
[43] Which of the following option is not correct?
a. if we try to read a text file that does not exist, an error occurs.
b. if we try to read a text file that does not exist, the file gets created.
c. if we try to write on a text file that does not exist, no error occurs.
d. if we try to write on a text file that does not exist, the file gets Created.

Ans.: b) if we try to read a text file that does not exist, the file gets created.
[44] Which of the following options can be used to read the first line of a text file Myfile.txt?
a. myfile = open(‘Myfile.txt’); myfile.read()

Page. 25
b. myfile = open(‘Myfile.txt’,’r’); myfile.read(n)
c. myfile = open(‘Myfile.txt’); myfile.readline()
d. myfile = open(‘Myfile.txt’); myfile.readlines()

Ans.: c) myfile = open(‘Myfile.txt’); myfile.readline()


[45] Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the
following option can be used to read all the remaining lines?
a. myfile.read()
b. myfile.read(n)
c. myfile.readline()
d. myfile.readlines()

Ans.: d) myfile.readlines()

2 Marks Questions File Handling Class 12 Computer Science


In this section of computer science class 12 previous year questions I am going to discuss 2 marks
questions file handling class 12 computer science. Here we go!
Steps are given just for explanation not required in the answer.
[1] Write a statement in Python to open a text file MARKER.TXT so that existing content can be read
from it.
Ans.:
Steps:
Create a file object/handle f to open the file “marker.txt” in read mode using the open() function.
Create an object data and store the data using the read() function.
Print the data stored in the data object using the print() function.
Close the file using the close() function.
Code:
f=open("MARKER.txt")
data=f.read()
print(data)
f.close()
[2] Write a statement in Python to open a text file DATA.TXT so that new content can be written in it.
Ans.:
Steps:
Create a file object/handle f to open the file “data.txt” in w (write) mode using the open() function.
Use write () function to add new content to the file.
Close the file using the close() function.
Code:
f=open("DATA.TXT","w")
f.write("Data file is ready to get data.")
f.close()
[3] Write a method/function ABLINES( ) in python to read contents from a text file LINES.TXT, to display
those lines, which is starting with either the alphabet ‘A’ or alphabet ‘B’.
For example:
If the content of the file is :
A BOY IS PLAYING OUTSIDE
THE PLAYGROUND IS BIG

Page. 26
BANYAN TREE IS IN THE GROUND
The method/function should display:
A BOY IS PLAYING OUTSIDE
BANYAN TREE IS IN THE GROUND
Ans.:
Steps:
Method 1 Using starts with method
Create a function using def as given in the question.
Create a file object myfile and open the file “lines.txt” in read (r) mode.
Declare an object d and store the contents of files in the list using readlines() function.
Traverse the list using for loop.
Now use the if condition to check the lines having the first letter is either ‘A’ or ‘B’ using startswith()
function.
Print the lines.
Close the file.
def ABLINES():
myfile = open("lines.txt",'r')
d=myfile.readlines()
for i in d:
if i[0].startswith('A') or i[0].startswith('B'):
print(i,end='')
myfile.close()
Method 2 Using index 0
Steps:
Create a function ABLINES() starting with def keyword.
Create an object myfile to open “MyFile.txt” in read (r) mode.
Create an object d to store the lines of the text file using readlines() function.
Traverse the list using for loop.
Use if condition to print the lines starts with ‘A’ or ‘B’ using the initial index 0.
Print the lines.
Close the file.
def ABLINES():
myfile = open("MyFile.txt",'r')
d=myfile.readlines()
for i in d:
if i[0]=='A' or i[0]=='B':
print(i,end='')
myfile.close()
[4] Write a method/function SHORTWORDS( ) in python to read lines from a text file WORDBANK.TXT,
and display those words, which are lesser than 5 characters.
For example :
If the content of the file is :
HAPPY JOY WELCOME KITE
LOVELY POSITIVE FUN
The method /function should display :
JOY
KITE
FUN
Ans.:

Page. 27
Steps:
Create a function SHORTWODS() starting with the def keyword.
Create a file object wb and open the file “wordbank.txt” in read (r) mode.
Now declare object d to store the contents of the file using read() function.
Declare a variable w to store the data received from the file into a d object to split in words using split()
function.
Traverse the words list object w using for loop.
Use if condition to print the words having less than 5 characters using relation operator < and len()
function.
Close the file.
def SHORTWORDS():
wb = open("wordbank.txt",'r')
d=wb.read()
w=d.split()
for i in w:
if len(i)<5:
print(i)
wb.close()
SHORTWORDS()
[5] Differentiate between the following :
f = open(‘diary.txt’, ‘a’)
f = open(‘diary.txt’, ‘w’)
Ans.:

f = open(‘diary.txt’, ‘a’) f = open(‘diary.txt’, ‘w’)

This line opens a file for appending or adding This line opens a file for writing content to
content to the text file diary.txt. the text file diary. txt.

It will add the content to the end of the file. It will overwrite the contents of the file.

For example: For example:


f=open(“dairy.txt”,’a’) f=open(“dairy.txt”,’w’)
f.write(“New line added.”) f.write(“Text file is created.”)
f.close() f.close()

[6] Write a method in python to read the Write function definition for TOWER( ) in python to read the
content of a text file WRITEUP.TXT, count the presence of word TOWER and display the number of
occurrences of this word.
Note : – The word TOWER should be an independent word – Ignore type cases (i.e. lower/upper case)
Example :
If the content of the file WRITEUP.TXT is as follwos :
Tower of hanoi is an interesting problem. Mobile phone tower is away from here. Views from EIFFEL
TOWER are amazing.
The function TOWER( ) should display : 3
Ans.:
def TOWER():
wp = open("WriteUP.txt",'r')
d=wp.read()

Page. 28
w=d.split()
c=0
for i in w:
if 'tower' in i.lower():
c+=1
print("Tower word occurs:",c, " times in the file.")
wp.close()
[7] Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which is starting
with an alphabet ‘A’ .
Ans.:
def begins_A():
f = open("Story.txt",'r')
d=f.readlines()
c=0
for i in d:
if i[0]=='A':
c+=1
print("The file story.txt contains", c," lines starting with A.")
f.close()
[8] Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and
display those words, which are less than 4 characters.
Ans.:
def DISPLAYWORDS():
f = open("STORY.txt",'r')
d=f.read()
w=d.split()
for i in w:
if len(i)<4:
print(i,end=' ')
f.close()
[9] Write a method in python to read the content from a text file story.txt line by line and display the
same on screen.
Ans.:
def read_lines():
f = open("story.txt",'r')
d=f.readlines()
for i in d:
print(i,end='')
f.close()
[10] Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence
of the word ‘‘India’’.
For example :
If the content of the file is
‘‘India is the fastest growing economy. India is looking for more investments around the globe. The
whole world is looking at India as a great market. Most of the Indians can foresee the heights that India
is capable of reaching.“
The output should be 4.
Ans.:
def india_freq():

Page. 29
myfile = open("india.txt",'r')
d=myfile.read()
w=d.split()
c=0
for i in w:
if i.lower()=='india':
c+=1
print("India found",c, " times.")
myfile.close()
[11] Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written in
it.
Refer answer 1.
[12] Write a statement in Python to open a text file README.TXT so that existing content can be read
from it.
Refer answer 2.
[13] Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT,
to count and display the occurrence of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’.
For example :
If the content of the file is –
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT
TO TAKE RESPONSIBILITY
The method/function should display
Count of IS TO and UP is 6
Ans.:
def istoupcount():
myfile = open("writer.txt",'r')
d=myfile.read()
w=d.split()
c=0
for i in w:
if i.lower()=='is' or i.lower()=='up' or i.lower()=='to':
c+=1
print("Count of is, up and to is:",c)
myfile.close()
[14] Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and display
those lines, which are starting either with A or starting with E.
For example :
If the content of the file is
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. WE SHOULD TAKE CARE OF OUR
ENVIRONMENT. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.
The method should display
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH.
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.
Ans.:
def AEDISP():
myfile = open("writer.txt",'r')
d=myfile.readlines()
for i in d:
if i[0]=='A' or i[0]=='E':

Page. 30
print(i,end='')
myfile.close()
[15] A text file named SOLUTION.TXT contains some English sentences. Another text file named
TEST.TXT needs to be created such that it replaces every occurrence of 3 consecutive letters ‘h’, ‘i’ and
‘s’ (irrespective of their cases) from each word of the file SOLUTION.TXT, with 3 underscores (‘___’).
For example :
If the file SOLUTION.TXT contains the following content :
“This is his history book.”
Then TEST.TXT should contain the following : “T ___ is ___ ___tory book.”
Write the definition for function CreateTest()in Python that would perform the above task of creating
TEST.TXT from the already existing file SOLUTION.TXT.
Ans.:
def Create_Test():
myfile = open("solution.txt",'r')
d=myfile.read()
t=d.replace('his','___')
myfile = open("Test.txt",'w')
myfile.write(t)
myfile.close()
myfile = open("Test.txt",'r')
print(myfile.read())
[16] A text file named AGENCIES.TXT contains some text. Write the definition for a function Showsites()
in Python which displays all such words of the file which have more than 9 characters and start with
“www.”.
For example :
If the file AGENCIES.TXT contains :
“Name: TechnoCraft, Website: www.technocraft.com, Name: DataTech, Website: www.datatech.com”
Then the function Showsites() should display the output as : www.technocraft.com
www.datatech.com
Ans.:
def ShowSites():
f=open("Agencies.txt")
data=f.read()
words=data.split()
for i in words:
if len(i)>9 and i.startswith('www'):
print(i)
Computer Science Class 12 Data file handling 3 marks questions
[1] Write a function in Python that counts the number of “Me” or “My” words present in a text file
“STORY.TXT”.
If the “STORY.TXT” contents are as follows:
My first book was Me and My Family. It gave me chance to be Known to the world.
The output of the function should be:
Count of Me/My in file: 4
def CountMyorMy():
f=open("story.txt")
data=f.read()
words=data.split()
c=0

Page. 31
for i in words:
if 'Me' in i or 'My' in i:
c+=1
print("Count of Me/My in file:",c)
[2] Write a function AMCount() in Python, which should read each character of a text file STORY.TXT,
which should count and display the occurrence of alphabets A and M (including small cases a and m
too).
Example:
If the file content is as follows:
Updated information As simplified by official websites.
The AMCount() function should display the output as:
A or a:4
M or m :2
Ans.:
def AMCount():
f=open("story.txt")
data=f.read()
ca=cm=0
for i in data:
if 'a' in i.lower():
ca+=1
if 'm' in i.lower():
cm+=1
print("A or a:",ca)
print("M or m:",cm)
[3] Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the
lines which are not starting with any vowel.
Example:
If the file content is as follows:
An apple a day keeps the doctor away. We all pray for everyone’s safety. A marked difference will come
in our country.
The COUNTLINES() function should display the output as:
The number of lines not starting with any vowel – 1
Ans.:
def COUNTLINES():
f = open("testfile.txt",'r')
d=f.readlines()
c=0
for i in d:
if i not in 'AEIOUaeiou':
c+=1
print("The number of lines not starting with any vowel - ",c)
f.close()
[4] Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT”
and then count and display the count of occurrence of alphabets E and T individually (including small
cases e and t too).
Example:
If the file content is as follows:
Today is a pleasant day. It might rain today. It is mentioned on weather sites

Page. 32
The ETCount() function should display the output as:
E or e: 6
T or t : 9
Ans.:
def ETCount():
f = open("testfile.txt",'r')
d=f.read()
ec=0
tc=0
for i in d:
if i.lower()=='e':
ec+=1
if i.lower()=='t':
tc+=1
print("E or e:",ec)
print("T or t:",tc)
f.close()
ETCount()
[5] Aman is a Python programmer. He has written a code and created a binary file record.dat with
employeeid, ename and salary. The file contains 10 records.
He now has to update a record based on the employee id entered by the user and update the salary.
The updated record is then to be written in the file temp.dat. The records which are not to be updated
also have to be written to the file temp.dat. If the employee id is not found, an appropriate message
should to be displayed.
As a Python expert, help him to complete the following code based on the requirement given above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True :
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()

Page. 33
Which module should be imported in the program? (Statement 1)
Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in
Statement 4 to write the updated data in the file, temp.dat?
Ans.:
pickle
open(“temp.dat”,”wb”)
pickle.load(fin)
pickle.dump(rec,fout)
5 Marks Questions File Handling Class 12 Computer Science
[1] Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain user
name and password for some entries. He has written the following code. As a programmer, help him to
successfully execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Ranjan should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
Ans.:
(a) csv
(b) w mode
(c) reader()
(d) close()
(e) Frieda myname@FRD
[2] A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user-defined function CreateFile() to input data for a record and add it to Book.dat.
ii. Write a function CountRec(Author) in Python which accepts the Author name as a parameter and
count and return the number of books by the given Author stored in the binary file “Book.dat”.
Ans.:
import pickle
def CreateFile():
f=open("book.dat","ab")

Page. 34
book_no=int(input("Enter Book No.:"))
book_name=input("Enter Book Name:")
author=input("Enter author name:")
price=float(input("Enter Price:"))
l=[book_no,book_name,author,price]
pickle.dump(l,f)
f.close()
def CountRec(Author):
c=0
f=open("book.dat","rb")
while True:
try:
rec=pickle.load(f)
if rec[2]==Author:
c+=1
except EOFError:
break
f.close()
return c
CreateFile()
a=input("Enter author to search:")
print("No. of books:",CountRec(a))
[3] A binary file “STUDENT.DAT” has a structure (admission_number, Name, Percentage). Write a
function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the
details of those students whose percentage is above 75. Also, display the number of students scoring
above 75%.
import pickle
def countrec():
f=open("student.dat","rb")
c=0
while True:
try:
rec=pickle.load(f)
if rec[2]>75:
print(rec[0],rec[1],rec[2])
c+=1
except EOFError:
break
f.close()
[4] What is the advantage of using a csv file for permanent storage? Write a Program in Python that
defines and calls the following user-defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a list
with field elements such as empid, name, mobile, and employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
Ans.:
The advantages of using a CSV file for permanent storage are as follows:
It is a common file format used to store tabular data
It is human readable and easy to modify
It is very simple to implement and parse data

Page. 35
It can be opened by general-purpose software like notepad, MS Word, MS Excel
It is compact and faster to handle as well as small in size
import csv
def ADD():
f=open("record.csv","a",newline='')
emp_id=int(input("Enter employee id:"))
ename=input("Enter Name:")
mo=input("Enter Mobile No.:")
sal=int(input("Enter Salary:"))
l=[emp_id,ename,mo,sal]
w=csv.writer(f)
w.writerow(l)
f.close()
def COUNTR():
f=open("record.csv","r",newline='')
r=csv.reader(f)
c=-1
for i in r:
c+=1
print("No. of records in CSV are:",c)
f.close()
[5] Give any one point of difference between a binary file and a csv file. Write a Program in Python that
defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists of a list
with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price
respectively.
(ii) search()- To display the records of the furniture whose price is more than 10000.
Ans.:
Binary files process the data faster than CSV file.
Binary files can’t be read by any software by the user directly, CSV data can be read by notepad, MS
Word or MS Excel.
The endline character or EndOfFile pointer is not present in binary file, the default endline character is
/n.
import csv
def ADD():
f=open("furniture.csv","a",newline='')
fid=int(input("Enter Furniture ID:"))
fname=input("Enter Furniture Name:")
pri=int(input("Enter Price:"))
l=[fid,fname,pri]
w=csv.writer(f)
w.writerow(l)
f.close()
def search():
f=open("furniture.csv","r",newline='')
r=csv.reader(f)
for i in r:
if int(i[2])>10000:
print(i)

Page. 36
f.close()
[6] Rohit, a student of class 12, is learning CSV File Module in Python. During examination, he has been
assigned an incomplete python code (shown below) to create a CSV File ‘Student.csv’ (content shown
below). Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII, A
2,ABHISHEK,XII, A
3,ARVIND,XII, A
4,RAVI,XII, A
5,ASHISH,XII,A
Incomplete Code
import _____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = [ ]
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [ _____ ] #Statement-4
data.append(_____) #Statement-5
stuwriter. _____ (data) #Statement-6
fh.close()
i. Identify the suitable code for blank space in the line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) cvs
Ans.: c) csv
ii. Identify the missing code for blank space in line marked as Statement-2.
a) “Student.csv”,”wb”
b) “Student.csv”,”w”
c) “Student.csv”,”r”
d) “Student.cvs”,”r”
Ans.: b) “Students.csv”,”w”
iii. Choose the function name (with argument) that should be used in the blank space of the line marked
as Statement-3.
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
Ans.: c) writer(fh)
iv. Identify the suitable code for blank space in line marked as Statement-4.
a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’
b) ROLL_NO, NAME, CLASS, SECTION
c) ‘roll_no’,’name’,’Class’,’section’

Page. 37
d) roll_no,name,Class,section
Ans.: d) roll_no,name,Class,section
v. Identify the suitable code for blank space in the line marked as Statement-5.
a) data
b) record
c) rec
d) insert
Ans.: c) rec
vi. Choose the function name that should be used in the blank space of line marked as Statement-6 to
create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
Ans.: d) writerow()

[7] Nisha, an intern in ABC Pvt. Ltd., is developing a project using the csv module in Python. She has
partially developed the code as follows leaving out statements about which she is not very confident.
The code also contains errors in certain statements. Help her in completing the code to read the desired
CSV File named “Employee.csv”.
#CSV File Content
ENO, NAME, DEPARTMENT
E1,ROSHAN SHARMA , ACCOUNTS
E2,AASMA KHALID, PRODUCTION
E3,AMRIK GILL,MARKETING
E4,SARAH WILLIAMS, HUMAN RESOURCE
#incomplete Code with Errors
import CSV #Statement-1
with open (______,_______ newline='') as. File: #Statement-2
ER= csv. ________ #Statement-3
for R in range (ER) #Statement-4
if __________=="ACCOUNTs" #Statement-5
print(________) #Statement-6
i) Nisha gets an Error for the module name used in Statement-1. What should she write in place of CSV
to import the correct module ?
a) file
b) csv
c) Csv
d) pickle
Ans.: b) csv
ii) Identify the missing code for blank spaces in the line marked as Statement-2 to open the mentioned
file.
a) “Employee.csv”, “r”
b) “Employee.csv”, “w”
c) “Employee.csv”, “rb”
d) “Employee.csv”, “w”
Ans.: a) “Employee.csv”,”r”
iii) Choose the function name (with parameter) that should be used in the line marked as Statement-3.
a) reader (File)

Page. 38
b) readrows (File)
c) writer (File)
d) writerows (File)
Ans.: a) reader(File)
iv) Nisha gets an Error in Statement-4. What should she write to correct the statement?
a) while R in range (ER) :
b) for R in ER:
c) for R = ER:
d) while R = ER:
Ans.: b) for R in ER:
v) Identify the suitable code for blank space in Statement-5 to match every row’s 3rd property with
“ACCOUNTS”.
a) ER[3]
b) ER[2]
c) R[2]
d) R[3]
Ans.: c) R[2]
vi) Identify the suitable code for blank space in Statement-6 to display every Employee’s Name and
corresponding Department?
a) ER[1], R[2]
b) R[1], ER[2]
c) R[1], R[2]
d) ER[1], ER[2]
Ans.: c) R[1], R[2]

Important Questions of File Handling


in Python from previous years Sample Paper

Q1. Write a function in Python that counts the number of “Me” or “My” (in smaller case also) words
present in a text file “STORY.TXT”. If the “STORY.TXT” contents are as follows:
My first book was Me and My Family. It gave me chance to be Known to the world.
The output of the function should be: Count of Me/My in file: 4
Solution

Page. 39
Q2. Write a function AMCount() in Python, which should read each character of a text file STORY.TXT,
should count and display the occurence of alphabets ‘A’ and ‘M’ (including small cases ‘a’ and ‘m ‘too).
Example: If the file content is as follows:
Updated information As simplified by official websites.
The AMCount() function should display the output as: A or a = 4, M or m =2
Solution

Q3. Write a function in python to count the number of lines in a text file ‘
STORY.TXT’ which is starting with an alphabet ‘A’ .
Solution:

Q4. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and
display those words, which are less than 4 characters.
Solution

Page. 40
Q5. Write a function RevText() to read a text file “ Story.txt “ and Print only word starting with ‘I’ in
reverse order . Example: If value in text file is: INDIA IS MY COUNTRY Output will be: AIDNI SI MY
COUNTRY.
Solution

Q6. Write a function in python to count the number of lowercase alphabets present in a text file
“Story.txt”
Solution

Page. 41
Q7. Write a user-defined function named count() that will read the contents of text file named
“Story.txt” and count the number of lines which starts with either “I‟ or “M‟. E.g. In the following
paragraph, there are 2 lines starting with “I‟ or “M‟:
“India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.”
Solution

Q8. Write a function countmy( )in Python to read the text file “Story.txt” and count the number of times
“my” or “My” occurs in the file. For example if the file “Story.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE section.”
The countmy( ) function should display the output as: “my occurs 2 times”.
Solution

Page. 42
Q9. Write a user defined function countwords() in python to count how many words are present in a
text file named “story.txt”. For example, if the file story.txt contains following text:
Co-education system is necessary for a balanced society. With co-education system, Girls and Boys may
develop a feeling of mutual respect towards each other.
The function should display the following:
Total number of words present in the text file are: 24
Solution

Q10. Write a user defined function in Python that displays the number of lines starting with ‘H’ in the file
story.txt. Eg: if the file contains:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.

Then the line count should be 2


Solution

Page. 43
Important Questions of Binary File Handling in Python.
Binary File Handling in Python

Q1. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
Write a user defined function CreateFile() to input data for a record and add to Book.dat .
Write a function CountRec(Author) in Python which accepts the Author name as parameter and count
and return number of books by the given Author are stored in the binary file “Book.dat
import pickle
def createfile():
fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()

createfile() # This function is called just to verify result and not required in exam

def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except:
fobj.close()
return num

n=countrec("amit") # This function is called just to verify result and not required in exam
print("Total records", n) # This statement is just to verify result and not required in exam
Q2. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a
function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the

Page. 44
details of those students whose percentage is above 75. Also display number of students scoring above
75%.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
Binary File Handling in Python
Q3 Write a function in python to search and display details, whose destination is “Cochin” from binary
file “Bus.Dat”. Assuming the binary file is containing the following elements in the list:
Bus Number
Bus Starting Point
Bus Destination
import pickle
def countrec():
fobj=open("bus.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
n=countrec() # This function is called just to verify result
print(n)
Q4. Write a function addrec() in Python to add more new records at the bottom of a binary file
“STUDENT.dat”, assuming the binary file is containing the following structure :
[Roll Number, Student Name]
import pickle
def addrec():
fobj=open("student.dat","ab")
rollno=int(input("Roll Number : "))
sname=input("Student Name :")
rec=[rollno,sname]
pickle.dump(rec,fobj)
fobj.close()
addrec()

Page. 45
Q5. Write a function searchprod( pc) in python to display the record of a particular product from a file
product.dat whose code is passed as an argument. Structure of product contains the following elements
[product code , product price]
import pickle
def searchprod(pc):
fobj=open("product.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[0]==pc:
print(rec)
except:
fobj.close()

n=searchprod(1) # This function is called to verify the result

Q6. Write a function routechange(route number) which takes the Route number as parameter and
modify the route name(Accept it from the user) of passed route number in a binary file “route.dat”.
import pickle
def routechange(rno):
fobj=open("route.dat","rb")
try:
while True:
rec=pickle.load(fobj)
if rec[0]==rno:
rn=input("Enter route name to be changed ")
rec[1]=rn
print(rec) #This statement is called to verify the change in the record
except:
fobj.close()

routechange(1) # This function is called to verify the result

Q7. Write a function countrec(sport name) in Python which accepts the name of sport as parameter and
count and display the coach name of a sport which is passed as argument from the binary file
“sport.dat”. Structure of record in a file is given below ——————– – [sport name, coach name]
def countrec(sn):
num=0
fobj=open("data.dat","rb")
try:
print("Sport Name","\t","Coach Name")
while True:
rec=pickle.load(fobj)
if rec[0]==sn:
print(rec[0],"\t\t",rec[1])
num=num+1
return num
except:

Page. 46
fobj.close()

Q8. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a function
countrec() in Python that would read contents of the file “salary.DAT” and display the details of those
employee whose salary is above 20000.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result

Q9. Amit is a monitor of class XII-A and he stored the record of all the students of his class in a file
named “class.dat”. Structure of record is [roll number, name, percentage]. His computer teacher has
assigned the following duty to Amit
Write a function remcount( ) to count the number of students who need remedial class (student who
scored less than 40 percent)
def countrec():
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()# This function is called to verify the result
Q10. A binary file “emp.dat” has structure [employee id, employee name]. Write a function
delrec(employee number) in Python that would read contents of the file “emp.dat” and delete the
details of those employee whose employee number is passed as argument.

Page. 47
The link ed image cannot be display ed. The file may hav e been mov ed, renamed, or deleted. Verify that the link points to the correct file and location.

CSV File in Python


Important Questions of CSV File in Python

Q1. Write a program to read entire data from file data.csv

Ans.
import csv
f=open("data.csv", 'r')
d=csv.reader(f)
for row in d:
print(row)
OUTPUT:
['Admno', 'Name', 'Class', 'Sec', 'Marks']

Page. 48
['1231', 'Amit', 'XII', 'A', '45']
['1224', 'Anil', 'XII', 'B', '49']
['1765', 'Suman', 'XI', 'A', '42']
['2132', 'Naman', 'XII', 'C', '38']
OR
We can also write the program in the following way
import csv
with open("data.csv",'r') as f:
d=csv.reader(f)
for row in d:
print(row)
Important Questions of CSV File in Python
Q2. Write a program to search the record from “data.csv” according to the admission number input
from the user. Structure of record saved in “data.csv” is Adm_no, Name, Class, Section, Marks

Ans.
import csv
f = open("data.csv",'r')
d=csv.reader(f)
next(f) #To Skip Header Row
k=0
adm = int(input("Enter admission number"))
for row in d:
if int(row[0])==adm:
print("Adm no = ", row[0])
print("Name = ", row[1])
print("Class = ", row[2])
print("Section = ", row[3])
print("Marks = ", row[4])
break
else:
print("Record Not Found")
OUTPUT :
Enter admission number1231
Adm no = 1231
Name = Amit
Class = XII
Section = A
Marks = 45
Important Questions of CSV File in Python
Q3. Write a program to add/insert records in file “data.csv”. Structure of a record is roll number, name
and class.

Ans.
import csv
field = ["Roll no" , "Name" , "Class"]
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)

Page. 49
ch='y'
while ch=='y' or ch=='Y':
rn=int(input("Enter Roll number: "))
nm = input("Enter name: ")
cls = input("Enter Class: ")
rec=[rn,nm,cls]
d.writerow(rec)
ch=input("Enter more record??(Y/N)")
f.close()
Important Questions of CSV File in Python
Q4. Write a program to copy the data from “data.csv” to “temp.csv”

Ans.
import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
Important Questions of CSV File in Python
Q5. Write a program to read all content of “student.csv” and display records of only those students who
scored more than 80 marks. Records stored in students is in format : Rollno, Name, Marks

Ans.
import csv
f=open("student.csv","r")
d=csv.reader(f)
next(f)
print("Students Scored More than 80")
print()
for i in d:
if int(i[2])>80:
print("Roll Number =", i[0])
print("Name =", i[1])
print("Marks =", i[2])
print("--------------------")
f.close( )
OUTPUT
Students Scored More than 80
Roll Number = 1
Name = Amit
Marks = 81
--------------------------
Roll Number = 2
Name = Suman
Marks = 85

Page. 50
-------------------------
Roll Number = 4
Name = Deepika
Marks = 89
-------------------------
Q6. Write a program to display all the records from product.csv whose price is more than 300. Format of
record stored in product.csv is product id, product name, price,.

Ans.
import csv
f=open("product.csv" , "r")
d=csv.reader(f)
next(f)
print("product whose price more than 300")
print()
for i in d:
if int(i[2])>300:
print("Product id =", i[0])
print("Product Name =", i[1])
print("Product Price =", i[2])
print("--------------------")
f.close( )
OUTPUT:
product whose price more than 300
Product id =2
Product Name = Mouse
Product Price = 850
---------------------------------
Product id =3
Product Name = RAM
Product Price = 1560
--------------------------------

Important Questions of CSV File in Python


Q7. Write a program to calculate the sum of all the marks given in the file “marks.csv. Records in
“marks.csv” are as follows :
Rollno, Name, Marks
1, Suman, 67
2, Aman,71
3, Mini, 68
4, Amit, 80

Ans.
import csv
f=open("marks.csv","r")
d=csv.reader(f)
next(f)
s=0
for i in d:

Page. 51
s=s + int(i[2])
print("Total Marks are " ,s)
f.close( )
Important Questions of CSV File in Python
Q8. Write a program to count number of records present in “data.csv” file.

Ans.
import csv
f = open("data.csv" , "r")
d = csv.reader(f)
next(f) #to skip header row
r=0
for row in d:
r = r+1
print("Number of records are " , r)
Important Questions of CSV File in Python
Q9. Write a program to modify the record of a student in a file “data.csv”. Following records are saved in
file.
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, suman, 25

Ans.
import csv
import os
f=open("data.csv","r")
f1 = open("temp.csv","w")
d=csv.reader(f)
d1=csv.writer(f1)
next(f)
s=0
rollno = int(input("Enter roll number :"))
mn=input("Enter modified name :")
mm = int(input("Enter modified marks :"))
mr=[rollno,mn,mm]
header =["Rollno", "Name", "Marks"]
d1.writerow(header)
for i in d:
if int(i[0])==rollno:
d1.writerow(mr)
else:
d1.writerow(i)
os.remove("data.csv")
os.rename("temp.csv","data.csv")
f.close()
f1.close()

Page. 52
Execution of Program
Enter roll number :4
Enter modified name :Sumati
Enter modified marks :45
After modification, data in the file will be
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, sumati, 45
Important Questions of CSV File in Python
Q10. Write a program to show the detail of the student who scored the highest marks. Data stored in
“Data.csv” is given below :
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, suman, 25

Ans.
import csv
f=open("data.csv","r")
d=csv.reader(f)
next(f)
max=0
for i in d:
if int(i[2])>max:
max=int(i[2])
f.close()
f=open("data.csv","r")
d=csv.reader(f)
next(f)
for i in d:
if int(i[2])==max:
print(i)
f.close()
Execution of Program :
['1' , ' Aman' , ' 35']

Case

Q1. Aman is working in an IT company writing a program to add record in an already existing CSV file
“stud.csv”. He has written the following code. As a friend of Aman, help him to complete the code given
below.
__________________ #Statement-1
fn = open(_____, _____, newline='') #Statement-2
sdata = csv._____ #Statement-3
temp = [ ]

Page. 53
sid = int(input("Enter Student Id : "))
sname = input("Enter Student Name : ")
class = input("Enter Class : ")
record = [ _____ ] #Statement-4
temp.___________ (record) #Statement-5
sdata. dump ( ___________ ) #Statement-6
fn.close()
1. Fill in the blank for statement1:
(a) load CSV
(b) read csv
(c) import csv
(d) import CSV
Ans. (c) import csv
2. Fill in the blank for statement2:
(a) "stud .csv", "wb"
(b) "stud .csv", "a"
(c) "stud .csv", "w"
(d) "stud .cvs", "a"
Ans. (b) “stud .csv”, “a”
3. Fill in the blank for statement3:
(a) writer(fn)
(b) reader(fn)
(c) readline(fn)
(d) writeline(fn)
Ans. (a) writer(fn)
4. Fill in the blank for statement4:
(a) Sid, Sname, Class
(b) sid, sname, class
(c) SID,SNAME,CLASS
(d) “sid”, ”sname”, "class”
Ans. (d) “sid”, ”sname”, “class”
5. Fill in the blank for statement5:
(a) add
(b) writes
(c) append
(d) dump
Ans. (c) append
6. Fill in the blank for statement6:
(a) record
(b) temp
(c) fn
(d) csv
Ans. (b) temp

Q2. Srishti is a class 12 Computer Science student. She has been assigned an incomplete python code
(shown below) to create a CSV file ‘book.csv’ and display the file content (as shown below). Help her to
complete the following code.
CSV File

Page. 54
bookid, subject, class
b1, Hindi, VI
b2, Science, VII
b3, Math, VI
import____________ #Statement-1
fn = open(____________, __________) #Statement-2
fno = csv._________ #Statement-3
fno.writerow(["bookid","subject", "class"])
fno.writerow(["b1", "Hindi", "VI"])
fno.writerow(["b2", "Science", "VII"])
fno.writerow(["b3", "Math", "VI"])
fn.____________ #Statement-4
_______ open("book.csv","r") as fn: #Statement-5
rd=csv._________ #Statement-6
for rec in rd:
print(rec)
fn.close()

1. Choose the correct code for Statement1.


a. csv
b. CSV
c. cvs
d. csv file
Ans. a. csv
2. Choose the correct code for Statement2.
a. "book.csv", "r"
b. "book.csv", "w"
c. "book.csv file", "w"
d. "book", "w"
Ans. b. “book.csv”, “w”
3. Choose the correct code for Statement3.
a. reader(fn)
b. read(book)
c. writer(fn)
d. write(fn)
Ans. c. writer(fn)
4. Choose the correct code for Statement4.
a. dump( )
b. close( )
c. exit( )
d. end( )
Ans. b. close( )
5. Choose the correct code for Statement5.
a. fn =
b. with
c. With
d. as
Ans. b. with
6. Choose the correct code for Statement6.

Page. 55
a. readlines(fn)
b. read(fn)
c. readrows()
d. reader(fn)
Ans. d. reader(fn)

Q3. Amit, a student of class 12th is trying to write a program to search the record from “data.csv”
according to the admission number input from the user. Structure of record saved in “data.csv” is
Adm_no, Name, Class, Section, Marks. He has written the partial code and has missed out certain
statements, You as an expert
of Python have to provide the answers of missing statements based on the following code of Amit.
Ans.

import _____________________ #Statement1


f = open(__________________) #Statement2
d=csv._______________________(f) #Statement3
next(f) #To Skip Header Row
k=0
adm = int(input("Enter admission number"))
for row in d:
if int(row[0])_______________adm: #Statement4
print("Adm no = ", row[0])
print("Name = ", row[___________]) #Statement5
print("Class = ", row[2])
print("Section = ", row[3])
print("Marks = ", row[4])
break
_____________ : #Statement6
print("Record Not Found")
1. Choose the correct module for Statement1.
a. CSV
b. Csv
c. Picke
d. csv
Ans. d. csv
2. Choose the correct code for Statement2
a. "data.csv", "r"
b. "data.csv", "w"
c. "data.csv", "a"
d. "data.csv", "wb"
Ans. a. “data.csv”, “r”
3. Choose the correct function for Statement3
a. Reader
b. reader( )
c. reader
d. read
Ans. c. reader
4. Choose the correct operator for Statement4
a. >

Page. 56
b. >=
c. ==
d. !=
Ans. c. ==
5. Choose the correct index for Statement5.
a. 0
b. 1
c. 2
d. 3
Ans. b. 1
6. Choose the correct selection statement for Statement6.
a. if
b. else
c. elif
d. if-
Ans. b. else

Q4. Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he has
been assigned an incomplete python code (shown below) to create a CSV File ‘Student.csv’ (content
shown below). Help him in completing the code which creates the desired CSV File. [C.B.S.E. Question
Bank]
CSV File

1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code

import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = [ ]
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
1. Identify the suitable code for blank space in line marked as Statement-1.
a) csv file
b) CSV

Page. 57
c) csv
d) Csv
Ans. c) csv
2. Identify the missing code for blank space in line marked as Statement-2?
a) “School.csv”,”w”
b) “Student.csv”,”w”
c) “Student.csv”,”r”
d) “School.csv”,”r”
Ans. b) “Student.csv”,”w”
3. Choose the function name (with argument) that should be used in the blank space of line marked as
Statement-3
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
Ans. c) writer(fh)
4. Identify the suitable code for blank space in line marked as Statement-4.
a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’
b) ROLL_NO, NAME, CLASS, SECTION
c) ‘roll_no’,’name’,’Class’,’section’
d) roll_no,name,Class,sectionc) co.connect()
Ans. c) ‘roll_no’,’name’,’Class’,’section’
5. Choose the function name that should be used in the blank space of line marked as Statement-5 to
create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
Ans. c) writerows()

Q5. Krrishnav is looking for his dream job but has some restrictions. He loves Delhi and would take a job
there if he is paid over Rs.40,000 a month. He hates Chennai and demands at least Rs. 1,00,000 to work
there. In any another location he is willing to work for Rs. 60,000 a month. The following code shows his
basic strategy for evaluating a job offer. [C.B.S.E. Question Bank]
pay= _________
location= _________
if location == "Mumbai":
print ("I’ll take it!") #Statement 1
elif location == "Chennai":
if pay < 100000:
print ("No way") #Statement 2
else:
print("I am willing!") #Statement 3
elif location == "Delhi" and pay > 40000:
print("I am happy to join") #Statement 4
elif pay > 60000:
print("I accept the offer") #Statement 5
else:
print("No thanks, I can find something better") #Statement 6

Page. 58
On the basis of the above code, choose the right statement which will be executed when different
inputs for pay and location are given
1. Input: location = “Chennai”, pay = 50000
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4
Ans. b. Statement 2
2. Input: location = “Surat” ,pay = 50000
a. Statement 2
b. Statement 4
c. Statement 5
d. Statement 6
Ans. d. Statement 6
3. Input- location = “Any Other City”, pay = 1
a Statement 1
b. Statement 2
c. Statement 4
d. Statement 6
Ans. d. Statement 6
4. Input location = “Delhi”, pay = 500000
a. Statement 6
b. Statement 5
c. Statement 4
d. Statement 3
Ans. c. Statement 4
5. v. Input- location = “Lucknow”, pay = 65000
a. Statement 2
b. Statement 3
c. Statement 4
d. Statement 5
Ans. d. Statement 5

Page. 59

You might also like