Xii CS Term 1 Question Bank
Xii CS Term 1 Question Bank
CLASS : XII
SUBJECT :COMPUTER SCIENCE(083)
Term-1
Session 2021-2022
LUCKNOW PUBLIC SCHOOL
TOPICS
XI-REVIEW
WORKING WITH FUNCTIONS
DATA FILE HANDLING
Typology of questions:
Multiple choice
Assertion reason
Case based
Prepared by: GAJENDRA SINGH DHAMI (PGT CS)
COMPUTER SCIENCE-XII 1
XI-REVIEW
1. Which of the following are the fundamental building block of a python program.
i. Identifier ii. Constant iii. Punctuators iv. Tokens
2. Identify the valid identifier from the following:
i. 9type ii. _type iii. My Name iv. True
3. Identify the identifier that is invalid from the following:
i. abc_23 ii. _type iii. False iv. TRUE
4. Which of the following is a relational operator:
i. > ii. // iii. or iv. **
5. Which of the following is a logical operator:
i. + ii. /= iii. and iv. in
6. Identify the membership operator from the following:
i. in ii. not in iii. both i & ii iv. Only i
7. Identify the identity operator from the following:
i. id() ii. is not iii. is iv. Both ii &iii
8. Which one of the following is not an arithmetic operator?
i. % ii. ** iii. // iv. +=
9. Identify the operator that compares 2 values for equality ,from the following:
i. = ii. == iii. is iv. equals
10. Identify the invalid augmented assignment operator from the following:
i. *= ii. =+ iii. %= iv. **=
11. What will be the correct output of the statement : >>>4//3.0
i. 1 ii. 1.0 iii 1.3333 iv. None of the above
12. What will be the correct output of the statement : >>> 4+2**2*10
i. 18 ii. 80 iii. 44 iv. None of the above
13. What will be the correct output of the statement : >>> 4+2**(2*2)+10+3/2
i. 31.0 ii. 31.5 iii. 31 iv. None of the above
14. Give the output of the following code:
>>> a,b=4,2
>>> a+b**2*10
i. 44 ii. 48 iii. 40 iv. 88
15. Give the output of the following code:
>>> a=b=0
>>> True+10-bool(a)*10+2**b
i. 14 ii. 15 iii. 12 iv. Error
16. What will be the correct output of the statement : >>> bool(3-4)
i. True ii. False iii. Error iv. None of the above
COMPUTER SCIENCE-XII 2
17. Give the output of the following code:
>>>a,b,c=1,2,3
>>> a//b**c+a-c*a
i. -2 ii. -2.0 iii. 2.0 iv. None of the above
18. What will be the correct output of the statement ?
>>> a,b,c=True,False,True
>>>a and b or b and not c
i. True ii. False iii. Error iv. None of the above
19. Give the output of the following code:
>>>import math
>>> math.ceil(1.03)+math.floor(1.03)
i. 3 ii. -3.0 iii. 3.0 iv. None of the above
20. What maximum value will following code can give in output?
>>>import random as r
>>>round( r.randint(1,4)+ r.randrange(1,4)+r.random( ))
i. 7 ii. 8 iii. 9 iv. 10
21. Single line comments in python begins with……………….. symbol.
i. # ii. “ iii. % iv.’’’
22. The input() function always returns a value of ……………..type.
i. Integer ii. float iii. string iv. Complex
23. ……….. function is used to determine the data type of a variable.
i. type( ) ii. id( ) iii. print( ) iv. str( )
24. Identify the type of data conversion in the following expression:
>>>int(9.4)+bool(-1)+float(9)+10
i. Implicit ii. Explicit iii. Type casting iv. Both ii & iii
25. Which is feature of python language?
i. cross platform ii. Open source iii. Case sensitive iv. All of these
26. Give the output of the following code:
>>>a,b=1,2
>>>a,b=b,a
>>>print(a,b,sep=’@’)
i. 1@2 ii. 2@1 iii. 21@ iv. 12@
27. ___________ checks the program code line by line?
i. Interpreter ii. compiler iii. assembler iv. All of these
28. Identify the type of error following code will generate.
>>>a,b=1,2
>>>print(a+b+c)
i. TypeError ii. ValueError iii. NameError iv. 12c
29. Give the output of the following code:
COMPUTER SCIENCE-XII 3
>>>a,b=3,2
>>>print(str(a)*b)
i. 22 ii. 33 iii. 6 iv. Error
30. Give the output of the following code:
>>>a,b=’abc’,’123’
>>>print(a+b+a)
i. abc123abc ii. Abc123 iii. 123abc123 iv. Error
31. Data type whose value cannot be modified at its place is _________.
i.mutable ii. immutable iii. exchangeable iv. None
32. _________ is used to include an empty statement in python.
i.pass ii. None iii. Null iv. empty
33. Give output of following code:
A=12+5j
P=A.real*10+A.imag*20
print(P)
i.220 ii. 120 iii. 290 iv. Error
ANSWER KEYS
1 iv 2 ii 3 iii 4 i
5 iii 6 iii 7 iv 8 iv
9 iv 10 ii 11 ii 12 iii
13 ii 14 i 15 iii 16 i
17 i 18 ii 19 i 20 ii
21 i 22 iii 23 i 24 iv
25 iv 26 ii 27 i 28 iii
29 ii 30 i 31 ii 32 i
33 i
COMPUTER SCIENCE-XII 4
CONTROL FLOW
i. if..else statement ii. for statement iii. if-elif statement iv. if statement
i. if..else statement ii. for statement iii. while iv. Both ii & iii
>>>list(range(1,7,2))
8. …………loop is the best choice when the number of iterations are known.
COMPUTER SCIENCE-XII 5
for k in 'ABCDE':
if k=='C':
continue
print(k,end='')
else:
print('#',end='')
print(k)
i. ABDEE ii. ABDE#E iii. ABCDE#E iv.None
for k in 'ABCDE':
if k=='C':
break
print(k,end='')
else:
print('#',end='')
print(k)
i. AB#E ii. AB#E iii. ABE iv.None
12. Select the option that represent the output generated by following code:
a=10
a+=10
if a:
a*=2
if a%3>5:
a=100
if True:
a=90
if False:
a=1
else:
a=11
print(a)
i. 11 ii. 90 iii. 40 iv.None
13. What output the following statements will generate?
>>>a=20.8
>>>t=int(a)>10 and int(’20.8’)>10
>>>t
i. True ii. False iii. 10 iv.Error
COMPUTER SCIENCE-XII 6
14. What output the following statements will generate?
>>>a=20.8
>>>t=int(a)>10 or int(’20.8’)>10
>>>t
i. True ii. False iii. 10 iv.Error
15. What output the following statements will generate?
R=len('ABCDE')
while R>0:
if R%2==1:
print('a',end='')
else:
break
R=R-2
else:
print(R)
i. aa-1 ii. aaa-1 iii. aaa iv.aa
COMPUTER SCIENCE-XII 7
P: Set-1 will use less number of comparison compared to set-2.
Q: Set-2 will use less number of comparison compared to set-1.
R: Set-2 is a nested form of if so only one ‘if body’ will execute.
S: Set-1 is a nested form of if so only one ‘if body’ will execute.
Now look below the statements,
i. P is True but Q is False
ii. Q is True but P is False
iii. Q is True and R is correct explanation of Q
iv. P is True and S is correct explanation of P
Select the correct option based on above:
i. i & iii ii. i& iv iii. ii& iii iv. ii & iv
18. Select the block or compound statement from the following:
i. for ii. with iii. while iv. All of these
Case based( 19-22)
Vivek is enthusiastic programmer and he has written a code to enter any 20
numbers to find the sum of all even numbers .But Vivek is not sure about some
code so he left blank at that places .Help him to complete the code. Vivek has
written the following code:
s=0
for k in range(______): #code 1
n=input('enter data=')
n=_______ # code 2
if _____= =0: #code 3
_______ #code 4
else:
print('sum of even nos=',s)
19. Select the option for code 1 to run loop 20 times.
COMPUTER SCIENCE-XII 8
ANSWER KEYS
1 ii 2 iv 3 i 4 iv
5 ii 6 iv 7 iv. 8 iii
9 iv 10 ii 11 iii 12 i
13 iv 14 i 15 ii 16 ii
17 iii 18 iv 19 iv 20 ii
21 iii 22 iv
LISTS,STRINGS,TUPLE,DICTIONARY
strlen=len(str1)+5
COMPUTER SCIENCE-XII 9
print(strlen)
7. Which method removes all the leading whitespaces from the left of the string?
Str.count(‘Hello’,12,25)
Str=”python 38”
print(Str.isalnum())
Str=”Computers”
print(Str.rstrip(“rs”))
11. How many times is the word ‘Python’ printed in the following statement?
s = ”I love Python”
for ch in s[3:8]:
print(‘Python’)
A=”Virtual Reality”
print(A.replace(‘Virtual’,’Augmented’))
COMPUTER SCIENCE-XII 10
13. What will be the output of the following code?
print(“ComputerScience”.split(“er”,2))
print(“ComputerScience”.partition(“er”,2))
15. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
16. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[::-1]
17. What is the correct python code to display the last four characters of “Digital
India”?
18. Given the list L=[11,22,33,44,55], write the output of print(L[: :-1]).
19. Which of the following can add an element at any index in the list?
i. insert( ) ii. append( ) iii. extend() iv. all of these
20. Which of the following function will return a list containing all the words of
the given string?
i.split() ii. index() iii. count() iv. list()
21. Which of the following statements are True?
COMPUTER SCIENCE-XII 11
a. [1,2,3,4]>[4,5,6]
b. [1,2,3,4]<[1,5,2,3]
c. [1,2,3,4]>[1,2,0,3]
d. [1,2,3,4]<[1,2,3,2]
i. a,b,d ii. a,c,d iii. b,c iv. Only d
22. What will be the elements of list l2?
>>>l1=[10,20,30,40,50]
>>>l2=l1[1:4]
Column-A Column B
1. L[1:4] a. [‘t’,’e’,’r’]
2. L[3:] b. [‘o’,’m’,’p’]
3. L[-3:] c. [‘c’,’o’,’m’,’p’,’u’,’t’]
4. L[:-2] d. [‘p’,’u’,’t’,’e’,’r’]
i. 1-b,2-d,3-a,4-c iii. 1-c,2-b,3-a,4-d
ii. 1-b,2-d,3-c,4-a iv. 1-d,2-a,3-c,4-b
26. Give output of following code:
>>>l=[1,2,3,’a’,[‘apple’,’green’],5,6,7,[‘red’,’orange’]]
>>>l[4][1]
i. ‘apple’ ii. ‘green’ iii. ‘red’ iv. ‘orange’
27. What will be the output of the following code?
>>>l1=[1,2,3]
>>>l1.append([5,6])
>>>l1
i. [1,2,3,5,6] ii. [1,2,3,[5,6]] iii. [[5,6]] iv. [1,2,3,[5,6]]
COMPUTER SCIENCE-XII 12
28. What will be the output of the following code?
>>>l1=[1,2,3]
>>>l2=[5,6]
>>>l1.extend(l2)
>>>l1
ii. [5,6,1,2,3] ii. [1,2,3,5,6] iii. [1,3,5] iv. [1,2,3,6]
29. What will be the output of the following code?
>>>l1=[1,2,3]
>>>l1.insert(2,25)
>>>l1
iii. [1,2,3,25] ii. [1,25,2,3] iii. [1,2,25,3] iv. [25,1,2,3,6]
30. What will be the output of the following code?
>>>l1=[1,2]
>>>l1.sort(reverse=True)
>>>l1*l1.pop()
iii. [1,2] ii. [1,2,1,2] iii. [2,1,2,1] iv. [2]
31. Which of the statement(s) is/are correct?
i. Python dictionary is an ordered collection of items.
ii. Python dictionary is a mapping of unique keys to values.
iii. Dictionary is mutable.
iv. All of these.
32. ………function is used to convert a sequence data type into tuple.
>>>t=(1,2,3,4)
COMPUTER SCIENCE-XII 13
36. What will be the output of following?
>>>d1={‘rohit’:56,”Raina”:99}
>>>print(“Raina” in d1)
>>>d={‘name’:’rohan’,’dob’:’2002-03-11’,’Marks’:’98’}
>>>d1={‘name’:‘raj’,’tom’:99}
>>>d1.update(d)
>>>print(“d1 :”,d1)
>>>p=[9,7]
>>> q=p
>>> q[1]=77
>>> print(p,q)
i. [9,7] [9,77] ii. [9,77] [9,77] iii. [9,7] [9,7] iv. None of these
>>>p={1:’aman’,2:’naman’,3:’pawan’}
COMPUTER SCIENCE-XII 14
>>>p={1:’aman’,2:’naman’ }
>>> k=list(p.items())
import random
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randint(1,3)
print(List[x],end="#")
i. Delhi#Mumbai#Chennai#Kolkata#
ii. Mumbai#Chennai#Kolkata#Mumbai#
iii. Mumbai# Mumbai #Mumbai # Delhi#
iv. Mumbai# Delhi #Chennai # Mumbai
43. Look carefully the code given below and answer the questions that follow.
i) Select the option for exp 1 to store list of words separated by space in L.
a) n.partion() b)n.split() c)n.words() d)Both a) and b)
ii) Select the correct option for exp 2 to store uppercase form of n in M.
a) n.toupper() b)n.upper() c)n.isupper() d)upper(n)
COMPUTER SCIENCE-XII 15
iii) Select the option for exp 3 to store frequency of occurrence of letter ‘A’ in N.
a) n.count(‘A’) b)n.repeat(‘A’) c)n.find(‘A’) d)None
iv) Select the option for exp 4 to store first five letters in Q.
a)n[1:5] b)n[:5:1] c)n[0:5] d)Both b) and c)
44. Raman is looking for his dream job but has some restrictions. He is ready to
work for ‘Mumbai’.He loves Delhi and would take a job there if he is paid over
Rs.40,000 a month. He does not want 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 or more in a month. The following code shows his basic strategy for
evaluating a job offer.
Code:
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
On the basis of the above code, choose the right statement which will be
executed when different inputs for pay and location are given.
i. Input: location = "Chennai”, pay = 50000
a. Statement 1 b. Statement 2 c. Statement 3 d. Statement 4
ii. Input: location = "Surat" ,pay = 50000
a. Statement 2 b. Statement 4 c. Statement 5 d. Statement 6
iii. Input location = "Delhi", pay = 500000
a. Statement 6 b. Statement 5 c. Statement 4 d. Statement 3
45. Consider the following code and answer the questions that follows:
Book={1:'Thriller', 2:'Mystery', 3:'Crime', 4:'Children Stories'}
Library ={'5':'Madras Diaries','6':'Malgudi Days'}
COMPUTER SCIENCE-XII 16
i. Ramesh needs to change the title in the dictionary book from ‘Crime’ to
‘Crime Thriller’. He has written the following command:
Book[‘Crime’]=’Crime Thriller’
But he is not getting the answer. Help him choose the correct command:
a. Book[2]=’Crime Thriller’
b. Book[3]=’Crime Thriller’
c. Book[2]=(’Crime Thriller’)
d. Book[3] =(‘Crime Thriller’)
ii. The command to merge the dictionary Book with Library the command
would be:
a. d=Book+Library b. print(Book+Library)
c. Book.update(Library) d. Library.update(Book)
iii. What will be the output of the following line of code?
print(list(Library))
a. [‘5’,’Madras Diaries’,’6’,’Malgudi Days’]
b. (‘5’,’Madras Diaries’,’6’,’Malgudi Days’)
c. [’Madras Diaries’,’Malgudi Days’]
d. [‘5’,’6’]
iv. In order to check whether the key 2 is present in the dictionary Book,
Ramesh uses the following command:
>>>2 in Book
He gets the answer ‘True’. Now to check whether the name ‘Madras Diaries’
exists in the dictionary Library, he uses the following command:
>>>‘Madras Diaries’ in Library
But he gets the answer as ‘False’. Select the correct reason for this:
a. We cannot use the in function with values. It can be used with keys only.
b. We must use the function Library.values() along with the in operator
c. We can use the Library.items() function instead of the in operator
d. Both b and c above are correct.
46. Amit is planning to give a birthday party for his father’s 50 birthday . For
arranging the birthday party , he needs to have a list of items from the nearby
grocery store , suppose he has created a following list of items to be
purchased
Items=[“cake”, ”balloons” ,”pizza”, ”burger”]
i. Suppose If ,before going to the store his mother gives him another list ,
vegetable=[“tomato”, ”onion”]
Amit writes the following code separately:
# CODE 1
COMPUTER SCIENCE-XII 17
list=Items. extend (vegetable)
print(len(list))
# CODE 2
list1=Items. append (vegetable)
print(len(list1))
What will be the outputs of the following?
(a) Code 1 : 5 Code 2 : 6
(b) Code 1 : 6 Code 2: 5
(c) Code 1: 5 Code 2: 5
(d) Code1: 6 Code 2: 6
ii. Suppose before going to the store his mother gives him another list ,
vegetable=[“tomato”, ”onion”]
Amit writes the following code:
List=Items. extend (vegetable)
print(list)
Tell him the output of the above code :
(a) [[“cake” , ”balloons”, ”pizza”, ”burger”],[“tomato”, ”onion”]]
(b) [“cake”, ”balloons”, ”pizza”, ”burger”,[“tomato”, ”onion”]]
(c) [“cake”, ”balloons”, ”pizza”, ”burger”, “tomato”, ”onion”]
(d) None of the above
iii. Now Amit has the two list :
Items=[“cake”,”balloons”,”pizza”,”burger”]
vegetable=[“tomato”, ”onion”]
Now Amit wants to delete the last element of list Items .Help him to do so
(a) del Items[3]
(b) pop(3)
(c) pop()
(d) Any of the above
iv. Help Amit to add “icecream” as second element in list Items
Items=[“cake”,”balloons”,”pizza”,”burger”]
(a) Items.insert (1, ”icecream”)
(b) Items.insert(2, ”icecream”)
(c) Items.insert(“icecream”)
(d) Items.insert(4,”icecream”)
47. Assertion (A): We can use a list as a key in a dictionary.
Reason(R): List is a mutable type and keys of dictionary must be an immutable
type
i. Both the A and R are true and R is the correct explanation for A
ii. A is true and R is false and R is the correct explanation for A
COMPUTER SCIENCE-XII 18
iii. A is false but the R is true and R is the correct explanation for A
iv. Both the A and R are false
48. Assertion(A) : pop() is used to remove an element from list but not in tuple.
Reason(B) : List and tuples support two way indexing.
i. Both the A and B is true and R is the correct explanation for A
ii. A is true and R is true and R is not the correct explanation for A
iii. A is false but the R is true and R is the correct explanation for A
iv. Both the A and R are false
49. Assertion (A) : Keys in a Python dictionary should be unique.
Reason (R) : Only immutable data types can be used as keys.
i. A is true but R is false.
ii. A is false but R is true.
iii. Both A and R are false.
iv. Both A and R are true but R is not the correct explanation of A.
v. Both A and R are true and R is the correct explanation of A.
50. Assertion (A) : for loop is used to iterate or read a sequence.
Reason (R) : while loop runs till a condition is true
i. A is true but R is false.
ii. A is false but R is true.
iii. Both A and R are false.
iv. Both A and R are true but R is not the correct explanation of A.
v. Both A and R are true and R is the correct explanation of A.
51. Assertion (A) : To stop execution of a loop ‘break’ is used.
Reason (R) : ‘break’ when executed takes the control out of loop as ‘break’ is
an example of jump statement.
i. A is true but R is false.
ii. A is false but R is true.
iii. Both A and R are false.
iv. Both A and R are true but R is not the correct explanation of A.
v. Both A and R are true and R is the correct explanation of A.
COMPUTER SCIENCE-XII 19
ANSWER KEYS
1 iii 2 iv 3 i 4 ii
5 iv 6 iii 7 iii 8 ii
9 i 10 iii 11 iv 12 iv
13 iii 14 iv 15 i 16 iii
17 1 18 iii 19 i 20 i
21 iii 22 iv 23 i 24 i
25 i 26 ii 27 iv 28 ii
29 iii 30 iv 31 iv 32 ii
33 iv 34 i 35 ii 36 i
37 iv 38 i 39 ii 40 i
46.iv a 47 iii 48 iv 49 ii
50 iv 51 v
COMPUTER SCIENCE-XII 20
WORKING WITH FUNCTIONS
Set-1
3. A module function only be used after including the module using ______
statement:
import random
x = random.random()
y= random.randint(0,4)
print(int(x),”:”, y+int(x))
return a*3,b*3,c*3
val=cal(10,12,14)
print(val)
i. [30, 24, 28] ii. [30,36,42] iii. (10, 20, 30) iv. (30,36,42)
COMPUTER SCIENCE-XII 21
i. A global variable ii. A volatile variable
return p*t*r
Considering the above defined function which of following function call are legal.
1. Interest(p=1000,c=5)
2. Interest(r=0.05,5000,3)
3. Interest(500,t=2,r=0.05)
4. Interest(c=4,r=0.12,p=5000)
11. A variable declared outside all the functions in a python program, then
mention the statements which are True in the context of the variable.
def ABC(A):
print(A.end=’’)
print(ABC(‘hello’))
COMPUTER SCIENCE-XII 22
Reason (R) : Syntactically, it would be impossible for the interpreter to decide
which values match which arguments if mixed modes were allowed while
providing default arguments.
def fn(a):
print(a)
x=90
fn(x)
print(l)
gfg(2)
16. Consider the following program. What is the correct flow of execution of
statements:
1. def fun1(m, n):
2. c=m+n
3. print(c)
4. return c
5. x = 10
6. y = 20
7. fun1(x,y)
COMPUTER SCIENCE-XII 23
8. print(“OK”)
(a) 1,2,3,4,5,6,7,8 (b) 5,6,7,1,2,3,4,8
(c) 5,6,1,2,3,4,7,8 (d) 7,8,1,2,3,4,5,6
17. What is the maximum and minimum value of z in following program:
import random
x = random.randint(2,6)
y = random.randrange(1,2)
z=x+y
print(z)
(a) min: 1 max: 2 (b) min: 2 max: 6
(c) min: 1 max: 8 (d) min: 3 max: 7
CASE BASED
18. Lalit is a game programmer and he is designing a game where he has to use
different python functions as much as possible. Apart from other things,
following functionalities are to be implemented in the game.
(1) The players have to input their names and Lalit has to remove the
unnecessary blank spaces from the name.
(2) He is simulating a dice where random number generation is required.
(3) Since the program becomes too lengthy, Lalit wants a separate section
where he can store all the functions used in the game program.
(4) He wants to implement usage of less memory so he doesn’t want to
include all the functions stored in separate sections.
(5) In the game, one source object generates and throws balls and the player
has to catch the balls. Here the distance and time is to be calculated so that
the program can check whether the ball was caught or missed by the
player.
Lalit is feeling difficulty in implementing the above functionalities. Help
him by giving answers following questions:
i. In functionality (1), which python module and function should be used:
(a) remove() function of string module
(b) split function()
(c) trim() function of string module
(d) strip() function of string module
ii. To implement functionality (2) which module can be used:
(a) random (b) randomise (c) randint (d) math
iii. In functionality (3), Lalit should use
(a) In-built functions
(b He should write another Python program
(c) He should use a module with all the required functions
COMPUTER SCIENCE-XII 24
(d) He should make a separate section in the same Python program
iv. To implement functionality (4), which syntax is correct
(a) import <function> from <module>
(b) from <module> import <function>
(c) import all
(d) import <function>
v. Which function is not the built-in Python function
(a) input() (b) len() (c) sqrt() (d) pow()
19. One student who is learning Python, is making a function-based program to
find the roots of a quadratic equation. He wrote the program but he is getting
some error. Help him to complete the task successfully:
from ……… import sqrt
def quad(b,c,a=1):
x = b*b-4*a*c
if x<0:
return "Sorry, complex root(s)"
d = sqrt(x)
r1 = (-b + d)/(2*a)
r2 = (-b - d)/(2*a)
return r1,r2 #line 9
print(quad(1,1,2))
root = quad(3)#line 11
rt = quad(2,1) #line 12
i. Which python module should be used in line 1
ii. (A) random (B) Math(C) math (D) Either (B) or (C)
He is getting an error in #line 9. What may be the error?
(a) Syntax error (b) Indentation error
(c) Logical Error (d) NameError
iii. Which statement is correct with reference to above program
(a) Two return statements are used and a function can use only one return
statement
(b) Required module is not given
(c) Syntax error in line 4
(d) Error in line 11
iv. Which type of argument method is used in line 12
(a) Positional arguments (b) Default arguments
(c) Keyword arguments (d) Variable length arguments
20. We can pass the argument in the function call in any order using…
a. Keyword argument
COMPUTER SCIENCE-XII 25
b. Variable Length argument
c. No argument
d. D. default argument
21. Assertion (A) : Every function definition starts with a valid function
header,there after function body so that it can be used.
COMPUTER SCIENCE-XII 26
i. Identify the global variable in above code:
a. x b. y c. r d.None
ii. Identify the variable used as default parameter in above code:
a. x b. y c. r d.None
iii. In above code which concept have been used
a. Modular approach
b. xy() is Nested function
c. selection or branching of statement
d. all the above
iv. Select the option that correctly represent the order of execution of
statements.
a. 123456789
b. 12797823489
c. 1279823459
d. 127892789
ANSWER KEYS
5 iv 6 ii 7 ii 8 iii
13 ii 14 iv 15 ii 16 b
19.iii d 19.iv a 20 a 21 V
22 v 23 a 24.i a 24.ii b
24.iii d 24.iv b
COMPUTER SCIENCE-XII 27
WORKING WITH FUNCTIONS
Set-2
1. Predict the correct output:
def FUN(x1,x2,x3=12):
print(x1+x2+x3,end='@')
t=[x1,x2,x3]
t=[10,30]
FUN(x2=10,x3=20,x1=40)
print(t)
print(type(two))
change(1,2,3,4)
COMPUTER SCIENCE-XII 28
def f1(a,b=[]):
b.append(a)
return b
print(f1(2,[3,4]))
s=0
while a>0:
s=s+a%10
a=a//10
return s/b
x=23
print(test(x)+test())
print(a,b,c)
a) SHOW(4,c=5) b) SHOW(a=2,c=5)
c) SHOW(b=1,a=7) d) SHOW(a=7,b=1)
8. Which of the following function headers is correct?
a) def fun(a = 2, b = 3, c) b) def fun(a = 2, b, c = 3)
def cube():
COMPUTER SCIENCE-XII 29
#missing statement
a**=3
cube()
print (a)
10. If return statement is not used inside the function, the function will
return:
i=0
def change(i):
i=i+1
return i
change(1)
print(i)
a) 1
b) Nothing is displayed
c) 0
d) Error
12. What happens if a local variable exists with the same name as the global
variable you want to access?
a) Error
b) The local variable is shadowed
c) Undefined behavior
d) The global variable is shadowed
13. Given the following function fun1().Select the invalid function call:
def fun1(name, age):
print(name, age)
a. fun1(name=’Emma’, age=23)
b. fun1(name=’Emma’, 23)
COMPUTER SCIENCE-XII 30
c. fun1(‘Emma’, 23)
d. fun1(23,’Emma’)
e="butter"
def fy(a):
print(a)+e
fy("bitter")
a) error
b) butter
error
c) bitter
error
d) bitterbutter
A=[12,45]
def update(B):
B+=[33]
print(B,end=’,’)
update(A)
print(A)
c) error
d) None of above
A=[12,45]
def update(B):
COMPUTER SCIENCE-XII 31
B=B+[33]
print(B,end=’,’)
update(A)
print(A)
def display(a):
a1=''
for i in range(0,len(a)):
if(_________):#code 1
a1=a1+"*"
elif(_________): #code 2
a1=a1+"&"
elif(_________): #code 3
a1=a1+_________ #code 4
else:
a1=a1+'@'
print(a1)
display("Welcome 2 All")
Now answer the following questions on the basis of above code:
COMPUTER SCIENCE-XII 32
a. a(i).isdigit()
b. a[i].isdigit()
c. a[i].digit
d. a.digit(i)
iii. Write python expression at code 3 to check is character at ith index is a a
letter.Select the correct option from the following:
a. a(i).letter()
b. a[i].alpha()
c. a[i].isalpha()
d. a.isalpha(i)
iv. Write python expression at code 4 to check is character at ith index is a capital
letter.Select the correct option from the following:
a. a(i).caps()
b. a[i].cap()
c. a[i].isuppper()
d. a.isupper(i)
city='LKO'
def account(name,acno,ct,bal=1200):
global branch,city
city=ct
branch=city
bal+=5000
return name,acno,branch,bal
p=account('adesh',123,'Cuttack')
print(p)
p=account(ct='delhi',name='sumit',bal=6500,acno=124)
print(p,branch,city)
Now answers the questions :
i. _____________ is default parameter used in above code.
a. bal
b. Cuttack
c. city
COMPUTER SCIENCE-XII 33
d. ct
ii. ______ are global variables used in above code.
a. city,branch
b. city,branch,p
c. city,branch,ct
d. both a and c
iii. ___________ are positional arguments used.
a. name,acno,ct,bal
b. name,acno,ct
c. 'adesh',123,'Cuttack'
d. ct='delhi',name='sumit',bal=6500,acno=124
iv. ___________ are keyword or named arguments used.
a. name,acno,ct,bal
b. name,acno,ct
c. 'adesh',123,'Cuttack'
d. ct='delhi',name='sumit',bal=6500,acno=124
v. What output above code will generate on execution? Select the correct
option.
a. ('adesh', 123, 'Cuttack', 6200)
('sumit', 124, 'delhi', 11500) delhi delhi
b. ('adesh', 123, 'Cuttack', 6200)
('sumit', 124, 'delhi', 11500) delhi LKO
c. ('adesh', 123, 'Cuttack', 6200)
('sumit', 124, 'delhi', 11500) delhi LKO
d. ('adesh', 123, 'Cuttack', 6200)
('sumit', 124, 'DELHI', 11500) DELHI delhi
19. The parameters that appear in function header are called___________ and the
parameters that appear in function call are called ____________.
a. actual,formal
b. formal,actual
c. keyword,positional
d. both b and c
COMPUTER SCIENCE-XII 34
P: return is not mandatory in every function body.
a. P is only correct
b. P and S are correct
c. P and R are correct
d. only Q is correct
a. ceil()
b. floor()
c. type()
d. random()
a. random()
b. randrange()
c. randint()
d. None
q=4
def ABC(c=34,d=20):
c+=d
d-=10
return c+d+PQR(c//d)
def PQR(T):
return T**2
a=PQR(q)
print(a*q**3,end='#')
print(ABC(a+q))
select the correct option:
COMPUTER SCIENCE-XII 35
a. 1024#64
b. 1024#66.0
c. 1024#66
d. error
24. Identify the correct order as per name scope resolution rule used by
python when there are following scopes or environments in a program:
a. LGEB
b. BGEL
c. LEGB
d. LEBG
a. built-in
b. module
c. user defined
d. all of above
def result():
return 2-10*(10+6)//5%2**3**2
a. 30
b. -30
c. -32
d. 2.0
COMPUTER SCIENCE-XII 36
ANSWER KEYS
1. c) 70@[10,30] 14. c)
2. d) 4 15. a)
3. a) 4 16. b)
6. a) 5.75 19. b
7. d) SHOW(a=7,b=1) 20. c
8. c) def fun(a, b = 2, c = 3) 21. c
9. c) global a 22. a
13. b) 26 B
COMPUTER SCIENCE-XII 37
DATA FILE HANDLING
Set-1
COMPUTER SCIENCE-XII 38
d. tell()
8. Ravi wants to read and write data in following form in python.What kind of file
Ravi should work with for better processing of following data?
a. text file
b. binary file
c. csv file
d. program file
9. Ravi wants to separate data in each row of a csv file using tab delimiter.For that
he must use _______statement
a. Csv.writer(filehandle,delimiter=’\t’)
b. csv.writer(filehandle,delimiter=’\t’)
c. csv.writer(filehandle,sep=’\t’)
d. filehandle.writer(csv,sep=’\t’)
10. To write the following data type to a csv file ___________ method is used .
p=[[‘a’,’b’],[‘1’,’2’]]
a. writelines()
b. writerows()
c. write()
d. dump()
11. Select the option that defines the correct form of using seek().
a. Fileobject.seek(10,0)
b. Fileobject.seek(10,-1)
c. Fileobject.seek(10,2)
d. Fileobject.seek(10,3)
12. Assertion(A): A text file consists of human readable characters,
COMPUTER SCIENCE-XII 39
d. Both A and R are true but R is not the correct explanation of A.
e. Both A and R are true and R is the correct explanation of A.
13. Which of the following commands can be used to read “n” number of
characters from a file using the file object <file>?
a. file.read(n)
b. n = file.read()
c. file.readline(n)
d. file.readlines()
14. Which of the following commands is used to open a file “c:\temp.txt” in
append-mode?
a. outfile =open(“c:\\temp.txt”, “a”)
b. outfile= open(“c:\\temp.txt”, “rw”)
c. outfile= open(“c:\temp.txt”, “w+”)
d. outfile =open(“c:\\temp.txt”, “r+”)
15. What is the description of `r+b` in binary mode?
a. read and write b. write and read
c. read only d. none of these
16. Which of the following parameter needs to be added with open function to
avoid blank row followed file each row in CSV file?
a. delimiter b. newline
c. writer, delimiter d. file object
17. Trying to open a binary file using a text editor will show:
a. Garbage values b) ASCII values
c) Binary character d) Unicodes
18. A file maintains a __________ which tells the current position in the file where
writing or reading will take place.
a. line b. file pointer c. list d. order
19. Which of the following file modes opens a file for appending and reading in a
binary file and moves the files pointer at the end of the file if the file already
exists or creates a new file?
a. .a b. .a+ c. .ab+ d. .ab
20. Aishwarya is running her own boutique business. She wants to store data of
all orders permanently and fast processing of data through her boutique
software. Suggest her to choose the appropriate technique among the following.
a. She can use Python Dictionaries with Text files.
b. She can use Python Dictionaries with Binary file concept.
c. She can use Python Lists without the Binary files concept.
d. She can use Python Dictionaries without the Binary file concept.
COMPUTER SCIENCE-XII 40
21. A programmer has confusion in understanding the behaviour of opening a
file in "w" mode. Clear his/her confusion, by suggesting the correct option
among the given below.
The behavior of "w" mode is:
a. Opening fails if the file already exists already.
b. Opening fails if the file does not exist already.
c. Opening will be succeeded if file exists with data and keeps the data intact.
d. Opening will be succeeded, if the file exists replaces the contents, do not
exist, creates a new file.
22. Rajat is a class 12 student and he has created a text file named names.txt. He
wants to display all the names contained in the text file. He has written one of
the following codes and succeeded in getting the output. Guess which among the
following option might have given the correct output:
a. names = open("names.txt", "r")
for line in names:
print(names)
b. names = open("names.txt", "r")
for line in names:
print("line")
c. names = open("names.txt", "r")
for line in names:
print(line)
d. names = open("names.txt", "r")
for names in line:
print(line)
23. Given the following directory structure. Assume that the current working
folder is in the feline folder.What is the relative path to the file bears.gif?
a) C:/animals/ursine b) animals/ursine
c) ..ursine/bears.gif d)None of the above.
24. In a program, there is a need of reading whole content of a textfile in a single
shot and store it in the form of list. Suggest the best option among the following
a) read() b) readline()
c) readlines() d) None of the above
25. When a file is opened in “a” mode, the file pointer is placed at
a) the beginning of the file. b)The end of the file.
c) the middle of the file. d) the current position of the file.
26. (A) : If a file is opened using the “with” statement, you get better syntax and
exceptions handling.
(B): When a file is opened using the “with” statement, it need not be closed
using theclose() function.
In the above two statements, which of the following is true?
COMPUTER SCIENCE-XII 41
a) Both A and B are Wrong
b) A is Wrong, but B is right.
c) A is right , but B is Wrong
d) Both A and B are right
27. Tom, during Practical Examination of Computer Science, has been assigned
an incomplete search() function to search in a text file “CAMP.txt”. The file
“CAMP.txt” iscreated by his Teacher and the following information is known about
the file
• File contains details of camp describing events of an adventure camp in
textformat
• File contains details of adventure activities like caving, trekking, paragliding,
rafting and rock climbing .Tom has been assigned the task to complete the code
and print the number of the word trekking
def search():
f = open("CAMP.txt",____) #Statement-1
A=____________________ #Statement-2
ct=0
for x in A:
p=x.split()
if p==”trekking”:
ct+=1
print(ct) _______________________# Statement-3
i. In which mode Rajitha should open the file in Statement-1?
a) r b) r+ c) rb d) wb
ii. Name the function that can be used by Rajitha to read the content of the file
in statement-2.
a) f.read( ) b) f.readline () c) f.readlines( ) d)f.readl()
iii. Which statement should Rajitha use in Statement 3 to close the file.
a) file.close() b) close(file) c) f.close() d) close()
28. Ajay is studying in an Engineering College in CSE branch. His sister, a class 12
student of Computer Science comes to him one day asking him the difference
between r+ and w+ modes of a file. What is the correct answer Ajay would give to
his sister?
a. No difference between r+ and w+
b. In r+ mode, the file is created if it does not exist and erases the content if the
file already exists; w+ raises an error if the file does not exist.
c. In w+ mode, the file is created if it does not exist and erases the content if
the file already exists; r+ raises an error if the file does not exist.
d. Depends on the operating system
29. What is the expected output of the given code?
f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
COMPUTER SCIENCE-XII 42
break
print(f.closed)
a) True b) False c) None d) Error
COMPUTER SCIENCE-XII 43
d1=f.read(5)
print(d)
print(d1)
a) Welcome to python program b) Welco
c) error d) None
34. What happens if no arguments are passed to the seek function?
a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error
35. How many arguments passed to the tell()?
a. 0
b. 1
c. 2
d. variable number of arguments
36. The character that separates values in csv files is called the ………
a) delimit
b) delimiter
c) delimited
d) sep
37. The default delimiter of csv file is ……………
a) comma
b) colon
c) semicolon
d) hyphen
38. To specify a different delimiter while writing into csv file, ……. argument is
used with csv.writer().
a) delimit
b) delimiter
c) delimited
d) delimits
39. To cancel the EOL translation in csv file while writing the data …………
argument is used with open().
a) newline
b) next
c) open
d) EOL
40. Which function is not used for binary file when using pickle module?
a) load()
b) dump()
c) writerow()
d) open()
41. Identify the type of data type that writerows() will write in a csv file.
COMPUTER SCIENCE-XII 44
a) [ ] b) ( ) c) [[],[]] d.any type
CASE BASED:
43. Mohan kumar is attempting a practice test and he has problem at some of the
following statements.Help him to answer the following questions.
def rt():
p=[]
a=open('sports.txt','w')
a.write('cricket is great game'+'\n')
a.write('India has many names in cricket')
a.close()
def ct():
with open('sports.txt') as p:
k=p.tell()
print(k) #statement 1
print(p.read(4)) #statement 2
print(p.readline(2)) #statement 3
print(p.tell()) #statement 4
p.seek(0,2)
print(p.readlines()) #statement 5
rt()
ct()
i. What output will be displayed at statement 1?
a. 1 b.2 c.-1 d.0
ii. What output will be displayed at statement 2?
a. cric b.cri c.crick d.error
iii. What output will be displayed at statement 3?
COMPUTER SCIENCE-XII 45
a. 'cricket is great game'
b. 'ket is great game'
'India has many names in cricket'
c. ke
d. error
iv. What output will be displayed at statement 4?
a. 2 b.6 c.52 d.4
v. What output will be displayed at statement 5?
a. [ ] b.( ) c.read error d.-1
ANSWER KEYS
1 d 2 a 3 b 4 a
5 c 6 d 7 c 8 c
9 b 10 b 11 a 12 d
13 b 14 a 15 a 16 b
17 a 18 b 19 c 20 d
21 d 22 b 23 c 24 C
25 b 26 d 27.i a 27.ii c
27.iii c 28 c 29 a 30 A
32.iv b 32.v b 33 c 34 d
35 b 36 b 37 a 38 b
39 a 40 c 41 c 42 c
43.v a
COMPUTER SCIENCE-XII 46
DATA FILE HANDLING
Set-2
1. Which of the following statements are true regarding the opening modes
of a file?
A. When you open a file for reading, if the file does not exist, an error
occurs.
B. When you open a file for reading, if the file does not exist, the program
will open an empty file.
C. When you open a file for writing, if the file does not exist, a new file is
created.
D. both A and C
2. Which of the following commands can be used to read the entire contents
of a file as a string using the file object ‘tmpfile’?
A. tmpfile.read(n)
B. tmpfile.read()
C. tmpfile.readline()
D. tmpfile.readlines()
3. Observe the following code carefully and answer the questions that
follows:
File = open("Mydata","w")
_____ #Blank1
File. Close()
(i) What type (Text/Binary) of file is My data?
(A) Binary file (B) Text File (C) CSV File
(ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”.
(A) File.writerow(“ABC”)
(B) pickle.dump(“ABC”,File)
(C) File.write(“ABC”)
(D) None of the above
4. What will be the output of the following code snippet?
fo = open("myfile.txt", "w+")
seq="TechBeamers\nHello Viewers!!"
fo.writelines(seq )
fo.seek(0,0)
for line in fo:
print (line)
fo.close()
A. TechBeamers
Hello viewers!!
B. Name of the file: myfile.txt TechBeamers Hello Viewers!!
C. TechBeamers Hello viewers!!
COMPUTER SCIENCE-XII 47
D. TechBeamers
Hello viewers!!
5. with open("hello.txt", "w") as f:
f.write("Hello World")
with open('hello.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.split()
print (words)
f.close()
A. Runtime Error
B. Hello World how are you today
C. [‘Hello’, ‘World’]
D. Hello
World
6. What will be the output of the following code snippet?
f = open("data.txt", "w+")
txt = "Python\n"
f.writelines( txt )
seq = " Is\nFun"
f.seek(0, 2)
f.writelines( seq )
myList = []
f.seek(0)
for line in f:
myList.append(line)
print(myList)
f.close()
A. Runtime Error
B. [‘Python\n’, ‘ Is\n’, ‘Fun’]
C. [‘ Is\n’, ‘Fun’]
D. [‘Python’, ‘Is’, ‘Fun’]
7. What will be the output of the following code snippet?
colors = ['red\n', 'yellow\n', 'blue\n']
f = open('colors.txt', 'w')
f.writelines(colors)
f.close()
f.seek(0,0)
for line in f:
COMPUTER SCIENCE-XII 48
print (line)
A. red yellow blue
B. [‘red\n’, ‘yellow\n’, ‘blue\n’]
C. Runtime Error
D. Compilation error
8. Give the output of the following:
a="abcdef"
with open("a.txt",'w') as b:
b.write(a)
with open('a.txt','r') as b:
t=b.read(3)
print(t+'abc')
(a) abc
(b) def
(c) defabc
(d) abcabc
9. Give the output of the following:
a=open('pqr.txt','w')
a.write("12345")
a.close()
a=open('pqr.txt','r')
t=a.readlines()
p=type(t)
print(len(t),p,sep='$$')
a.close()
(a) ['12345']$$<class 'list'>
(b) 1$$<class 'list'>
(c) 1$$<class ‘str’>
(d) error
10. Give the output of the following:
a="abcdef8\npqr345"
with open("a.txt",'w') as b:
b.write(a)
q=open('a.txt','r')
q.seek(4)
t=q.read(3)
print(t)
(A) abcdef
(B) def
(C) ef8
(D) error
COMPUTER SCIENCE-XII 49
11. Identify the line no. which will generate an error.
import pickle as pd #Line-1
f=open(‘data.txt','wb') #Line-2
pickle.load("123",f) #Line-3
f.close() #Line-4
(A) Line-1
(B) Line-2
(C) Line-3
(D) None of the above
12. When a file is opened in append mode the file pointer is at the end of file
and anything written on it is added at the end of file.
(A) True (B) False
13. Give output of the following code:
import pickle as p
d1={'a':12,'b':20,'c':50}
d2={'a':14,'b':21,'c':30}
FILE=open('abc.dat','wb')
p.dump(d2,FILE)
p.dump(d1,FILE)
FILE.close()
FILE=open('abc.dat','rb')
d1=p.load(FILE)
print(sum(d1.values()))
FILE.close()
COMPUTER SCIENCE-XII 50
(ii) Write the appropriate code for statement-2 to get the current position of
file pointer.
(A) a.seek(0) (B) a.tell() (C) a.tell(0) (D) a.seek(0,0)
(iii) Write the appropriate code for statement-3 to place the pointer at the
beginning of desired record.
(A) a.seek(0,0) (B) a.seek(pos) (C) a.seek(0,2) (D)
a.seek(0,1)
(iv) Write the appropriate code for statement-4 to overwrite the desired
record with the modified values.
(A) pic.dump(r) (B) pic.dump(a,r) (C) pic.dump(r,a) (d)
pic.dump(a)
15. If a file ‘q.txt’ contains following text:
‘we are one.We can complete the task easily’
Now give output of :
a=open(q.txt,’r’)
print(a.tell( ),end=’,’)
p=a.read(5)
a.seek(11,0)
print(a.tell( ))
A) ‘w,’a’ B) 1,12 C) 0,16 D) 0,11
16. The process of converting a byte stream to a Python Object is
called_______.
A) Serialization
B) Deserialization
17. Give output of the following code:
import pickle as pic
b=open('bi1.txt','wb')
L=[['aman',1,67],['raman',6,90],['ratan',7,89]]
L1=[['amit',2,77],['ram',16,99],['ratna',17,79]]
pic.dump(L,b)
pic.dump(L1,b)
b.close()
#search in binary file
b=open('bi1.txt','rb')
L=pic.load(b)
for i in L:
if i[2]>70:
print(i)
b.close()
A) ['ratan', 7, 89]
B) ['ratan', 7, 89]
C) ['ratan', 7, 89], ['ram',16,99]
D) ['raman', 6, 90]
['ratan', 7, 89]
COMPUTER SCIENCE-XII 51
18. Which of the following command is used to open a file “d:\temp.csv” for
reading and writing mode both?
a) csv.writer(delimiter=’|’)
b) csv.writer(f, separator=’|’)
c) csv.writer(f,delimiter='|')
d) None of the above
22. Observe the code given below. Write the missing statement to write
records of two products to a csv file at one go.
import csv
products=[['mouse',340,5],['keyboard',680,3]]
COMPUTER SCIENCE-XII 52
f=open('d:\\products.csv','w')
wr=csv.writer(f)
_________________ #missing statement
f.close()
a) csv.writerows(products)
b) wr.writerow(products)
c) wr.writerows(products)
d) wr.writerows(products,f)
23. Write the missing statement to remove EOL character from the file.
import csv
f=open('marks.csv','w',__________) #fill the missing statement
wr=csv.writer(f)
a) EOL=False
b) EOL=’\n’
c) removeEOL(true)
d) newline=''
24. Mrinal, the programmer at BigShopper is writing a program to create a
CSV file “shopping.csv” which will contain product name and price for
all entries. He has written the following code. As a programmer, help
him to successfully execute the given task.
import______ # Line 1
def addCsvFile(PName,Price): # to data into the CSV file
f=open(' shopping.csv',' ___') # Line 2
FileWriter = csv.writer(f)
FileWriter.________([PName,Price]) #Line 3
f.close()
def readCsvFile(): # to read data from CSV file
with open(' shopping.csv','r') as File:
FileReader = csv.______(File) # Line 4
for row in FileReader:
print (row[0],row[1])
File.close()
addCsvFile(“Mouse”, 980)
addCsvFile(“Keyboard”, 1250)
addCsvFile(“Printer”, 8500)
readCsvFile()
(i) Name the module he should import in Line 1.
(a) pickle (b) csv (c) random (d) math
COMPUTER SCIENCE-XII 53
(ii) In which mode, Mrinal should open the file in Line 2 to add data into the
file?
(a) ‘r’ (b) ‘a’ (c) ‘w’ (d) ‘wb+’
(iii) Fill in the blank in Line 4 to read the data from a csv file.
(a) FileReader = csv.reader(File) (b) FileReader = csv.writer(File)
(b) FileReader = csv.load(File) (c) FileReader = csv.readData(File)
(iv) Write the missing statement on Line-3 to write data of products to a csv
file.
(a) FileWriter.writeData([PName,Price])
(b) FileWriter.dump([PName,Price])
(c) FileWriter.writerow([PName,Price])
(d) FileWriter.writerows([PName,Price])
25. 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', ‘w’,______ ) # 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:
if 'run' in row[0]:
print (row[0])
newFile.close()
addCsvFile("Arjun", "123@456")
addCsvFile("Arunima", "aru@nima")
addCsvFile("Frieda", "myname@FRD")
readCsvFile() #Line 4
(i) Name the module he should import in Line 1.
(A) pickle(B) math (C) csv (D) random
(ii) Write the appropriate code for Line-2 to remove EOL translation from
COMPUTER SCIENCE-XII 54
CSV file.
(A) removeEOL="" (B) removeEOL="\n" (C) newline="" (D)
newline="\n"
(iii) Fill in the blank in Line 3 to read the data from a csv file.
(A) reader (B) writer (C) readline() (D) read()
(iv) Write the output he will obtain while executing Line 4.
(A) Arunima (B) [‘Arunima’, ‘ aru@nima’] (C) No
Output
(D) Arunima
aru@nima
26.Following are CODE-1 and CODE-2.Select the option that gives the correct
output:
CODE-1 CODE-2
def rt(): def rt():
p=[] p=[]
a=open('sports.txt','w') a=open('sports.txt','w')
a.write('hello') a.write('hello')
a.close() a.close()
def ct(): def ct():
with open('sports.txt','r+') as p: with open('sports.txt','w+') as p:
p.write('a') p.write('a')
p.seek(0) p.seek(0)
print(p.read()) print(p.read())
rt() rt()
ct() ct()
D)CODE-1: a CODE-2:aello
ANSWERS KEYS
2. B 15. D
3. (i) B (ii) C 16. B
COMPUTER SCIENCE-XII 55
4. A 17. D
5. C 18. D
6. B 19. A
7. C 20. D
8. D 21. C
9. B 22. C
10. C 23. D
11. C 24. (i) b)
(ii) ‘a’
(iii) a) FileReader = csv.reader(File)
(iv) b)FileWriter.writerow([PName,Price])
COMPUTER SCIENCE-XII 56