0% found this document useful (0 votes)
249 views86 pages

Multiple Choice Question Bank (MCQ) Term - I

The document provides a multiple choice question (MCQ) bank for Computer Science based on the CBSE exam pattern for the 2021-22 session. It covers topics related to computational thinking and programming including Python fundamentals like data types, operators, decision making and looping statements. The MCQ bank contains 29 questions with one correct option each to test understanding of Python concepts covered in Class 11.

Uploaded by

inventing new
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views86 pages

Multiple Choice Question Bank (MCQ) Term - I

The document provides a multiple choice question (MCQ) bank for Computer Science based on the CBSE exam pattern for the 2021-22 session. It covers topics related to computational thinking and programming including Python fundamentals like data types, operators, decision making and looping statements. The MCQ bank contains 29 questions with one correct option each to test understanding of Python concepts covered in Class 11.

Uploaded by

inventing new
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

MCQ - XII

Multiple Choice Question Bank


[MCQ ] Term – I
Computer Science [083]
Based on Latest CBSE Exam Pattern
for the Session 2021-22

1|Pa
ge
TERM-1

2|P ag
e
Unit -1 : Computational Thinking and Programming-2

Topic: Revision of python topics covered in class XI

KEY POINTS:
Introduction to Python
 Python is an open source, object oriented HLL developed by Guido van Rossum in
1991
 Tokens- smallest individual unit of a python program.
 Keyword-Reserved word that can’t be used as an identifier
 Identifiers-Names given to any variable, constant, function or module etc.

Classify the following into valid and invalid identifier


(i) Mybook (ii) Break (iii) _DK (iv) My_book (v) PaidIntrest (vi) s-num
(vii)percent (viii) 123 (ix) dit km (x) class
Ans:(i)valid(ii)Invalid (iii)Valid (iv)valid (v)valid (vi)invalid (‘-‘)is not allowed
(vii)valid(viii)invalid(First Character must be alphabet(ix)invalid (no space is
allowed) (x)invalid (class is a keyword)

 Literals- A fixed numeric or non-numeric value.


 Variable- A variable is like a container that stores values to be used in program.
 String- The text enclosed in quotes.
 Comment- Comments are non-executable statement begin with # sign.
 Docstring-Comments enclosed in triple quotes (single or double).
 Operator – performs some action on data
o Arithmetic(+,-,*,/,%,**,//)
o Relational/comparison (<,>, <=,>=, = =, !=).
o Assignment-(=,/=,+=,-=,*=,%=,**=,//=)
o Logical – and, or
3|P ag
e
o Membership – in, not in

4|P ag
e
 Precedence of operators:
( ) Parentheses Highest
** Exponentiation
~ x Bitwise nor
+x, -x Positive, Negative (Unary +, -)
*(multiply), / (divide),//(floor division), %(modulus)
+(add),-(subtract)
& Bitwise and
^ Bitwise XOR
| Bitwise OR
<(less than),<=(less than or equal),>(greater than), >=(greater than or
equal to), ==(equal),!=(not equal)
is , is not
not x Boolean NOT
and Boolean AND

or Boolean OR
Low
Data type:
There are following basic types of variable in as explained in last chapter:
Type Description
bool Stores either value True or False.
int Stores whole number.
float Stores numbers with fractional part.
Complex Stores a number having real and imaginary part (a+bj)
String Stores text enclosed in single or double quote
Stores list of comma separated values of any data type
List
between square [ ] brackets.(mutable )
Stores list of comma separated values of any data type
Tuple
between parentheses ( ) (immutable)
Unordered set of comma-separated key:value pairs ,
Dictionary
within braces {}

5|P ag
e
All questions are of 1 mark.
Q.No. Question
1. Which of the following is a valid identifier:
i. 9type ii. _type iii. Same-type iv. True
2. Which of the following is a relational operator:
i. > ii. // iii. or iv. **
3. Which of the following is a logical operator:
i. + ii. /= iii. and iv. in
4. Identify the membership operator from the following:
i. in ii. not in iii. both i & ii iv. Only i
5. Which one is a arithmetic operator:
i. not ii. ** iii. both i & ii iv. Only ii
6. 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
7. What will be the correct output of the statement : >>> 4+2**2*10
i. 18 ii. 80 iii. 44 iv. None of the above
8. Give the output of the following code:
>>> a,b=4,2
>>> a+b**2*10
i. 44 ii. 48 iii. 40 iv. 88
9. Give the output of the following code:
>>> a,b = 4,2.5
>>> a-b//2**2
i. 4.0 ii. 4 iii. 0 iv. None of the above
10. 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
11. If a=1,b=2 and c= 3 then which statement will give the output as : 2.0 from the following:
i. >>>a%b%c+1 ii. >>>a%b%c+1.0 iii. >>>a%b%c iv. a%b%c-1
12. Which statement will give the output as : True from the following :
i. >>>not -5 ii. >>>not 5 iii. >>>not 0 iv. >>>not(5-1)
13. Give the output of the following code:
>>>7*(8/(5//2))
i. 28 ii. 28.0 iii. 20 iv. 60
14. 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
15. What will be the output of the following code:
>>>import math
>>>math.fabs(-5.03)
i. 5.0 ii. 5.03 iii. -5.03 iv . None of the above
Single line comments in python begin with….......................symbol.
16. i. # ii. “ iii. % iv. _
17. Which of the following are the fundamental building block of a python program.
i. Identifier ii. Constant iii. Punctuators iv. Tokens
18. The input() function always returns a value of.......................type.
i. Integer ii. float iii. string iv. Complex
19. ……….. function is used to determine the data type of a variable.
i. type( ) ii. id( ) iii. print( ) iv. str( )
20. The smallest individual unit in a program is known as a……………
i. Token ii. keyword iii. punctuator iv. identifier
15 | P a g
e
FLOW OF EXECUTION
#Decision making statements in python

Description
Statement
An if statement consists of a boolean expression
if statement
followed by one or more statements.
An if statement can be followed by an optional else
if...else statement statement, which executes when the boolean
expression is false.
If the first boolean expression is false, the next is
checked and so on. If one of the condition is true ,
if…elif…else
the corresponding statement(s) executes, and the
statement ends.
It allows to check for multiple test expression and
nested if…else statements execute different codes for more than two
conditions.

#Iteration or Looping construct statements in python

Description
Loop
for loop:
for<ctrl_var>in<sequence>:
It is used to iterate/repeat ifself over a range of
<statement in loop body>
values or sequence one by one.
else:
<statement>
while loop:
while<test_exp>:
The while loop repeatedly executes the set of
body of while
statement till the defined condition is true.
else:
body of else

16 | P a g
e
21. Which of the following is not a decision making statement
i. if..else statement ii. for statement iii. if-elif statement iv. if statement

22. …………loop is the best choice when the number of iterations are known.
i. while ii. do-while iii. for iv. None of these

23. How many times will the following code be executed.

a=5
while a>0:
print(a)
print(“Bye”)

i. 5 times ii. Once iii. Infinite iv. None of these

24. What abandons the current iteration of the loop


i. continue ii. stop iii. infinite iv. Break

25. Find the output of the following python program

for i in range(1,15,4):
print(i, end=’,’)

i. 1,20,3 ii. 2,3,4 iii. 1,5,10,14 iv. 1,5,9,13


26. …………loop is the best when the number of iterations are not known.
i. while ii. do-while iii. for iv. None of these
27. In the nested loop.......................loop must be terminated before the outer loop.
i. Outer ii. enclosing iii. inner iv. None of these
28. …………..statement is an empty statement in python.
i. pass ii. break iii. continue iv. if
29. How many times will the following code be executed

for i in range(1,15,5):
print(i,end=’,’)

i. 3 ii. 4 iii. 1 iv. infinite


30. Symbol used to end the if statement:
i. Semicolon(;) ii. Hyphen(-) iii. Underscore( _ ) iv. colon(:)

String: Text enclosed inside the single or double quotes referred as String.
String Operations: String can be manipulated using operators like concatenation (+),
repetition (*) and membership operator like in and not in.
Operation Description
Concatenation Str1 + Str2
Repetition Str * x
Membership in , not in
Comparison str1 > str2
Slicing String[range]
17 | P a g
e
String Methods and Built-in functions:

Function Description
len() Returns the length of the string.
capitalize() Converts the first letter of the string in uppercase
split() Breaks up a string at the specified separator and returns a list of substrings.
replace() It replaces all the occurrences of the old string with the new string.
find() It is used to search the first occurrence of the substring in the given string.
It also searches the first occurrence and returns the lowest index of the
index()
substring.
It checks for alphabets in an inputted string and returns True in string
isalpha()
contains only letters.
isalnum() It returns True if all the characters are alphanumeric.
isdigit() It returns True if the string contains only digits.
It returns the string with first letter of every word in the string in uppercase
title()
and rest in lowercase.
count() It returns number of times substring str occurs in the given string.
lower() It converts the string into lowercase
islower() It returns True if all the letters in the string are in lowercase.
upper() It converts the string into uppercase
isupper() It returns True if all the letters in the string are in uppercase.
lstrip() It returns the string after removing the space from the left of the string
rstrip() It returns the string after removing the space from the right of the string
It returns the string after removing the space from the both side of the
strip()
string
It returns True if the string contains only whitespace characters, otherwise
isspace()
returns False.
istitle() It returns True if the string is properly title-cased.
swapcase() It converts uppercase letter to lowercase and vice versa of the given string.
ord() It returns the ASCII/Unicode of the character.
It returns the character represented by the imputed Unicode /ASCII
chr()
number
18 | P a g
e
31. Which of the following is not a python legal string operation.
i. ‘abc’+’aba’ ii. ‘abc’*3 iii. ‘abc’+3 iv. ‘abc’.lower()
32. Which of the following is not a valid string operation.
i. Slicing ii. concatenation iii. Repetition iv. floor
33. Which of the following is a mutable type.
i. string ii. tuple iii. int iv. list
34. What will be the output of the following code
str1=”I love Python”
strlen=len(str1)+5
print(strlen)
i. 18 ii. 19 iii. 13 iv. 15
35. Which method removes all the leading whitespaces from the left of the string.
i. split() ii. remove() iii. lstrip() iv rstrip()
36. It returns True if the string contains only whitespace characters, otherwise returns
False. i) isspace() ii. strip() iii. islower() iv. isupper()
37. It converts uppercase letter to lowercase and vice versa of the given string.
i. lstrip() ii. swapcase() iii. istitle() iv. count()
38. What will be the output of the following code.
Str=’Hello World! Hello Hello’
Str.count(‘Hello’,12,25)
i. 2 ii. 3 iii. 4 iv. 5
39. What will be the output of the following code.
Str=”123456”
print(Str.isdigit())
ii. True ii. False iii. None iv. Error
40. What will be the output of the following code.
Str=”python 38”
print(Str.isalnum())
iii. True ii. False iii. None iv. Error
41. What will be the output of the following code.
Str=”pyThOn”
print(Str.swapcase())
i. PYtHoN ii. pyThon iii. python iv. PYTHON
42. What will be the output of the following code.
Str=”Computers”
print(Str.rstrip(“rs”))
i. Computer ii. Computers iii. Compute iv. compute
43. What will be the output of the following code.
Str=”This is Meera\’ pen”
print(Str.isdigit())
i. 21 ii. 20 iii. 18 iv. 19
44. How many times is the word ‘Python’ printed in the following statement.
s = ”I love Python”
for ch in s[3:8]:
print(‘Python’)
i. 11 times ii. 8 times iii. 3 times iv. 5 times
19 | P a g
e
45. Which of the following is the correct syntax of string slicing:
i. str_name[start:end] iii. str_name[start:step]
ii. str_name[step:end] iv. str_name[step:start]
46. What will be the output of the following code?
A=”Virtual Reality”
print(A.replace(‘Virtual’,’Augmented’))
i. Virtual Augmented iii. Reality Augmented
ii. Augmented Virtual iv. Augmented Reality
47. What will be the output of the following code?
print(“ComputerScience”.split(“er”,2))
i. [“Computer”,”Science”] iii. [“Comput”,”Science”]
ii. [“Comput”,”erScience”] iv. [“Comput”,”er”,”Science”]
48. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
i. he ii. lo iii. olleh iv. hello
49. ………..function will always return tuple of 3 elements.
i. index() ii. split() iii. partition() iv. strip()
50. What is the correct python code to display the last four characters of “Digital India”
i. str[-4:] ii. str[4:] iii. str[*str] iv. str[/4:]

LIST: A list is a collection of comma-separated values (items) of same or different type


within square brackets. List types can be of three types:
1. Empty list 2. Long List 3. Nested List
2.
Built-in Function (Manipulating Lists)

Function Description
append() It adds a single item to the end of the list.
extend() It adds one list at the end of another list
insert() It adds an element at a specified index.
reverse() It reverses the order of the elements in a list.
index() It returns the index of first matched item from the list.
len() Returns the length of the list i.e. number of elements in a list
sort() This function sorts the items of the list.
clear() It removes all the elements from the list.
count() It counts how many times an element has occurred in a list and returns it.
It removes the element from the end of the list or from the specified index
pop()
and also returns it.
20 | P a g
e
It removes the specified element from the list
del Statement

It is used when we know the element to be deleted, not the index of the
remove()
element.
max() Returns the element with the maximum value from the list.
min() Returns the element with the minimum value from the list.
51. Given the list L=[11,22,33,44,55], write the output of print(L[: :-1]).
i. [1,2,3,4,5] ii. [22,33,44,55] iii. [55,44,33,22,11] iv. Error in code
52. Which of the following can add an element at any index in the list?
i. insert( ) ii. append( ) iii. extend() iv. all of these
53 Which of the following function will return a list containing all the words of the given string?
i . split() ii. index() i i i . count() iv. list()
54. Which of the following statements are True.
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. a,b,c iv. Only d
55. If l1=[20,30] l2=[20,30] l3=[‘20’,’30’] l4=[20.0,30.0] then which of the following
statements will not return ‘False’:
a. >>>l1==l2 b. >>>l4>l1 c. >>>l1>l2 d. >>> l2==l2
i. b, c ii. a,b,c iii. a,c,d iv. a,d
56. >>>l1=[10,20,30,40,50]
>>>l2=l1[1:4]
What will be the elements of list l2:
i. [10,30,50] ii. [20,30,40,50] iii. [10,20,30] iv. [20,30,40]
57. >>>l=[‘red’,’blue’]
>>>l = l + ‘yellow’
What will be the elements of list l:
i. [‘red’,’blue’,’yellow’] ii. [‘red’,’yellow’] iii. [‘red’,’blue’,’yellow’] iv. Error
58. What will be the output of the following code:
>>>l=[1,2,3,4]
>>>m=[5,6,7,8]
>>>n=m+l
>>>print(n)
i. [1,2,3,5,6,7,8] ii. [1,2,3,4,5,6,7,8] iii. [1,2,3,4][5,6,7,8] iv. Error
59. What will be the output of the following code:
>>>l=[1,2,3,4]
>>>m=l*2
>>>n=m*2
>>>print(n)

i [1,2,3,4,1,2,3,4,1,2,3,4] ii. [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4] iii. [1,2,3,4][4,5,6,7]


iv. [1,2,3,4]
60. Match the columns: if

>>>l=list(‘computer’)

Column A Column B

21 | P a g
e
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

61. If a list is created as


>>>l=[1,2,3,’a’,[‘apple’,’green’],5,6,7,[‘red’,’orange’]] then what will be the output of the
following statements:
>>>l[4][1]
i. ‘apple’ iii. ‘green’
ii. ‘red’ iv. ‘orange’
62. >>>l[8][0][2]
i. ‘d’ iii. ‘e’
ii. ‘r’ iv. ‘o’
63. >>>l[-1]
i. [‘apple’,’green’] iii. [‘red’,’orange’]
ii. [‘red’ ] iv. [’orange’]
64 >>>len(l)
i. 10 iii. 9
ii. 8 iv 11
65. 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]]
66. 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]
67. 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]
68. >>>l1=[10,20,30,40,50,60,10,20,10]
>>>l1.count(‘10’)
i. 3 ii. 0 iii. 2 iv. 9
69. Which operators can be used with list?
i. in ii. not in iii. both (i)&(ii) iv. Arithmetic operator only
70. Which of the following function will return the first occurrence of the specified element in a list.
i. sort() ii. value() iii. index() iv. sorted()

Tuples and Dictionary: Tuple is a data structure in python, A tuple consists of multiple
values in a single variable separated by commas. Tuples are enclosed within parentheses ( ).
Tuple is an immutable data type.
Common Tuple Operations:

22 | P a g
e
Operation Description
Concatenation Tuple1 + Tuple2
Repetition Tuple * x
Index Tuple.index(ele)
Count Tuple.count(ele)
Slicing Tuple[range]
Membership in and not in

Tuple Functions:
Function Description
del statement It is used to delete the tuple.
It returns the index of first matched item from the
index( )
tuple.
Returns the length of the tuple i.e. number of
len( )
elements in a tuple
It counts how many times an element has occurred
count( )
in a tuple and returns it.
It returns True if a tuple is having at least one item
any ( )
otherwise False.
It is used to sort the elements of a tuple. It returns
sorted( )
a list after sorting.
sum( ) It returns sum of the elements of the tuple.
Returns the element with the maximum value
max( )
from the tuple.
Returns the element with the minimum value from
min( )
the tuple.

Dictionary: Python Dictionaries are a collection of some key-value pairs .Dictionaries are
mutable unordered collections with elements in the form of a key:value pairs that associate
keys to values. Dictionaries are enclosed within braces {}
Function Description
It returns the content of dictionary as a list of
items( )
tuples having key-value pairs.
keys( ) It returns a list of the key values in a dictionary

23 | P a g
e
It returns a list of values from key-value pairs in a
values( )
dictionary
It returns the value for the given key ,if key is not
get( )
available then it returns None
copy( ) It creates the copy of the dictionary.
Returns the length of the Dictionary i.e. number
len( )
of key:value pairs in a Dictionary
It is used to create dictionary from a collection of
fromkeys( )
keys(tuple/list)
clear( ) It removes all the elements from the Dictionary.
It sorts the elements of a dictionary by its key or
sorted( )
values.
It removes the last item from dictionary and also
popitem( )
returns the deleted item.
Returns the key having maximum value in the
max( )
Dictionary.
Returns the key having minimum value in the
min( )
Dictionary.

71. 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.

72. ………function is used to convert a sequence data type into tuple.


i. List() ii tuple() iii TUPLE iv. tup()

73. It tup=(20,30,40,50), which of the following is incorrect


i. print(tup[3]) ii. tup[2]=55 iii. print(max(tup)) iv. print(len(tup))

74. Consider two tuples given below:

>>>tup1=(1,2,4,3)
>>>tup2=(1,2,3,4)

What will the following statement print(tup1<tup2)


i. True ii. False iii. Error iv. None of these

75. Which function returns the number of elements in the tuple


i. len( ) ii. max( ) iii. min( ) iv. count( )

24 | P a g
e
76. Which function is used to return a value for the given key.
i. len( ) ii. get( ) iii. keys( ) iv. None of these

77. Keys of the dictionary must be


i. similar ii. unique iii. can be similar or unique iv. All of these

78. Which of the following is correct to insert a single element in a tuple .


i. T=4 ii. T=(4) iii. T(4,) iv. T=[4,]

79. Which of the following will delete key-value pair for key=’red’ form a dictionary D1
i. Delete D1(“red”) ii. del. D1(“red”) iii. del D1[“red”] iv. del D1

80. Which function is used to remove all items form a particular dictionary.
i. clear( ) ii. pop( ) iii. delete iv. rem( )

81. In dictionary the elements are accessed through


i. key ii. value iii. index iv. None of these

82. Which function will return key-value pairs of the dictionary


i. key( ) ii. values( ) iii. items( ) iv. get( )
83 Elements in a tuple can be of..................type.
i. Dissimilar ii. Similar iii. both i & ii iv. None of these

84 To create a dictionary , key-value pairs are separated by…………….


i. (;) ii. ( , ) iii. (:) iv. ( / )
85 Which of the following statements are not correct:
a. An element in a dictionary is a combination of key-value pair
b. A tuple is a mutable data type
c. We can repeat a key in dictionary
d. clear( ) function is used to deleted the dictionary.
i. a,b,c ii. b,c,d iii. b,c,a iv. a,b,c,d
86 Which of the following statements are correct:
a. Lists can be used as keys in a dictionary
b. A tuple cannot store list as an element
c. We can use extend() function with tuple.
d. We cannot delete a dictionary once created.
i. a,b,c ii. b,c,d iii. b,c,a iv. None of these
87 Like lists, dictionaries are......................which mean they can be changed.
i. Mutable ii. immutable iii. variable iv. None of these
88 To create an empty dictionary , we use
i. d=[ ] ii. d =( ) iii. d = {} iv. d= < >
89 To create dictionary with no items , we use
ii. Dict ii. dict( ) iii. d = [ ] iv. None of these
90 What will be the output
>>>d1={‘rohit’:56,”Raina”:99}
>>>print(“Raina” in d1)
i. True ii. False iii. No output iv. Error
91 Rahul has created the a tuple containing some numbers as
>>>t=(10,20,30,40)
now he wants to do the following things help him

1. He want to add a new element 60 in the tuple, which statement he should use out of the
given four.

25 | P a g
e
i. >>>t+(60)
ii. >>>t + 60
iii. >>>t + (60,)
iv. >>>t + (‘60’)
92 Rahul wants to delete all the elements from the tuple, which statement he should use
i. >>>del t
ii. >>>t.clear()
iii. >>>t.remove()
iv. >>>None of these
93 Rahul wants to display the last element of the tuple, which statement he should use
i. >>> t.display()
ii. >>>t.pop()
iii. >>>t[-1]
iv. >>>t.last()
94 Rahul wants to add a new tuple t1 to the tuple t, which statement he should use
i. >>>t+t1
ii. >>>t.add(t1)
iii. >>>t*t1
iv. None of these
95 Rahul has issued a statement after that the tuple t is replace with empty tuple, identify the statement
he had issued out of the following:
i. >>> del t
ii. >>>t= tuple()
iii. >>>t=Tuple()
iv. >>>delete t
96 Rahul wants to count that how many times the number 10 has come:
i. >>>t.count(10)
ii. >>>t[10]
iii. >>>count.t(10)
iv. None of these
97 Rahul want to know that how many elements are there in the tuple t, which statement he should use
out of the given four
i. >>>t.count()
ii. >>>len(t)
iii. >>>count(t)
iv. >>>t.sum()
98 >>>t=(1,2,3,4)
Write the statement should be used to print the first three elements 3 times
i. >>>print(t*3)
ii. >>>t*3
iii. >>>t[:3]*3
iv. >>>t+t
99 Match the output with the statement given in column A with Column B
1. >>>tuple([10,20,30]) a. >>> (10,20,30)
2. >>>(“Tea”,)* 3 b. >>> 2
3. >>>tuple(“Item”) c. >>> ('Tea', 'Tea', 'Tea')
4. >>>print(len(tuple([1,2]))) d. >>> ('I', 't', 'e', 'm')

i. 1-b,2-c,3-d,4-a
ii. 1-a,2-c,3-d,4-b
iii. 1-c,2-d,3-a,4-a
iv. 1-d,2-a,3-b,4-c

26 | P a g
e
100 Write the output of the following code:
>>>d={‘name’:’rohan’,’dob’:’2002-03-11’,’Marks’:’98’}
>>>d1={‘name’:‘raj’)
>>>d1=d.copy()
>>>print(“d1 :”d1)
i. d1 : {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
ii. d1 = {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
iii. {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'}
iv. (d1 : {'name': 'rohan', 'dob': '2002-03-11', 'Marks': '98'})

27 | P a g
e
WORKING WITH FUNCTIONS

FUNCTION: A function is a subprogram that acts on data and often returns a value.
Python functions can belong to one of the following three categories:
1. Built-in Function 2. Functions defined in modules 3. User defined functions

Arguments and Parameters: The values being passed through a function call statement are
called argument (or actual parameter or actual argument).
The values received in the function definition/header are called parameter (or formal
parameter of formal argument)

Note: A function header cannot have expressions. It can have just names or identifiers.
Python supports three types of arguments/parameters:

1. Positional Argument (Required Arguments): The way of parameter and argument


specification is called Positional or Required arguments or Mandatory arguments

2. Default Arguments: A parameter having default value in the function header is known
as a default parameter.

3. Keyword (or named) Arguments: Keyword arguments are the named arguments with
assigned values being passed in the function call statement.
Rules for combining all three types of statements:
i. An argument list must first contain positional (required) arguments followed by any
keyword argument.
ii. Keyword arguments should be taken from the required arguments preferably.
iii. We cannot specify a value for an argument more than once.

There can be broadly two types of functions in Python:


1. Functions returning some value ( Non – void function)
2. Functions not returning any value (void function)

Scope of variable: Part(s) of program within which a name is legal and accessible, is
called scope of the variable (name).

There are two kinds of scopes in Python:


1. Global Scope: A name declared outside all the function body is called Global variable
and it has Global Scope.
2. Local Scope: A name declared within a function is called Local variable and it has
Local scope.

Lifetime: The time for which a variable or name remains in memory is called Lifetime of
variable.

28 | P a g
e
Built-in Functions

Function Description
eval() It is used to evaluate the value of a string and returns numeric value
min() and Both can take two or more arguments and returns the smallest and largest
max() value respectively.
abs() It returns the absolute value of a single number.
type() It is used to determine the type of variable.
round() It returns the result up to a specified number of digit .
len() Returns the length of an object.
range() It is used to define a series of numbers.
Functions form math module
ceil(x) It returns the smallest integer that is greater than or equal to x.
floor(x) It returns the largest integer that is less than or equal to x.
It returns the value of xy , where x and y are numeric expressions, and
pow(x,y)
returns the output in floating point number.
sqrt(x) Returns the square root of x.
Functions from random module
random() It generates a random number from 0 to 1.
It generates an integer between its lower and upper argument. By default
randrange()
the lower argument is 0 and upper argument is 1
It is used for making a random selection from a sequence like list, tuple or
choice()
string.
shuffle() It is used to shuffle or swap the contents of a list.

101 A function in python begins with which keyword?


i. void ii. return iii. int iv. Def

102 Name the statement that sends back a value from a function
i. print ii. input iii. return iv. None

103 What is the output of the program given below:


x=50
def func(x):
x=2
func(x)
print(‘x is now’,x)
29 | P a g
e
i. x is now 50 iii. x is now 2
ii. x is now 100 iv. Error

104 What is the output of the program given below:


import random
x = random.random()
y= random.randint(0,4)
print(int(x),”:”, y+int(x))
i. 0: 0 iii. 2 : 4
ii. 1: 6 iv. 0 : 5
105 def cal(a,b,c):
return a*3,b*3,c*3
val=cal(10,12,14)
print(type(val))
print(val)
i. [30, 24, 28] iii. [30,36,42]
ii. [10, 20, 30] iv. [10,12,14]
106 What is the output of the expression:round(4.576)
i. 4.5 ii. 5 iii. 4 iv. 4.6

107 What is the output of the function shown below?


import math
abs(math.sqrt(25))
i. Error ii. -5 iii. 5 iv. 5.0

108 What is the output of the functions shown below?>>>min(max(False,-3,-4), 2,7)


i. 2 i i . False iii. -3 iv. -4

109 What are the outcomes of the function shown below?

>>>x=3
>>>eval('x**2')
i. Error ii. 1 iii. 9 iv. 6
110 Which of the following functions does not throw an error?
i. ord() ii. ord(‘ ‘) iii. ord(”) iv. ord(“”)
111 What is the output of below program?
def say(message, times = 1):
print(message * times , end =’ ‘)
say(‘Hello and’)
say('World', 5)
i. Hello and WorldWorldWorldWorldWorld
ii. Hello and World 5
iii. Hello and World,World,World,World,World
iv. Hello and HelloHelloHelloHelloHello
112 What is a variable defined inside a function referred to as?
i. A global variable ii. A volatilevariable
iii. A local variable iv. An automatic variable
113 How many keyword arguments can be passed to a functionin a single function call?
i. zero ii. one i i i . zero or more i v . one or more

30 | P a g
e
114 How are required arguments specified in the functionheading?
i. identifier followed by an equal to sign and the default value
ii. identifier followed by the default value within backticks (“)
iii.identifier followed by the default value within squarebrackets ([ ])
iv. identifier
115 What is returned by
>>> math.ceil(3.4)?
i. 3 ii. 4 iii. 4.0 iv. 3.0

116 What is the value returned by


>>> math.floor(3.4)
i. 3 ii. 4 iii. 4.0 iv. 3.0
117 What is returned by
>>> math.ceil(-3.4)?
ii. 3 ii. 4 iii. 4.0 iv. -3
118 What is the value returned by
>>> math.floor(-3.4)
ii. 3 ii. -4 iii. 4.0 iv. 3.0
119 What is displayed on executing print(math.fabs(-3.4))?
i. -3.4 i i . 3.4 iii. 3 i v . -3
120 What is output of print(math.pow(3, 2))?
i. 9 ii. 9.0 iii. None iv. None of these
121 What is the value of x if x = math.sqrt(4)?
i. 2 ii. 2.0 iii. (2, -2) iv. (2.0, -2.0)
122 To include the use of functions which are present in the random library, we must use the option:
i. import random iii. random.h
ii. import.random iv. random.random
123 What is the output of the code shown below?
import random
random.choice(2,3,4)
i. An integer other than 2, 3 and 4 ii. Either 2, 3 or 4
iii. Error iv. 3 only
124 What is the output of the function shown below (random module has already been imported)?
>>>random.choice('sun')
i. sun ii. u iii. either s, u or n iv. Error
125 What is the output of the function shown below if the random module has already been imported?
>>>import random
>>>random.randint(3.5,7)
i. Error
ii. Any integer between 3.5 and 7, including 7
iii. Any integer between 3.5 and 7, excluding 7
iv. The integer closest to the mean of 3.5 and 7
126 Which type of elements are accepted by random.shuffle()?
i. strings ii. lists iii. tuples iv. integers
127 …………keyword is used to define a function.
i. Void ii. func iii. def iv. None

128 Which of the following statements are True out of the given below:
31 | P a g
e
1. More than one value(s) can be returned by a function
2. The variable declared inside a function is a Global variable.
3. Once the function is defined , it may be called only once
4. A function is used by invoking it
i. 1 & 2 ii. 1 & 4 iii. 2 & 3 iv. 2 & 4
129 Match the columns:
A B
1. max() a. will compute x**y
2. sqrt(x) b. will select a option randomly
3. choice() c. will return the largest value
4. pow(x,y) d. will compute (x)1/2
i. 1-a,2-b,3-c,4-d iii. 1-c,2-d,3-b,4-a
ii. 1-d,2-a,3-c,4-b iv. 1-b,2-c,3-d,4-a

130 What will be the output of the following code:


A=1
def f ():
A=10
print(A)
i. 1 ii. 10 iii. Error iv. None
131 >>>def Interest(p,c,t=2,r=0.09):
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)

i. 1 , 2 and 4 ii. 2 & 3 iii. 1 &4 iv. 3 & 4


133 Consider the program given in question no.132 and answer the question from 133 to 138 given
below:
What will come in place of statement 2:
i. upper() ii. isupper iii. isupper() iv is_upper()
134 What will come in place of statement 3:
i. [digits] ii. [“digits”] iii. d[“digits”] iv. d[“Digits”]
135 What will come in place of statement 4:
i. [“Special_chr”] iii. “Special_chr”
ii. D[“Special_chr”] iv. d(“Special_chr”)
136 What will come in place of statement 5:
i. s ii. S iii. d[“s”] iv. d[s]
137 What will come in place of statement 6:
i. d[“Upper_case”] iii. [“Upper_case”]
ii. d[“s”] iv. d[s]
138 What will come in place of statement 7:
i. d[“Digits”] iii. d[“digits”]
ii. d[“Digit”] iv. d[s]
139 The built-in function sin() belongs to which module:
i. random ii. pandas iii. math iv. numpy
140 …………..function returns the smallest integer greater than the given floating point number.
i. floor() ii. ceil() iii. sqrt() iv CEIL()
32 | P a g
e
141 …………function will return the largest integer less than the given floating point number.
i. floor() ii. ceil() iii. sqrt() iv CEIL()
142 ………..function returns the length of the object being passed.
i. Length() ii. Len() iii. len() iv. count()
143 ………..function returns the absolute value.
i. Abs( ) ii. abs( ) iii. absolute( ) iv. None of these
144 The range(x) function will generate the series of numbers from :
i. Min to max ii. o to x-1 iii. o to x iv. x
145 ……….. function can identify the whitespace in a given string.
i. Space( ) ii. isspace( ) iii. Isspace( ) iv. is_space( )
146 Consider the statement given below and answer the question:
>>>S=’My name is Ravindra’
Which statement will print “True” out of the given :
i. print(S.isspace( ))
ii. print (s.isspace( ))
iii. print(S[2].isspace)
iv. print(S[2].isspace( ))
147 A variable declared outside all the functions in a python program, then mention the statements
which are True in the context of the variable.
1. This variable will have global scope.
2. This variable will not be accessible from anywhere in the prog.
3. This variable will have a large lifetime than local variable.
4. This variable will be referred as Local variable.
i. Only 1&2 ii. Only 1 iii. Only 1&3 iv. Only 3

Answers:

1 ii 2 i 3 iii 4 iii 5 iv 6 ii 7 iii


8 i 9 i 10 i 11 ii 12 iii 13 ii 14 i
15 iii 16 i 17 i 18 iii 19 i 20 i 21 ii
22 iii 23 iii 24 iv 25 iv 26 i 27 iii 28 i
29 i 30 iv 31 iii 32 iv 33 iv 34 i 35 iii
36 i 37 ii 38 i 39 i 40 ii 41 i 42 iii
43 iv 44 iv 45 i 46 iv 47 iii 48 i 49 iii
50 i 51 iii 52 i 53 i 54 iii 55 iv 56 iv
57 iv 58 ii 59 ii 60 i 61 iii 62 i 63 iii
64 iii 65 iv 66 ii 67 iii 68 ii 69 iii 70 iii
71 iv 72 ii 73 ii 74 ii 75 i 76 ii 77 ii
78 iii 79 iii 80 i 81 i 82 iii 83 iii 84 iii
85 ii 86 iv 87 i 88 iii 89 ii 90 i 91 iii
92 i 93 iii 94 i 95 ii 96 i 97 ii 98 iii
99 ii 100 i 101 iv 102 iii 103 i 104 i 105 iii
106 ii 107 iv 108 ii 109 iii 110 ii 111 i 112 iii
113 iii 114 i 115 ii 116 i 117 iv 118 ii 119 ii

33 | P a g
e
120 ii 121 ii 122 i 123 ii 124 iii 125 ii 126 ii
127 iii 128 ii 129 iii 130 i 131 iii 132 iv 133 iii
134 iv 135 iii 136 i 137 i 138 i 139 iii 140 ii
141 i 142 iii 143 ii 144 ii 145 ii 146 iv 147 iii
Data File Handling

Key Points of Data File Handling

File:- A file is a collection of related data stored in computer storage for future data retrieval.
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line includes a sequence of characters.
2. Binary Files: A binary file is any type of file that is not a text file. WORKING WITH TEXT FILES:
Basic operations with files:
a. Read the data from a file
b. Write the data to a file
c. Append the data to a file
d. Delete a file a. Read the data from a file:
There are 3 types of functions to read data from a file. –read( ), readline( ), readlines( )

Binary files are used to store binary data such as images, video files, audio files etc. They store data in the binary
format (0‘s and 1‘s).
In Binary files there is no delimiter for a line. To open files in binary mode, when specifying a mode, add 'b' to it.
Pickle module can be imported to write or read data in a binary file.

CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The information is
organized with one record on each line and each field is separated by comma.
CSV File Characteristics
• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored
• Fields with in-built commas are separated by double quote characters.
Compare text files, binary files and csv files and write pros and cons of each of them .
Text Files Binary Files CSV Files

It is very common
It is capable to handle format and platform
1 textual data. It is capable to handle large file. independent.

It consists of series of lines It consists of plain text


of a set of letters, numbers It consists of data with a specific pattern with a list of data with a
2 or symbols (String) without any delimiter. delimiter.

Any text editors like No specific programs can be used to It can be read using text
notepad can be used to read read them, python provides functions to editors like notepads and
3 them. read data. spreadsheet software.

It terminates a line
automatically when the
delimiter is not used
4 Every line ends with EOL. There is no specific EOL character. after data.

34 | P a g
e
MCQs on Data File Handling
1 Every file has its own identity associated with it. Which is known as –
a. icon
b. extension
c. format
d. file type
2 Which of the following is not a known file type?
a. .pdf
b. jpg
c. mp3
d. txp
3. In f=open(“data.txt”, “r”), r refers to .
a. File handle
b. File object
c. File Mode
d Buffer
4. EOL stands for
a. End Of Line
b. End Of List
c. End of Lines
d. End Of Location
5. Which of the following file types allows to store large data files in the computer memory?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these
6. Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these
7. Which of the following is nor a proper file access mode?
a. close
b. read
c. write
d. append
35 | P a g e
8. To read 4th line from text file, which of the following statement is true?
a. dt = f.readlines();print(dt[3])
b. dt=f.read(4) ;print(dt[3])
c. dt=f.readline(4);print(dt[3])
d. All of these
9 Which of the following function flushes the files implicitly?
a. flush()
b. close()
c. open()
d. fflush()
10. Which of the following functions flushes the data before closing the file?
a. flush()
b. close()

11. In F=open("MyFile.txt") , name of file object is


a.open
b.MyFile.txt
c.F
d.F=open()

12. Default EOL character in Python.


a. ‘\n’
b. ‘\r’
c. ‘’
d. ‘\t’

13. Which of the following is not a file extension for text files?
a. .txt
b. .ini
c. .rtf
d. .DAT

14. What is the first thing to do before performing any functions on a text file?

a. Import modules
b. Open file
c. Read file
d. Print the name of the file
36 | P a g
e
15. What is a file object?
a. It serves as a link to the file.
b. It is a file present in a computer.
c. A keyword
d. A module in python

16. Which is not a correct file mode for text files?


a. a
b. ar
c. a+
d. r+

17. What does the prefix r in front of a string do?


a. It makes the string a raw string
b. It opens the file in read mode
c. It converts the file into text file
d. It creates the file if it doesn’t exist

18. A file object is also known as


a. File handle
b. File copy
c. File directory
d. File link

19. How to open a text file in read mode only?


a. r
b. r+
c. rb+
d. rw+

20. How to open a text file in write and read mode?


a. r+
b. a+
c. wr
d. wb

21. Syntax for closing a file:


a. closefile(<file object>)
b. <fileobject>.close()
c. <filename>.closer()
d. closefile.<fileobject>

22. Which method can not be used to read from files?


a. read()
b. readlines()
c. readlines(<filename>)
d. readline()

23. What does strip() function do?


a. Removes the trailing or leading spaces, if any.
b. Deletes the file
c. Remove the file object
d. Removes all the spaces between words
37 | P a g
e
24. readlines() gives the output as
a. List
b. Tuple
c. String
d. Sets

25. When reading a file using the file object, what method is best for reading the entire file into a single
string?
a. readline()
b. read_file_to_str()
c. read()
d. readlines()

26. Which file can open in any text editor and is in human readable form?

a. Binary files
b. Text files
c. Data files
d. Video files

27. Which function breaks the link of file-object and the file on the disk?

a. close( )
b. open( )
c. tell( )
d. readline( )

28. Which function reads the leading and trailing spaces along with trailing newline character ('\n')
also while reading the line?
a. readlines( )
b. readline( )
c. read( )
d. flush( )

29. Which mode is used to retain its previous data and allowing to add new data?
a. write mode
b. read mode
c. open mode
d. append mode

30. Which function forces the writing of data on disc still pending in output buffer?

a. seek( )
b. tell( )
c. flush( )
d. write( )

31. Syntax for flush( ) function is:


a. <fileOobject>(flush( ))
b. flush( ).<fileobject>
c. <fileObject>.flush( )
d. flush( ).<file-object>

32. Which function returns the entire file content in a list where each line is one item of the list?
a. readlines( )
38 | P a g
e
b. readline( )
c. output( )
d. Input( )

33. Which function is used to remove the given character from trailing end i.e. right end?

a. strip( )
b. remove( )
c. Istrip( )
d. rstrip( )

34. Sometimes the last lap of data remains in buffer and is not pushed onto disk until a
operation is performed.
a. dump( )
b. close( )
c. load( )
d. open( )

35. The position of a file-pointer is governed by the .


a. File mode b. append mode
c. write mode d. open mode

36. In which mode the file must exist already, otherwise python raises an error? a. read mode
b. write mode
c. binary mode
d. None of these

37. What is the prefix r stands for in file path?


a. raw string
b. read
c. write
d. append

38. In which mode if the file does not exist, then the file is created?
a. read write mode
b. read mode
c. write mode
d. All of these

39. Which option is correct about this program?


f=open(“ss.txt”,”wb”)
print(“Name of the file:”,f.name)
f.flush()
f.close()
a. Compilation error
b. Runtime error
c. No output
d. Flushes the file when closing them

40. What is the output of the following?


import sys
sys.stdout.write(‘Hello\n’)

39 | P a g
e
sys.stdout.write(‘Python\n’)
a. error
b. Runtime error
c. Hello Python
d. Hello
Python

41. Which function is used to read all the characters in text files?

a. read( )
b. readcharacters( )
c. readall( )
d. readchar( )

42. Which function is used to read all the lines?


a. read( )
b. readall( )
c. readlines( )
d. readline( )

43. In which format does the readlines( ) function give the output?

a. Integer type
b. list type
c. string type
d. tuple type

44. In which format does the read( ) function give the output?

a. Integer type
b. string type
c. list type
d. tuple type
4
45. Which function is used to write a list of strings in a file?
a. writestatement()
b. writelines()
c. writefulline()
d. writeline()

46. Which function is used to write all the characters?


a. writechar()
b. writecharacters()
c. write()
d. writeall()

47. What is the correct syntax of open() function?


a. file=open(file_name[,access_mode][,buffering])
b. fileobject=open(file_name[,access_model][,buffering])
c. fileobject=filename.open()
d. none of the mentioned

48. In file handling, what does means “r”, “a”?


a. append, read
40 | P a g
e
b. read, append
c. read, add
d. None of the mentioned

49. The default file open mode is….


a. w
b. r+
c. w+
d. r

50. What is the difference between r+ and w+ modes?


a. In r+ mode, file length truncates to zero.
b. In w+ mode, file length truncates to zero either file exists or not.
c. No difference
d. Depends on the operating system

51. 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

52. Which of the following statements is true regarding the opening modes of a file? a. While opening a file
for reading, if the file does not exist, an error occurs. b. While opening a file for writing ,if the file does not
exist, an error occurs. c. While opening a file for reading, if the file does not exist, a new file is created. d.
None of the above.

53. To force python to write the contents of file buffer on to storage file,........method may be used.
a. buffer()
b. flush()
c. close()
d. write()

54. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs.
b) When you open a file for writing, if the file does not exist, a new file is created.
c) When you open a file for writing, if the file exists, the existing file content is overwritten with the new
content.
d) All of the these
55. To read the next line of the file from a file object f1, we use:
a) f1.read(2)
b) f1.read()
c) f1.readline()
d) f1.readlines()

41 | P a g
e
ANSWER KEY

1.B 2.D 3.C 4.A 5.B 6.C 7.A 8.A 9B 10.A

11.C 12.A 13.D 14.B 15.A 16.B 17.A 18.A 19.A 20.A

21.B 22.C 23.A 24.A 25.C 26.B 27.A 28.B 29.D 30.C

31.C 32.A 33.D 34.B 35.A 36.A 37.A 38.C 39.D 40.D

41.A 42.C 43B 44.B 45.B 46.C 47.B 48.B 49.D 50.B

51.B 52.A 53.B 54.D 55.C

42 | P a g
e
BINARY FILES MCQs

Q1. 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+”)

Q2 What are the binary files used for?

a. It is used to store data in the form of bytes.


b. To store data
c. To look folder good
d. None of these

Q3. What is the function of `rb` mode in binary?

a. Both reading and writing operations can take place.


b. File is in only write mode.
c. File is created if it does not exist.
d. File must exist otherwise error will be shown.
Q4. 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

5. What is binary file mode for append?

a. `rb`
b. `wb`
c. `ab`
d. None of these

Q6. What is the binary file mode associated with “ file must exist, otherwise error will be raised
and reading and writing can take place”.

a. read and write


b. write and read
c. read only
d. append

43 | P a g
e
Q7. What is the process of converting a byte stream back to the original structure called?

a. append
b. txt.file
c. Unpickling
d. None of these.

Q8. Which module is used to store data into python objects with their structure?
a. pickle
b. binary files
c. unpickle
d. None of these

Q9. What is pickle.dump()?


a. dump() function is used to store the object data to the file.
b. It is used to read
c. append
d. None of these

Q10. Which one of the following is the correct statement?

a. pickle import
b. import - pickle
c. import pickle
d. None of the above
Q11. Which is the valid syntax to write an object onto a binary file opened in the write mode?

a. pickle.dump(<object to be written>, <file handle of open file>)


b. pickle.dump(<file handle of open file>, <object to be written>)
c. dump.pickle(<object>, <file handle>)
d. None of the above

Q12. Which method is used for object serialization?

a. Pickling
b. Unpickling
c. None of the above
d. All of the above

Q13. Which method of pickle module is used to read from a binary file?

a. dump()
b. load()
c. All of the above
d. None of the above

44 | P a g
e
Q14.Which method is used for object deserialization?

a. Pickling
b. Unpickling
c. All of the above
d. None of the above
Q15.Which of the following is the correct syntax to read from a file using load function?

a. pickle.load(<filehandle>)
b. <object> - load.pickle(<filehandle>)
c. <object> - pickle.load(<filehandle>)
d. All of the above

Q16. Which method of pickle module is used to write onto a binary file?
a. dump()
b. load()
c. All of the above
d. None of the above

Q17. Which of the following file modes open a file for reading and writing both in the binary
file?
a. r
b. rb
c. rwb
d. rb+

Q18.Which of the following file modes that opens a file for reading and writing both and
overwrites the existing file if the file exists otherwise creates a new file ?

a. w
b. wb+
c. rwb
d. rb

Q19. 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

Q20.Which of the following file modes will not delete the existing data in binary file?

a. .wb
b. .w
c. .a
d. .ab

45 | P a g
e
ANSWER KEY

1-A 6-A 11-A 16-A

2-A 7-C 12-A 17-D

3-D 8-A 13-B 18-B

4-A 9-A 14-B 19-C

5-C 10-C 15-C 20-D

CSV FILES

Q1 is a file format which stores records separated by comma.


a. .tsv
b. .csv
c. .py
d. .bin

Q2.The CSV files can be operated by software.


a. Spreadsheet
b. Notepad
c. MS Excel
d. All of the above

Q3.When you read csv file using csv.reader() function it returns the values in object.

a. dictionary
b. tuple
c. nested list
d. sets

Q4.CSV module allows to write multiple rows using function.

a. writerows( )
b. writerow( )
c. writer( )
d. None of the above

Q5.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
46 | P a g
e
Q6.which is the correct way to import a csv module?

a. import csv
b. from csv import *
c. None of the above
d. Both A & B

Q7.Observe the following code and fill the blank in statement1


import csv
with as f: #statement1
r = csv. (f) #statement2
for row in : #statement3
print( ) #statement4

a. open("data.csv")
b. f=open("data.csv")
c. Both A & B are Correct
d. Both A & B are incorrect

Q8.Observe the following code and fill the blank in statement2

import csv

with as f: #statement1

r = csv. (f) #statement2

for row in : #statement3

print( ) #statement4

a. load
b. read()
c. reader()
d. readlines()

Q9.Observe the following code and fill the blank in statement3

import csv

with as f: #statement1

r = csv. (f) #statement2

for row in : #statement3

print( ) #statement4

a. f
b. r
c. r,f
d. None of the above

47 | P a g
e
Q10.Observe the following code and fill the blank in statement4

import csv

with as f: #statement1

r = csv. (f) #statement2

for row in : #statement3

print( ) #statement4

a. r
b. row
c. f
d. csv

ANSWER KEY

1.B 2.D 3.C 4.A 5.B


6.D 7.A 8.C 9.B 10.B

Accession and Reasoning


1. Amit, 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 'School.csv' (content shown below).
Help him in completing the code which creates the desired CSV File.
CSV File

1, AKASH, XII, A

2, AKRITI, XII, A

3, ISHA, XII, A

4, RASHI, XII, A

5, SEJAL, XII, A

Incomplete Code

import #Statement-1

fh = open( , , newline='') #Statement-2

stuwriter = csv. #Statement-3

data = [ ]

48 | P a g
e
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

49 | P a g
e
fh.close()

i. Identify the suitable code for blank space in line marked as Statement-1.
a) csv file

b) CSV

c) csv

d) Csv

Correct Answer: c) csv


ii. 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"

Correct Answer: a) "School.csv","w"


iii. Choose the function name (with argument) that should be used in the blank pace of line marked as
Statement-3
a) reader (fh)

b) reader (MyFile)

c) writer (fh)

d) writer (MyFile)

Correct Answer: 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'
d) roll_no,name,Class,sectionc) co.connect()
Correct Answer: d) roll_no,name,Class,section

50 | P a g
e
v. 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( )

Correct Answer: c) writerows( )

2: Amritya Seth is a programmer, who has recently been given a task to write a python code to perform the
following binary file operations with the help of two user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing student information – roll number,
name and marks (out of 100) of each student.

b. GetStudents() to display the name and percentage of those students who have a percentage greater than 75.
In case there is no student having percentage > 75 the function displays an appropriate message. The function
should also display the average percent.

He has succeeded in writing partial code and has missed out certain statements, so he has left certain queries
in comment lines. You as an expert of Python have to provide the missing statements and other related
queries based on the following code of Amritya.

Answer any four questions (out of five) from the below mentioned questions.
import pickle

def AddStudents():

#1 statement to open the binary file to

write data

while True:

Rno = int(input("Rno :"))

Name = input("Name : ")

Percent = float(input("Percent :"))

L = [Rno, Name, Percent]

#2 statement to write the list L

51 | P a g
e
into the file

Choice = input("enter more (y/n): ")

if Choice in "nN":

break

F.close()

def GetStudents():

Total=0

Countrec=0

Countabove75=0

with open("STUDENT.DAT","rb") as F:

while True:

try:

#3 statement to read

from the file

Countrec+=1

Total+=R[2]

if R[2] > 75:

print(R[1], " has percent =

",R[2])

Countabove75+=1
except:

break

if Countabove75==0:

52 | P a g
e
print("There is no student who has

percentage more than 75")

average=Total/Countrec

print("average percent of class = ",average)

AddStudents( )

GetStudents( )

i. Which of the following commands is used to open the file “STUDENT.DAT” for writing only in binary
format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')

b. F= open("STUDENT.DAT",'w')

c. F= open("STUDENT.DAT",'wb+')

d. F= open("STUDENT.DAT",'w+')

Correct Answer: a. F= open("STUDENT.DAT",'wb')


ii. Which of the following commands is used to write the list L into the binary file, STUDENT.DAT?
(marked as #2 in the Python code)
a. pickle.write(L,f)

b. pickle.write(f, L)

c. pickle.dump(L,F)

d. f=pickle.dump(L)

Correct Answer: c. pickle.dump(L,F)


iii. Which of the following commands is used to read each record from the binary file STUDENT.DAT?
(marked as #3 in the Python code)
a. R = pickle.load(F)

b. pickle.read(r,f)

c. r= pickle.read(f)

d. pickle.load(r,f)

Correct Answer: a. R = pickle.load(F)

53 | P a g
e
iv. Which of the following statement(s) are correct regarding the file access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.

b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and creates a
new one if it does not exist.

c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a new
one if it does not exist.

d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists.

Correct Answer: a

v. Which of the following statements correctly explain the function of seek() method?
a. tells the current position within the file.

b. determines if you can move the file position or not.

c. indicates that the next read or write occurs from that position in a file.

d. moves the current file position to a given specified position

Correct Answer: d

*************************

54 | P a g
e
SAMPLE PAPER -1
Class –XII SUB-Computer Sc.
Max. Marks: 35 Duration: 1:30 Hrs
General Instructions:
1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Section A and Section B have choices.
3. Section - A has 35 MCQ/True or False questions of 1 marks each. Any 27 questions to be
answered.
4. Section – B has 2 questions, each question includes 5 MCQ questions, Attempt any 4
questions.

Ques Section-I Mark


No. s
Allott
ed
Select the most appropriate option out of the options given for each question.
1 Consider a list L = [5, 10, 15, 20], which of the following will result in an error:- 1
a) L[0] += 3 b) L += 3 c) L *= 3 d) L[1] = 45
2 Find the operator which cannot be used with a string in Python from the following:- 1
a) // b) * c) + d) in
3 Consider a tuple in python named Months = (‘Jul’, ‘Aug’, ‘Sep’). Identify the invalid statement(s) from the 1
given below statements:-
a)S = Months[0] b)print(Months[2])
c)Months[1] = ‘Oct’ d)LIST1 =list(Months)
4 Functions that do not return any value are known as:- 1
a)Fruitful functions b)Void functions
c)Standard python functions d)User-defined functions
5 Which is the correct dictionary declaration? 1
a)d1={1:'January',2='February',3:'March'} b)d2=(1:'January',2:'February',3:'March'}
c)d3={1:'January',2:'February',3:'March'} d)d4={1:January,2:February,3:March}
6 Which of the following is a wrong way of defining a function:- 1
a)def f(x=10, y=20, z=30) b)def f(x, y, z)
c)def f(x=10, y, z) d)def f(x, y=20, z=30)
7 A void function also returns a _ value to its caller. 1
8 What is the area of memory called, which stores the parameters and local variables of a function call? 1
a)Heap b)Queue c)Stack d)Array
9 Rohan wants to drive a car but He is unable to drive because his age is below 18. A python code is written 1
to check his age .identify it is correct or incorrect.
Age=input(“enter age:”)
if age<=18:
print(“you are not eligible””)
a)Correct b)Incorrect
10 CSV stands for 1
a)Column Separated Values b)Comma Separated Values
c)Comma Started Values d)Column Separated Values
11 What is the output of the function shown below (random module has already been imported)? 1
print(random.choice(‘sun’))
a)sun b)u c)Either s, u or n d)Error
12 What is the default mode of opening a file in python? 1
a)read b)write c)append d)read and write
13 Which of the following expressions is an example of type casting? 1
a)4.0+float(6) b)5.3+6.3 c)5.0+3 d)None of these
14 To read twelve characters from a file object f1, we use 1
a)f1.read(12) b)f1.read() c)f1.readline() d)read(f1,12)
15 In which of the following flie modes, the existing data of file will not be lost? 1
a)wb+ b)wb c)rb d)w+
55 | P a g
e
16 What is the output of the following Python Code; Select any one of the following options? 1
import random
print(int(random.random()*5)
a)Always generate 0

56 | P a g
e
b) Generate any number between 0 to 4(including both)
c) Generate any number between 0 to 5(including both)
17 Which of the following is valid variable name:- 1
a)Student name b)3Number c)%name% d)Block_number
18 What will be the output after the following 1

statements? a = [0, 1, 2, 3]
del
a[:]
print(
a)
a)None b)[] c)[0, 1, 2, 3] d)NameError
19 What will be the output after the following 1

statements? x = 27
y=9
while x < 30 and
y < 15: x = x +
1
y=y
+1
print(x,y
)
a) 26 11 b) 25 11 c) 30 12 d) 26 10
20 What will the following code produce? 1
T=[‘kvs’,’rpr’]
T1=range(len(T))
for i in T1:
T[i]=T[i].upper()
print(T)
a)[‘KVS’,’RPR’] b)[‘kvs’,’rpr’] c)[‘Kvs’,’Rpr’] d)Error
21 Find out the type of error if any- 1
if v <5:
print(“KVS”)
else:
print(“CBSE”)
a)No Error b)Declaration of v c): with else not required d)Indentation Error
22 Consider square numbers defined as follows: 1
compute(1) = 1
compute(N) = compute(N-1) + 2N-1
According to this definition, what is compute (3)?
a)compute(3) = compute(2) +compute(1) b)compute(3) = compute(2) -2*3+1
b)compute(3) = compute(2) + 2*3-1 d)compute(3) = compute(3) +2*3-1
23 When you open a file for writing, if the file does not exist, an error occurs.(True/False) 1

24 The relative path for a file always remains same even after changing the directory.(True/False) 1

25 The value of the expressions 4/(3*(4-2)) and 4/3*(4-2) is the same.(True/False) 1

26 The command to merge the dictionary Book with Library the command would be: 1
a) d=Book+Library b) print(Book+Library)
c)Book.update(Library) d)Library.update(Book)

57 | P a g
e
27 Identify the correct option to add new value 50 to 1

existing tuple T T = (11,22,33,44,55)

a)T = T + 66 b)T = T + 66 c)T = T + (66,) d)T = T + (66)


28 Find and write the output of the following python code: 1
a=10
def call():
global a
a=15
b=20
print(a)
call()
a)25 b)35 c)15 d)10
29 Which of the following Python codes will result in an error? 1
object = ‘a’

58 | P a g
e
a)pickle.dumps(object) b)pickle.dumps(object,3)
c)pickle.dumps(object,3,True) d)pickle.dumps(‘a’,2)
30 if is a and roll_no is a/an . 1
31 if a = [5,4,3,2,2,2,1], evaluation of the expression a [ a [ a [ a [ 2 ] + 1 ] ] ]: 1
a)3 b)4 c)5 d)2
32 What is the output of the following program : 1
print( 0.1 + 0.2 == 0.3)
a)True b)False c)Machine Dependent d)Error
33 What will be the output after the following statements? 1
x=0
y=4
while x + y < 10:
print(x, end=' ')
x += 2
a)0 2 4 6 b)0 2 4 c)0 2 d)0 2 4 8
34 apple =’red’ 1
def fruit():
pineapple=’green’
In above code apple is a variable while pineapple is a variable.
35 Which of the following is the use of id() function in Python? 1
a) Id returns the identity of the object b) Every object doesn’t have a unique ID
c) All of the mentioned d) None of the mentioned
Section-II (Case Study Based Question)
36 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.
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(hea
der) for i in
range(5):
roll_no = int(input("Enter Roll
Number : ")) name = input("Enter
Name : ")
Class = input("Enter
59 | P a g
e
Class : ") section =
input("Enter Section : ")
rec = [ ] #Statement-4
data.append(rec)
stuwriter. (data)
#Statement-5 fh.close()

Answer any four of the following questions.

i) Identify the suitable code for blank space in line marked as Statement-1 1
a) csv file b) CSV c) csv d) Csv
ii) Identify the missing code for blank space in line marked as Statement-2? 1
a) "School.csv","w" b) "Student.csv","w" c) "Student.csv","r"
d) "School.csv","r"
iii) Choose the function name (with argument) that should be 1

used in the blank space of line marked as Statement-3


a) reader(fh) b) reader(MyFile) c) writer(fh) d)
writer(MyFile)

60 | P a g
e
iv) Identify the suitable code for blank space in line marked as Statement-4. 1
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()
v) Choose the function name that should be used in the blank 1

space of line marked as Statement-5 to create the desired CSV


File?
a) dump() b) load() c) writerows() d) writerow()
37 Your teacher has given you a method/function FilterWords() in python
which read lines from a text file NewsLetter.TXT, and display those words,
which are lesser than 4 characters. Your teachers intentionally kept few
blanks in between the code and asked you to fill the blanks so that the
code will run to find desired result. Do the needful with the following
python code. def FilterWords():
c=0
file=open('NewsLetter.TXT', ' ')
#Statement-1 line = file.
#Statement-2
word =
#Stateme
nt-3 for c in word:
if :
#Statement-4
print(c)

#Stateme
nt-5 FilterWords()

Answer any 4 of the following questions.


i) Write mode of opening the file in statement-1? 1
a. a b. ab c. w d. r
ii) Fill in the blank in statement-2 to read the data from the file. 1
a. File.Read() b. file.read() c. read.lines( ) d.
readlines( )
iii) Fill in the blank in statement-3 to read data word by word. 1
a. Line.Split() b. Line.split() c. line.split() d.
split.word()
iv) Fill in the blank in statement-4, which display the word 1

having lesser than 4 characters.


a. len(c) ==4 b. len(c)<4 c. len ( )= =3 d. len ( )==3
v) Fill in the blank in Statement-5 to close the file. 1
a. file.close() b. File.Close() c. Close() d. end()
61 | P a g
e
SOLUTION
Class –XII SUB-Computer Sc.

Ques No Section-I Marks


Allotted
Select the most appropriate option out of the options given for each question.
1 b 1
2 a 1
3 c 1
4 b 1
5 c 1
6 c 1
7 None 1
8 c 1
9 b 1
10 b 1
11 c 1
12 a 1
13 a 1
14 a 1
15 c 1
16 b 1
17 d 1
18 b 1
19 c 1
20 a 1
21 b 1
22 b 1
23 False 1
24 False 1
25 False 1
26 c 1
27 c 1
28 c 1
29 d 1
30 keyword, identifier 1
31 d 1
32 b 1
33 b 1
34 global, local 1
35 a 1
Section-II (Case Study Based Question)
36 Any Four
i) c 1
ii) b 1
iii) c 1
iv) d 1
v) c 1
37 Any Four
i) d 1
ii) b 1
iii) c 1
iv) b 1
v) a 1

62 | P a g
e
63 | P a g
e
SAMPLE PAPER-2
Term-I Examination – 2021-22
Model Question Paper-Set-2
Class- XII, Subject – Computer Science (083)
Duration: 90 mins. MM: 35
General Instructions to the Examinee:
1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Part A and Part B have choices.
3. Part-A is having MCQs (Attempt 27 out of 35 questions).
4. Part- B has two Case based questions.
a. Each case study has 4 case-based subparts.
b. An examinee is to attempt any 4 out of the 5 subparts.
5. All programming questions are to be answered using Python Language only.
Part-A
(Attempt any 27 questions from question no 1 to 35.)
1. What possible output(s) are expected to be displayed on screen at the time of 1
execution of the program from the following code?
from random import randint
LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = randint(3,8) – 1
second = randint(4,9) – 2
third = randint(6,11) – 3
print(LST[first],"#", LST[second],"#", LST[third],"#")
a) 20#25#25#
b) 30#40#70#
c) 15#60#70#
d) 35#40#60#
2. Specify the maximum values that can be assigned to each of the variables first, 1
second and third in the code given in Question no. 1 -
a) First: 6, Second: 6, Third: 7
b) First: 7, Second: 7, Third: 8
c) First: 3, Second: 4, Third: 6
d) First: 8, Second: 8, Third: 9
3. Which of the following is not a valid identifier name in Python? 1
(a) First_Name (b) _Area
(c)2nd_num (d)While
4. Which statement is correct for dictionary? 1
(a) A dictionary is an ordered set of key:value pair
(b) each of the keys within a dictionary must be unique
(c) each of the values in the dictionary must be unique
(d) values in the dictionary are immutable
5. Identify the valid declaration of Record: 1
Record=(1342, “Pooja” , 45000, “Sales”)
(a) List
(b) Tuple
(c) String
(d) Dictionary
6. Which of the following functions do we use to write data in a binary file? 1
(a) writer( )
(b) output( )
(c) dump( )
(d) send( )
64 | P a g
e
7. Which operator is used for replication? 1
(a) +
(b) %
(c) *
(d) //
8. Which of the following functions generates an integer? 1
(a) uniform( )
(b) randint( )
(c) random( )
(d) None of the above
9. Consider the tuple in python named DAYS=( “SUN”, “MON”, “TUES”). 1
Identify the invalid statement(s) from the given below statements:
(a) S=DAYS[1]
(b) print(DAYS[2])
(c) DAYS[0]= “WED”
(d) LIST=list(DAYS)

10. t1=(2,3,4,5,6) 1
print(t1.index(4))
Output will be –
(a) 4
(b) 5
(c) 6
(d) 2

11. Which of the following statements correctly explain the function of tell() 1
method?
(a) tells the current position within the file.
(b) tell the name of file.
(c) move the current file position to a different location.
(d) it changes the file position only if allowed to do so else returns an error.

12. Which of the following statements correctly explain the function of seek() 1
method?
(a) tell the current position within the file.
(b) indicate that the next read or write occurs from that position in a file.
(c) determine if you can move the file position or not.
(d) move the current file position to a different location at a defined offset.

13. Which of the following command is used to open a file “c:\temp.txt” in read- 1
mode only?
(a) infile = open(“c:\temp.txt”, “r”)
(b) infile = open(“c:\\temp.txt”, “r”)
(c) infile = open(file = “c:\temp.txt”, “r+”)
(d) infile = open(file = “c:\\temp.txt”, “r+”)

14. Which of the following command is used to open a file “c:\temp.txt” in write- 1
mode only?
(a) outfile = open(“c:\temp.txt”, “w”)
(b) outfile = open(“c:\\temp.txt”, “w”)
(c) outfile = open(file = “c:\temp.txt”, “w+”)
(d) outfile = open(file = “c:\\temp.txt”, “w+”)

65 | P a g
e
15. Which of the following command is used to open a file “c:\temp.txt” in 1
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+”)

16. Which of the following commands can be used to read “n” number of 1
characters from a file using the file object <file>?
(a) file.read(n)
(b) n = file.read()
(c) file.readline(n)
(d) file.readlines()

17. Which of the following commands can be used to read the entire contents of a 1
file as a string using the file object <tmpfile>?
(a) tmpfile.read(n)
(b) tmpfile.read()
(c) tmpfile.readline()
(d) tmpfile.readlines()

18. Which of the following commands can be used to read the remaining lines in a 1
file using the file object <tmpfile>?
(a) tmpfile.read(n)
(b) tmpfile.read()
(c) tmpfile.readline()
(d) tmpfile.readlines()

19. Which of the following statement is False regarding the opening modes of a 1
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) When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.

20. Which module is required to use built in function dump() 1


(a) Math (b)flush (c)pickle (d)csv

21. Which of the following function is used to write data in binary mode? 1
(a)write (b)output (c)dump (d)send

22. To read 2 characters from file object f1 command should be 1


(a)f1.read(2) (b)f1.read() (c)f1.readline() (d) f1.readlines()

23. To get byte position from the beginning of file, function used is - 1
(a)seek (b)tell (c)read (d)write

24. The file pointer, used to go to particular position 1


(a)seek (b)tell (c)read (d)write

66 | P a g
e
25. In regards to separated value files such as .csv and .tsv, what is the delimiter? 1
(a) Any character such as the comma (,) or tab (\t) that is used to separate
the column data.
(b) Delimiters are not used in separated value files
(c) Anywhere the comma (,) character is used in the file
(d) Any character such as the comma (,) or tab (\t) that is used to separate
the row data

26. In separated value files such as .csv and .tsv, what does the first row in the file 1
typically contain?
(a) The author of the table data
(b) The source of the data
(c) Notes about the table data
(d) The column names of the data

27. Assume you have a file object my_data which has properly opened a separated 1
value file that uses the tab character (\t) as the delimiter. What is the proper
way to open the file using the Python csv module and assign it to the variable
csv_reader? Assume that csv has already been imported.

(a) csv.tab_reader(my_data)
(b) csv.reader(my_data)
(c) csv.reader(my_data, delimiter='\t')
(d) csv.reader(my_data, tab_delimited=True)
28. When iterating over an object returned from csv.reader(), what is returned with 1
each iteration? For example, given the following code block that assumes
csv_reader is an object returned from csv.reader(), what would be printed to
the console with each iteration?

for item in csv_reader:


print(item)

(a) The full line of the file as a string


(b) The row data as a list
(c) The individual value data that is separated by the delimiter
(d) The column data as a list
29. Find the output of the following: 1
>>>Line = “Fun with Python”
>>> print (Name [ : 5 : -1])
(a) ith Python
(b) th Python
(c) nohtyP ht
(d) nohty
30. What will be the Output for the following code – 1
Language=["C", "C++", "JAVA", "Python", "VB", "BASIC", "FORTRAN"]
del Language[4]
Language.remove("JAVA")
Language.pop(3)
print(Language)
(a) ['C', 'C++', 'VB', 'FORTRAN']
(b) ['C', 'C++', 'Python', 'FORTRAN']
(c) ['C', 'C++', 'BASIC', 'FORTRAN']
(d) ['C', 'C++', 'Python', 'BASIC']

67 | P a g
e
31. An absolute path name begins at the 1
(a) Leaf
(b) Stem
(c) current directory
(d) root
32. What happens if a local variable exists with the same name as the global 1
variable you want to access?
(a) Error
(b) The local variable is shadowed
(c) Undefined behavior
(d) The global variable is shadowed
33. Choose the correct option with reference to below Python code? 1

def fn(a):
print(a)
x=90
fn(x)
(a) x is the formal argument.
(b) a is the actual argument.
(c) fn(x) is the function signature.
(d) x is the actual argument.
34. What is the output of the following – 1
print(21//9%3, 2**2**3)
(a) 7 64
(b) 2 256
(c) 7 256
(d) 2 64
35. Assertion (A) : Keys in a Python dictionary should be unique. 1
Reason (R) : Only immutable data types can be used as keys.

(a) A is true but R is false.


(b) A is false but R is true.
(c) Both A and R are false.
(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.
Part-B
(Attempt any 4 out of the 5 subparts in each question)
36. In an online lottery system, names having exactly 5 characters are to be
displayed. Piyush has been asked to complete this task. He has created a functi on
FindNames() in python which read contents from a text file LOTTERY.TX T,
which contains names of participants, and displays those names, which are
having exactly 5 characters. He got confused with few statements and left it
blank. Help him complete the code.
def FindNames():
c=0
file=open('LOTTERY.TXT', ' ') #Statement-1
line = file. #Statement-2
word = #Statement-3
for c in word:
if : #Statement-4
print(c)
#Statement-5
FindNames()
68 | P a g
e
(i) Write mode of opening the file in statement-1? 1
(a) A
(b) Ab
(c) W
(d) r

(ii) Fill in the blank in statement-2 to read the data from the file. 1
(a) File.Read()
(b) file.read()
(c) read.lines( )
(d) readlines( )

(iii) Fill in the blank in statement-3 to read data word by word. 1


(a) Line.Split()
(b) Line.split()
(c) line.split()
(d) split.word()

(iv) Fill in the blank in statement-4, which display the word having exactly 5 1
characters.
(a) len(c) ==5
(b) len(c)<5
(c) len ( )= =5
(d) len ( )==6

(v) Fill in the blank in Statement-5 to close the file. 1


(a) file.close()
(b) File.Close()
(c) Close()
(d) end()
37. Snigdha is making a software on “Countries & their Capitals” in which variou s
records are to be stored/retrieved in CAPITAL.CSV data file. It consists some
records (Country & Capital). She has written the following code in python. Asa
programmer, you have to help her to successfully execute the program.

import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in CSV file
f=open(“CAPITAL.CSV”, ) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
# Statement-3
def ShowRec(): # Fn. to display all records from CSV file
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv. (NF) # Statement-4
for rec in NewReader:
print(rec[0], “#”, rec[1])

AddNewRec(“INDIA”, “NEW DELHI”)


AddNewRec(“CHINA”, “BEIJING”)
ShowRec() # Statement-5

69 | P a g
e
(i) Which module should be imported in Statement-1. 1
(a) pickle
(b) csv
(c) file
(d) text

(ii) Which file mode to be passed to add new record in Statement-2. 1


(a) w+
(b) w
(c) wb
(d) a

(iii) What should be written in Statement-3 to close the file? 1


(a) close()
(b) fwriter.close()
(c) f.close()
(d) csv.close()

(iv) Which function to be used in Statement-4 to read the data from a csv file. 1
(a) read()
(b) readline()
(c) readlines()
(d) reader()

(v) The output after executing Statement-5 will be – 1


(a) (“INDIA”, “NEW DELHI”)
(“CHINA”, “BEIJING”)
(b) INDIA NEW DELHI
CHINA BEIJING
(c) INDIA, NEW DELHI
CHINA, BEIJING
(d) INDIA # NEW DELHI
CHINA # BEIJING

All the Best

70 | P a g
e
SAMPLE PAPER SOLUTION
Term-I Examination – 2021-22
Set-2 Answer Key
Class- XII, Subject – Computer Science (083)
Duration: 90 mins. MM: 35

General Instructions to the Examinee:


1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Part A and Part B have choices.
3. Part-A is having MCQs (Attempt 27 out of 35 questions).
4. Part- B has two questions based on Case studies.
a. Each case study has 4 case-based subparts.
b. An examinee is to attempt any 4 out of the 5 subparts.
5. All programming questions are to be answered using Python Language only.

Part-A
(Attempt any 27 questions from question no 1 to 35.)

1. What possible output(s) are expected to be displayed on screen at the time of


execution of the program from the following code?

from random import randint


LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = randint(3,8) – 1
second = randint(4,9) – 2
third = randint(6,11) – 3
print(LST[first],"#", LST[second],"#", LST[third],"#")

a) 20#25#25#
A
b) 30#40#70#
c) 15#60#70#
d) 35#40#60#

2. Specify the maximum values that can be assigned to each of the variables first,
second and third in the code given in Question no. 1 -
a) First: 6, Second: 6, Third: 7
b) First: 7, Second: 7, Third: 8 B
c) First: 3, Second: 4, Third: 6
d) First: 8, Second: 8, Third: 9

3. Which of the following is not a valid identifier name in Python?


(a) First_Name
(b) _Area
(c) 2nd_num C
(d) While

4. Which statement is correct for dictionary?


(a) A dictionary is an ordered set of key:value pair
C
(b) each of the keys within a dictionary must be unique
(c) each of the values in the dictionary must be unique

71 | P a g
e
(d) values in the dictionary are immutable
5. Identify the valid declaration of Record:
Record=(1342, “Pooja” , 45000, “Sales”)
(a) List
(b) Tuple B
(c) String
(d) Dictionary

6. Which of the following functions do we use to write data in a binary file?


(a) writer( )
C
(b) output( )
(c) dump( )
(d) send( )

7. Which operator is used for replication?


(a) +
C
(b) %
(c) *
(d) //

8. Which of the following functions generates an integer?


(a) uniform( )
B
(b) randint( )
(c) random( )
(d) None of the above

9. Consider the tuple in python named DAYS=( “SUN”, “MON”, “TUES”).


Identify the invalid statement(s) from the given below statements:
(a) S=DAYS[1]
(b) print(DAYS[2]) C
(c) DAYS[0]= “WED”
(d) LIST=list(DAYS)

10. t1=(2,3,4,5,6)
print(t1.index(4))
Output will be –
(a) 4 D
(b) 5
(c) 6
(d) 2
11. Which of the following statements correctly explain the function of tell()
method?
A
(a) tells the current position within the file.
(b) tell the name of file.
(c) move the current file position to a different location.
(d) it changes the file position only if allowed to do so else returns an error.

12. Which of the following statements correctly explain the function of seek()
method?
(a) tell the current position within the file.
(b) indicate that the next read or write occurs from that position in a file. D
(c) determine if you can move the file position or not.

72 | P a g
e
(d) move the current file position to a different location at a defined
offset.

13. Which of the following command is used to open a file “c:\temp.txt” in read-
mode only?
(a) infile = open(“c:\temp.txt”, “r”)
(b) infile = open(“c:\\temp.txt”, “r”) B
(c) infile = open(file = “c:\temp.txt”, “r+”)
(d) infile = open(file = “c:\\temp.txt”, “r+”)

14. Which of the following command is used to open a file “c:\temp.txt” in write-
mode only?
(a) outfile = open(“c:\temp.txt”, “w”)
(b) outfile = open(“c:\\temp.txt”, “w”) B
(c) outfile = open(file = “c:\temp.txt”, “w+”)
(d) outfile = open(file = “c:\\temp.txt”, “w+”)

15. Which of the following command 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”) A
(c) outfile = open(“c:\temp.txt”, “w+”)
(d) outfile = open(“c:\\temp.txt”, “r+”)

16. 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() A
(c) file.readline(n)
(d) file.readlines()

17. 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() B
(c) tmpfile.readline()
(d) tmpfile.readlines()

18. Which of the following commands can be used to read the remaining lines in a
file using the file object <tmpfile>?
(a) tmpfile.read(n)
(b) tmpfile.read() D
(c) tmpfile.readline()
(d) tmpfile.readlines()

19. Which of the following statement is False 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
(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.

73 | P a g
e
(d) When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
20. Which module is required to use built in function dump() C
(a) Math (b)flush (c)pickle (d)csv

21. Which of the following function is used to write data in binary mode? C
(a)write (b)output (c)dump (d)send

22. To read 2 characters from file object f1 command should be A


(a)f1.read(2) (b)f1.read() (c)f1.readline() (d) f1.readlines()

23. To get byte position from the beginning of file, function used is - B
(a)seek (b)tell (c)read (d)write

24. The file pointer, used to go to particular position A


(a)seek (b)tell (c)read (d)write

25. In regards to separated value files such as .csv and .tsv, what is the delimiter?
(a) Any character such as the comma (,) or tab (\t) that is used to
A
separate the column data.
(b) Delimiters are not used in separated value files
(c) Anywhere the comma (,) character is used in the file
(d) Any character such as the comma (,) or tab (\t) that is used to separate
the row data

26. In separated value files such as .csv and .tsv, what does the first row in the file
typically contain?
D
(a) The author of the table data
(b) The source of the data
(c) Notes about the table data
(d) The column names of the data
27. Assume you have a file object my_data which has properly opened a separated
value file that uses the tab character (\t) as the delimiter. What is the proper
way to open the file using the Python csv module and assign it to the variable
csv_reader? Assume that csv has already been imported.
C
(a) csv.tab_reader(my_data)
(b) csv.reader(my_data)
(c) csv.reader(my_data, delimiter='\t')
(d) csv.reader(my_data, tab_delimited=True)
28. When iterating over an object returned from csv.reader(), what is returned with
each iteration? For example, given the following code block that assumes
csv_reader is an object returned from csv.reader(), what would be printed to
the console with each iteration?

for item in csv_reader:


print(item) B

(a) The full line of the file as a string


(b) The row data as a list
(c) The individual value data that is separated by the delimiter
(d) The column data as a list

74 | P a g
e
29. Find the output of the following:
>>>Line = “Fun with Python”
>>> print (Name [ : 5 : -1])
C
(a) ith Python
(b) th Python
(c) nohtyP ht
(d) nohty

30. What will be the Output for the following code –


Language=["C", "C++", "JAVA", "Python", "VB", "BASIC", "FORTRAN"]
del Language[4]
Language.remove("JAVA")
Language.pop(3)
print(Language)
B
(a) ['C', 'C++', 'VB', 'FORTRAN']
(b) ['C', 'C++', 'Python', 'FORTRAN']
(c) ['C', 'C++', 'BASIC', 'FORTRAN']
(d) ['C', 'C++', 'Python', 'BASIC']

31. An absolute path name begins at the


(a) Leaf
D
(b) Stem
(c) current directory
(d) root

32. 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 D
(c) Undefined behavior
(d) The global variable is shadowed

33. Choose the correct option with reference to below Python code?
def fn(a):
print(a)
x=90
fn(x)
D
(a) x is the formal argument.
(b) a is the actual argument.
(c) fn(x) is the function signature.
(d) x is the actual argument.

34. What is the output of the following –


print(21//9%3, 2**2**3)

(a) 7 64 B
(b) 2 256

75 | P a g
e
(c) 7 256
(d) 2 64

35. Assertion (A) : Keys in a Python dictionary should be unique.


Reason (R) : Only immutable data types can be used as keys.

(a) A is true but R is false. D


(b) A is false but R is true.
(c) Both A and R are false.
(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.

Part-B
(Attempt any 4 out of the 5 subparts in each question)

36. In an online lottery system, names having exactly 5 characters are to be


displayed. Piyush has been asked to complete this task. He has created a function
FindNames() in python which read contents from a text file LOTTERY.TXT,
which contains names of participants, and displays those names, which are
having exactly 5 characters. He got confused with few statements and left it
blank. Help him complete the code.
def FindNames():
c=0
file=open('LOTTERY.TXT', ' ') #Statement-1
line = file. #Statement-2
word = #Statement-3
for c in word:
if : #Statement-4
print(c)
#Statement-5
FindNames()

(i) Write mode of opening the file in statement-1?


(a) A
D
(b) Ab
(c) W
(d) r
(ii) Fill in the blank in statement-2 to read the data from the file.
(a) File.Read()
B
(b) file.read()
(c) read.lines( )
(d) readlines( )

(iii) Fill in the blank in statement-3 to read data word by word.


(a) Line.Split()
C
(b) Line.split()
(c) line.split()
(d) split.word()

(iv) Fill in the blank in statement-4, which display the word having exactly 5
characters.
(a) len(c) ==5
(b) len(c)<5 A

76 | P a g
e
(c) len ( )= =5
(d) len ( )==6
(v) Fill in the blank in Statement-5 to close the file.
(a) file.close()
A
(b) File.Close()
(c) Close()
(d) end()

37. Snigdha is making a software on “Countries & their Capitals” in which various
records are to be stored/retrieved in CAPITAL.CSV data file. It consists some
records(Country & Capital). She has written the following code in python. Asa
programmer, you have to help her to successfully execute the program.

import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in CSV file
f=open(“CAPITAL.CSV”, ) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
# Statement-3
def ShowRec(): # Fn. to display all records from CSV file
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv. (NF) # Statement-4
for rec in NewReader:
print(rec[0], “#”, rec[1])

AddNewRec(“INDIA”, “NEW DELHI”)


AddNewRec(“CHINA”, “BEIJING”)
ShowRec() # Statement-5

(i) Which module should be imported in Statement-1.


(a) pickle
B
(b) csv
(c) file
(d) text

(ii) Which file mode to be passed to add new record in Statement-2.


(a) w+
D
(b) w
(c) wb
(d) a

(iii) What should be written in Statement-3 to close the file.


(a) close()
C
(b) fwriter.close()
(c) f.close()
(d) csv.close()

(iv) Which function to be used in Statement-4 to read the data from a csv file.
(a) read()
D
(b) readline()
(c) readlines()
(d) reader()

77 | P a g
e
(v) The output after executing Statement-5 will be –
(a) (“INDIA”, “NEW DELHI”)
(“CHINA”, “BEIJING”)
(b) INDIA NEW DELHI D
CHINA BEIJING
(c) INDIA, NEW DELHI
CHINA, BEIJING
(d) INDIA # NEW DELHI
CHINA # BEIJING

XXX

78 | P a g
e
SAMPLE PAPER -3
Term-I Examination – 2021-22
Model Question Paper-Set-3
Class- XII, Subject – Computer Science (083)
Duration: 90 mins. MM:35

General Instructions to the Examinee:


1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Part A and Part B have choices.
3. Part-A is having MCQs (Attempt 27 out of 35 questions).
4. Part- B has two questions based on Case studies.
a. Each case study has 4 case-based subparts.
b. An examinee is to attempt any 4 out of the 5 subparts.
5. All programming questions are to be answered using Python Language only.

Part-A
(Attempt any 27 questions from question no 1 to 35.)

1. Consider the following code: 1


import math
import random
print(str(int(math.pow(random.randint(2,4),2))),end= ' ')
print(str(int(math.pow(random.randint(3,4),2))),end= ' ')
print(str(int(math.pow(random.randint(4,4),2))))
What could be the possible outputs out of the given four choices?

(a) 2 3 4
(b) 9 16 16
(c) 16 4 16
(d) 2 4 9

2. What is the value of x – 1


x = 23.14 + 9//2
a) 27.0
b) 27.64
c) 28
d) 27.14

3. Which type of error will occur when the following code is executed? 1
>>>print(‘Cloud’ + 9)
(a) Syntax Error
(b) Type Error
(c) Name Error
(d) Value Error
4. Which of the following operators can be used with strings? 1
(a) /
79 | P a g
e
(b) *
(c) %
(d) –

5. Identify the valid declaration of data: 1


data=(1, “One” , 2 , “Two”, 3, “Three”)
(a) List
(b) Tuple
(c) String
(d) Dictionary
6. Which of the following functions do we use to read data in a Binary file? 1
(a) reader( )
(b) readlines( )
(c) load( )
(d) read( )
7. ‘+’ operator is used for _ in strings? 1
(a) Replication
(b) Duplication
(c) Concatenation
(d) Updation
8. What will be the maximum and minimum value of span? 1
>>>span = int(23 + random.random() * 8)
(a) 30 and 23
(b) 31 and 23
(c) 30 and 24
(d) 31 and 24

9. Consider the tuple in python named NUM=(1,2,3). 1


What will be the value of DOUBLE, if -
>>> DOUBLE=NUM*2
(a) (2,4,6)
(b) (1,1,2,2,3,3)
(c) (1,2,3,1,2,3)
(d) Error

10. t=(1,2,[3,4,5],"Confused") 1
print(t[3][2])
Output will be –
(a) r4
(b) 5
(c) n
(d) 2
11. What is the use of seek() method in files? 1
(a) sets the file’s current position at the offset
(b) sets the file’s previous position at the offset
(c) sets the file’s current position within the file
(d) none of the mentioned
12. Find the output of the following code – 1
fp = open("sample.txt", "r")
fp.read(8)
print(fp.tell())
fp.close()
(a) 0
80 | P a g
e
(b) 7
(c) 8
(d) 9

13. Which of the following command is used to open a file “c:\newfile.txt” in read 1
and write mode both?
(a) infile = open(“c:\ newfile.txt”, “r”)
(b) infile = open(“c:\\ newfile.txt”, “r”)
(c) infile = open(file = “c:\ newfile.txt”, “r+”)
(d) infile = open(file = “c:\\ newfile.txt”, “r+”)

14. Which of the following command is used to open a file “c:\bio.txt” in write 1
mode only?
(a) outfile = open(“c:\bio.txt”, “w”)
(b) outfile = open(“c:\\bio.txt”, “w”)
(c) outfile = open(file = “c:\bio.txt”, “w+”)
(d) outfile = open(file = “c:\\bio.txt”, “w+”)

15. Which of the following command is used to open a binary file “c:\record.dat” 1
in append-mode?
(a) outfile = open(“c:\\record.dat”, “a”)
(b) outfile = open(“c:\\record.dat”, “ab”)
(c) outfile = open(“c:\\record.dat”, “wb”)
(d) outfile = open(“c:\\record.dat”, “w+”)
16. What will be the output of the following code if content of the file “smile.txt” 1
is –
Smiling is infectious,
You catch it like the flu.
When someone smiled at me today,
I started smiling too.

file=open(“smile.txt”)
contents=file.read()
print(file.read(7))

(a) Smiling
(b) Smilin
(c) ng too.
(d) No output
17. The readlines() method returns 1
(a) A string
(b) A list of words
(c) A list of lines
(d) A list of integers
18. In which of the following modes, the existing data of file will not be lost? 1
(a) ab
(b) w+
(c) wb
(d) wb+
19. If a file is opened for reading, which of the following statement(s) is(are) 1
False?
(a) The file must exist on the disk on the specified path.
(b) If the file exists at the specified path, the file is successfully opened.
81 | P a g
e
(c) The file, even if at a different location on disk other than the specified
path, will get opened.
(d) Python gives error if the file does not exist at the specified path.

20. Which of the following is not a valid mode of opening a file? 1

(a) ab (b) rw (c) r+ (d) w+

21. Which of the following function is used to read data in binary mode? 1

(a)read (b)reader (c)load (d)readlines

22. Function to read all the characters of a file – 1

(a)f1.read(n) (b)f1.read() (c)f1.readline() (d) f1.readlines()

23. To move a file pointer f, 10 bytes ahead from the current position of file, 1
function used is –

(a)f.seek(10) (b)f.seek(10,0) (c) f.seek(10,1) (d) f.seek(10,2)

24. If the content of the file “wish.txt” is – “Happy”, then what will be the content 1
of the file after executing the following statements –

f=open(“wish.txt”, ‘w’)
f.write(“Birthday”)
f.close()

(a)Happy Birthday (b)HappyBirthday (c)Happy (d)Birthday

25. Which of the following is not a function of csv module? 1


(a) readline()
(b) writerow()
(c) reader()
(d) writer()
26. Whenever possible, what is the recommended way to ensure that a file object is 1
properly closed after usage?

(a) By using try block


(b) Making sure that close() function is used before end of the script
(c) By using the with statement
(d) It doesn’t matter
27. Which of the following is/are True? 1

(a) When you open a file for reading, if the file does not exist, an error
occurs.
(b) When you open a file for writing, if the file does not exist, a new file is
created.
(c) When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
(d) All of the above
28. Given the file image.png, which of the following is the correct way to open the 1
file for reading as a buffered binary file?
82 | P a g
e
(a) open(“image.png”)
(b) open(“image.png”, “r”)
(c) open(“image.png”, “rb”)
(d) open(“image.png”, “wb”)
29. What is the output of the following? 1
d = {“one”: 'I', “two” : 'II', “three” : 'III'}
for i in d:
print(i)

(a) one
two
three
(b) I
II
III
(c) one I
two II
three III
(d) 0
1
2

30. What is the output when following code is executed? 1


>>>print (r"Python\tProgram")

(a) Python Program


(b) r Python Program
(c) Error
(d) Python\tProgram

31. Which of the following is the use of id() function in python? 1


(a) id returns the identity of the object
(b) Every object doesn’t have a unique id
(c) All of the mentioned
(d) None of the mentioned

32. What is the output of the program given below? 1


num = 45
def func (num):
num = 23
func (num)
print ('num is now', num)

(a) num is now 45


(b) num is now 23
(c) num is now 68
(d) Error

33. Consider the expression given below. The value of X is: 1


X = 2+9*((3*12)-8)/10

(a) 30.0
83 | P a g
e
(b) 27.2
(c) 28.4
(d) 30.8

34. Find the output of the following – 1


>>> list1=[1,2,3]
>>> list2=[1,2,2,3]
>>> list1>list2

(a) Error
(b) False
(c) True
(d) None

35. Assertion (A): Parameters with default arguments can be followed by 1


parameters with no default argument.
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.

(a) A is true but R is false.


(b) A is false but R is true.
(c) Both A and R are false.
(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.

Part-B
(Attempt any 4 out of the 5 subparts in question no. 36 and 37)

36. Shubham Dixit of class 12 is writing a program to create a CSV file “hobby.csv”
which will contain Name and hobby name 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(Name,Hobby): # to write / add data into the CSV file
f=open(' hobby.csv','_ ') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([Name,Hobby])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
newFile = open(' hobby.csv','r')
newFileReader = csv._ (newFile) # Line 3
for row in newFileReader:
print (row[0], “@”, row[1])
newFile. # Line 4
addCsvFile(“Pranav”, “Cricket”)
addCsvFile(“Sunaina”, “Badminton”)
addCsvFile(“Manish”, “Painting”)
readCsvFile() #Line 5

84 | P a g
e
(i) Name the module he should import in Line 1. 1
(a) pickle
(b) csv
(c) file
(d) random
(ii) In which mode, Shubham should open the file to add data into the file.(Line 2) 1
(a) w+
(b) r
(c) r+
(d) a

(iii) Fill in the blank in Line 3 to read the data from a csv file. 1
(a) load()
(b) read()
(c) reader()
(d) readline()
(iv) Fill in the blank in Line 4 to close the file.. 1
(a) close()
(b) Close()
(c) CLOSE()
(d) end()
(v) Write the output he will obtain while executing Line 5. 1
(a) Pranav Cricket
Sunaina Badminton
Manish Painting
(b) “Pranav” “Cricket”
“Sunaina” “Badminton”
“Manish” “Painting”
(c) Pranav @ Cricket
Sunaina @ Badminton
Manish @ Painting
(d) “Pranav” @ “Cricket”
“Sunaina” @ “Badminton”
“Manish” @ “Painting”

37. Subrat Ray is learning to work with Binary files in Python using a process
known as Pickling/de-pickling. His teacher has given him the following
incomplete code, which is creating a Binary file namely Mydata.dat and then
opens, reads and displays the content of this created file.

import #Statement-1
sqlist=list()
for k in range(5):
sqlist.append(k*k)
fout=open(“mydata.dat”, ) #Statement-2
(sqlist,fout) #Statement-3
fout.close()
fin=open(“Mydata.dat”, “rb” )
mylist= (fin) #Statement-4
fin.close()
print(mylist) #Statement-5

85 | P a g
e
(i) Which module should be imported in Statement-1. 1
(a) pickle
(b) csv
(c) file
(d) text

(ii) Which file mode to be passed to write data in file in Statement-2. 1


(a) w+
(b) w
(c) wb
(d) a

(iii) What should be written in Statement-3 to write data onto the file. 1
(a) dump()
(b) write()
(c) pickle.dump()
(d) writeline()

(iv) Which function to be used in Statement-4 to read the data from the file. 1
(a) load()
(b) readline()
(c) readlines()
(d) pickle.load()

(v) The output after executing Statement-5 will be – 1


(a) 0 1 4 9 16
(b) 1, 4, 9, 16, 25
(c) [0, 1, 4, 9, 16]
(d) [1, 4, 9, 16, 25]

All the Best

86 | P a g
e
SOLUTION
Term-I Examination – 2021-22
Set-B Answer Key
Class- XII, Subject – Computer Science (083)
Duration: 90 mins. MM:35

General Instructions to the Examinee:


1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Part A and Part B have choices.
3. Part-A is having MCQs (Attempt 27 out of 35 questions).
4. Part- B has two questions based on Case studies.
a. Each case study has 4 case-based subparts.
b. An examinee is to attempt any 4 out of the 5 subparts.
5. All programming questions are to be answered using Python Language only.

Part-A
(Attempt any 27 questions from question no 1 to 35.)

1. Consider the following code:


import math
import random
print(str(int(math.pow(random.randint(2,4),2))),end= ' ')
print(str(int(math.pow(random.randint(3,4),2))),end= ' ')
print(str(int(math.pow(random.randint(4,4),2)))) B
What could be the possible outputs out of the given four choices?

(a) 2 3 4
(b) 9 16 16
(c) 16 4 16
(d) 2 4 9

2. What is the value of x –


x = 23.14 + 9//2

a) 27.0 D
b) 27.64
c) 28
d) 27.14

3. Which type of error will occur when the following code is executed?
>>>print(‘Cloud’ + 9)
(a) Syntax Error

87 | P a g
e
(b) Type Error B
(c) Name Error
(d) Value Error
4. Which of the following operators can be used with strings?
(a) /
B
(b) *
(c) %
(d) –
5. Identify the valid declaration of data:
data=(1, “One” , 2 , “Two”, 3, “Three”)
B
(a) List
(b) Tuple
(c) String
(d) Dictionary

6. Which of the following functions do we use to read data in a Binary file?


(a) reader( )
C
(b) readlines( )
(c) load( )
(d) read( )

7. ‘+’ operator is used for _ in strings?


(a) Replication
C
(b) Duplication
(c) Concatenation
(d) Updation
8. What will be the maximum and minimum value of span?
>>>span = int(23 + random.random() * 8)
A
(a) 30 and 23
(b) 31 and 23
(c) 30 and 24
(d) 31 and 24
9. Consider the tuple in python named NUM=(1,2,3).
What will be the value of DOUBLE, if -
>>> DOUBLE=NUM*2
(a) (2,4,6) C
(b) (1,1,2,2,3,3)
(c) (1,2,3,1,2,3)
(d) Error
10. t=(1,2,[3,4,5],"Confused")
print(t[3][2])
Output will be –
(a) 4 C
(b) 5
(c) n
(d) 2

11. What is the use of seek() method in files?


(a) sets the file’s current position at the offset
A
(b) sets the file’s previous position at the offset
(c) sets the file’s current position within the file
(d) none of the mentioned

88 | P a g
e
12. Find the output of the following code –
fp = open("sample.txt", "r")
fp.read(8)
print(fp.tell())
fp.close()
(a) 0
(b) 7 C
(c) 8
(d) 9
13. Which of the following command is used to open a file “c:\newfile.txt” in read
and write mode both?
(a) infile = open(“c:\ newfile.txt”, “r”)
(b) infile = open(“c:\\ newfile.txt”, “r”) D
(c) infile = open(file = “c:\ newfile.txt”, “r+”)
(d) infile = open(file = “c:\\ newfile.txt”, “r+”)

14. Which of the following command is used to open a file “c:\bio.txt” in write
mode only?
(a) outfile = open(“c:\bio.txt”, “w”)
(b) outfile = open(“c:\\bio.txt”, “w”) B
(c) outfile = open(file = “c:\bio.txt”, “w+”)
(d) outfile = open(file = “c:\\bio.txt”, “w+”)

15. Which of the following command is used to open a binary file “c:\record.dat”
in append-mode?
(a) outfile = open(“c:\\record.dat”, “a”)
(b) outfile = open(“c:\\record.dat”, “ab”) A
(c) outfile = open(“c:\\record.dat”, “wb”)
(d) outfile = open(“c:\\record.dat”, “w+”)

16. What will be the output of the following code if content of the file “smile.txt”
is –
Smiling is infectious,
You catch it like the flu.
When someone smiled at me today,
I started smiling too.

file=open(“smile.txt”)
contents=file.read()
print(file.read(7))

(a) Smiling
(b) Smilin D
(c) ng too.
(d) No output
17. The readlines() method returns
(a) A string
C
(b) A list of words
(c) A list of lines
(d) A list of integers
18. In which of the following modes, the existing data of file will not be lost?
(a) ab
(b) w+ A

89 | P a g
e
(c) wb
(d) wb+
19. If a file is opened for reading, which of the following statement(s) is(are)
False?
C
(a) The file must exist on the disk on the specified path.
(b) If the file exists at the specified path, the file is successfully opened.
(c) The file, even if at a different location on disk other than the
specified path, will get opened.
(d) Python gives error if the file does not exist at the specified path.
20. Which of the following is not a valid mode of opening a file? B
(a) ab (b) rw (c) r+ (d) w+

21. Which of the following function is used to read data in binary mode? C
(a)read (b)reader (c)load (d)readlines

22. Function to read all the characters of a file – B


(a)f1.read(n) (b)f1.read() (c)f1.readline() (d)
f1.readlines()

23. To move a file pointer f, 10 bytes ahead from the current position of file, C
function used is -
(a)f.seek(10) (b)f.seek(10,0) (c) f.seek(10,1) (d) f.seek(10,2)

24. If the content of the file “wish.txt” is – “Happy”, then what will be the content
of the file after executing the following statements –

f=open(“wish.txt”, ‘w’) D
f.write(“Birthday”)
f.close()

(a)Happy Birthday (b)HappyBirthday (c)Happy (d)Birthday

25. Which of the following is not a function of csv module?


(a) readline()
A
(b) writerow()
(c) reader()
(d) writer()

26. Whenever possible, what is the recommended way to ensure that a file object is
properly closed after usage?
(a) By using try block
(b) Making sure that close() function is used before end of the script C
(c) By using the with statement
(d) It doesn’t matter

27. Which of the following is/are True?


(a) When you open a file for reading, if the file does not exist, an error
occurs.
(b) When you open a file for writing, if the file does not exist, a new file is D
created.
(c) When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
(d) All of the above
90 | P a g
e
28. Given the file image.png, which of the following is the correct way to open the
file for reading as a buffered binary file?
(a) open(“image.png”)
(b) open(“image.png”, “r”) C
(c) open(“image.png”, “rb”)
(d) open(“image.png”, “wb”)

29. What is the output of the following?


d = {“one”: 'I', “two” : 'II', “three” : 'III'}
for i in d:
print(i)
A
(a) one
two
three
(b) I
II
III
(c) one I
two II
three III
(d) 0
1
2

30. What is the output when following code is executed?


>>>print (r"Python\tProgram")

(a) Python Program


(b) r Python Program
D
(c) Error
(d) Python\tProgram

31. Which of the following is the use of id() function in python?


(a) id returns the identity of the object
A
(b) Every object doesn’t have a unique id
(c) All of the mentioned
(d) None of the mentioned

32. What is the output of the program given below?


num = 45
A
def func (num):
num = 23
func (num)
print ('num is now', num)

(a) num is now 45


(b) num is now 23
(c) num is now 68
(d) Error

91 | P a g
e
33. Consider the expression given below. The value of X is:
X = 2+9*((3*12)-8)/10
B
(a) 30.0
(b) 27.2
(c) 28.4
(d) 30.8

34. Find the output of the following –


>>> list1=[1,2,3]
>>> list2=[1,2,2,3]
>>> list1>list2
(a) Error
C
(b) False
(c) True
(d) None

35. Assertion (A) : Parameters with default arguments can be followed by


parameters with no default argument.
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.
B
(a) A is true but R is false.
(b) A is false but R is true.
(c) Both A and R are false.
(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.

Part-B
(Attempt any 4 out of the 5 subparts in question no. 36 and 37)

36. Shubham Dixit of class 12 is writing a program to create a CSV file “hobby.csv”
which will contain Name and hobby name 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(Name,Hobby): # to write / add data into the CSV file
f=open(' hobby.csv','_ ') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([Name,Hobby])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
newFile = open(' hobby.csv','r')
newFileReader = csv._ (newFile) # Line 3
for row in newFileReader:
print (row[0], “@”, row[1])
newFile. # Line 4
addCsvFile(“Pranav”, “Cricket”)
addCsvFile(“Sunaina”, “Badminton”)
addCsvFile(“Manish”, “Painting”)
92 | P a g
e
readCsvFile() #Line 5

(i) Name the module he should import in Line 1.


(a) pickle
B
(b) csv
(c) file
(d) random

(ii) In which mode, Shubham should open the file to add data into the file.(Line 2)
(a) w+
D
(b) r
(c) r+
(d) a

(iii) Fill in the blank in Line 3 to read the data from a csv file.
(a) load()
C
(b) read()
(c) reader()
(d) readline()

(iv) Fill in the blank in Line 4 to close the file. A


(a) close()
(b) Close()
(c) CLOSE()
(d) end()

(v) Write the output he will obtain while executing Line 5.


(a) Pranav Cricket
C
Sunaina Badminton
Manish Painting
(b) “Pranav” “Cricket”
“Sunaina” “Badminton”
“Manish” “Painting”
(c) Pranav @ Cricket
Sunaina @ Badminton
Manish @ Painting
(d) “Pranav” @ “Cricket”
“Sunaina” @ “Badminton”
“Manish” @ “Painting”

37. Subrat Ray is learning to work with Binary files in Python using a process
known as Pickling/de-pickling. His teacher has given him the following
incomplete code, which is creating a Binary file namely Mydata.dat and then
opens, reads and displays the content of this created file.

import #Statement-1
sqlist=list()
for k in range(5):
sqlist.append(k*k)
fout=open(“mydata.dat”, ) #Statement-2
93 | P a g
e
(sqlist,fout) #Statement-3
fout.close()
fin=open(“Mydata.dat”, “rb” )
mylist= (fin) #Statement-4
fin.close()
print(mylist) #Statement-5

(i) Which module should be imported in Statement-1.


(a) pickle
A
(b) csv
(c) file
(d) text

(ii) Which file mode to be passed to write data in file in Statement-2.


(a) w+
C
(b) w
(c) wb
(d) a

(iii) What should be written in Statement-3 to write data onto the file.
(a) dump()
C
(b) write()
(c) pickle.dump()
(d) writeline()

(iv) Which function to be used in Statement-4 to read the data from the file.
(a) load()
D
(b) readline()
(c) readlines()
(d) pickle.load()

(v) The output after executing Statement-5 will be –


(a) 0 1 4 9 16
C
(b) 1, 4, 9, 16, 25
(c) [0, 1, 4, 9, 16]
(d) [1, 4, 9, 16, 25]

94 | P a g
e
95 | P a g
e

You might also like