You are on page 1of 161

TERM- 1 BOARD EXAMINATIONS

UNIT-1 PYTHON MCQ’S


CHAPTER WISE AND TOPIC WISE : CHAPTER-1 - PYTHON REVISION TOUR-1

1. Which keyword can be used in any place in Python It's a syntax error.
code to tell interpreter “to do Adds string1 to string2 (both must be in numeric
nothing” and move to next instruction format).
skip Correct answer
continue Concatenates string1 and string2.
next 6. Python is compiled language. True or False?
pass True
Correct answer False
pass Correct answer
2. Are there tools available to help find bugs, or False
perform static analysis? 7. Which of these should you include in order to pass
Yes, PyErrs. variables to a script?
Yes, PyChecker and Pylint. from sys import getarg
No, you must find the bugs on your own. from system import argv
Yes, PyStats. from sys import args
Correct answer from sys import argv
Yes, PyChecker and Pylint. Correct answer
3. Python was created by ____________. from sys import argv
James Gosling 8. Which of the following statements is true?
Steve Jobs Python is an interpreted language.
Guido van Rossum Python is a high level programming language.
Google Python is an object-oriented language.
Guido van Rossum All of the above.
What is used to define a block of code (body of loop, Correct answer
function etc.) in Python? All of the above.
Curly braces 9. In Python, 'Hello', is the same as "Hello"
Parenthesis True
Indentation False
Quotation 10.What is the correct file extension for Python files?
4. A Python paragraph comment uses the style .pyth
________. .pt

// comments // .pyt
/ comments / .py
''' comments ''' Correct answer
/# comments #/ .py
Correct answer 11.In Python, a syntax error is detected by the
''' comments ''' ________ at _________.
5. What does the expression string1 + string2 do? compiler/at compile time
Repeats string1 string2 times (string2 must be in interpreter/at runtime
1

numeric format). compiler/at runtime


Page

Concatenates string1 and string2. interpreter/at compile time

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Correct answer False
interpreter/at runtime 17.A ___________ error does not cause the program
12.Which of the following is correct? to abort, but produces incorrect
Comments are for programmers for better results.
understanding of the program. syntax
Python Interpreter ignores comment. runtime
You can write multi-line comments in Python using logical
triple quotes, either ''' or """. Correct answer
All the above logical
Correct answer 18.________ is interpreted.
All the above Python
13.Is it possible to link a Python program to code C++
written in C? Ada
Yes; the C code can be in a form of a dynamically or a Pascal
statically linked library. 19.Which of the following statements is true?
No, it is impossible. Python 3 is a newer version, but it is backward
Yes, but the C code must be provided in a form of a compatible with Python 2.
dynamically linked library. Python 3 is a newer version, but it is not backward
Yes, but C code must be provided in a form of compatible with Python 2.
statically linked library. A Python 2 program can always run on a Python 3
Correct answer interpreter.
Yes; the C code can be in a form of a dynamically or A Python 3 program can always run on a Python 2
a statically linked library. interpreter.
14.Which of the following is correct? Correct answer
Python Interpreter ignores comment. Python 3 is a newer version, but it is not backward
Comments are for programmers for better compatible with Python 2.
understanding of the program. 20.A Python line comment begins with ________.
You can write multi-line comments in Python using //
triple quotes, either ''' or """. /#
All of the above $$
Correct answer 21.What is a correct syntax to output "Hello World"
All of the above in Python?
15.Is it possible to check for more than one error in print("Hello World")
one except line? echo("Hello World");
Yes, if the exception types are enclosed in echo "Hello World"
parentheses. p("Hello World")
No, it is not possible. 22.________ is an object-oriented programming
Yes, if the exception types are enclosed in square language.
brackets. Java
Yes, if the exception types are enclosed in curly C++
braces. Python
Correct answer
Yes, if the exception types are enclosed in All the above
parentheses. Correct answer
All the above
16.Python syntax is case-sensitive. 23.How do you insert comments in Python code?
2
Page

True #This is a comment

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


/This is a comment/ Yes
//This is a comment 30.Which of the following is not a variable?
//This is a comment# in
Correct answer on
#This is a comment it
24.Which of the following is not a keyword? __init__
eval Correct answer
assert in
nonlocal 31.Which of the following are Python reserved words
pass (keywords):
Correct answer default
eval and
25.What is the output of the following code? goto
25 class
75 None
35 Correct answer
None class
Correct answer
None 32.All keywords in Python are in _________
26.Which of the following is not a keyword? Lower case
open Upper case
lambda None of the mentioned
is Capitalized
except Correct answer
Correct answer None of the mentioned
open 33.From the execution of the statements n = 300, m
27.Select the correct output of the following code. = n how many objects and
references will be created?
Python Two objects, two references
15 One object, two references
Blank Two objects, one reference
Correct answer One object, one reference
Python Correct answer
28.All keywords available in Python are in One object, two references
Uppercase 34.What is the output of the following code?
Lowercase 70
Both uppercase and lowercase 63
CamelCase 152530
Correct answer TypeError: unsupported operand type(s) for +: 'int'
Both uppercase and lowercase and 'str'
29.Is Python case sensitive when dealing with Correct answer
identifiers? TypeError: unsupported operand type(s) for +: 'int'
Yes and 'str'
None of the above 35.What Python built-in function returns the unique
No number assigned to an object:
machine dependent refnum()
3
Page

Correct answer id()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


ref() x_y_z = 1,000,000
identity() Correct answer
Correct answer xyz=123
id() 43.Which of the following cannot be a variable ?
36.Which of the following is valid ? _name_
_var = 'python' def
__var = 'python' at
_name_ = 'python' on
All the above Correct answer
Correct answer def
All the above 44.Which of the following cannot be a variable?
37.In Python, a variable may be assigned a value of __init__
one type, but later it can assigned a in
value of a different type: it
True on
False Correct answer
38.What is the maximum possible length of an in
identifier or an attribute ? 45.Why are local variable names beginning with an
32 underscore discouraged?
64 they are used to indicate a private variables of a class
73 they confuse the interpreter
Any length they are used to indicate global variables
Correct answer they slow down execution
Any length Correct answer
39.How to swap two variables in one line ? they are used to indicate a private variables of a
x=y class
x ^= y ^= x ^= y 46.Which of the following is not a keyword?
x, y = y, x pass
(x ^= y), (y ^= x), (x ^= y) class
Correct answer max
x, y = y, x def
40.What is the maximum possible length of an 47.Which of the following are valid Python variable
identifier? names:
31 characters ver1.3
63 characters return
79 characters home_address
None of the above route66
41.What is the output of the following code? Age
4square
0 48.What is the output of the following code?
63 50
Error 100
None Error
42.Which of the following is an invalid statement? None
num = 1,000,000 Correct answer
xyz=123 100
4
Page

x,y,z = 1, 2, 3 49.What is the output of the following code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


75 15
0 Error
Error None
None Correct answer
Correct answer 25
75 57.Output of print(f"Python {3 + .2}")
50.What is the output of the following code? 3.2
Page 11 of 391 3+.2
0 Shows error
70 Python 3.2
Error Correct answer
None Python 3.2
Correct answer 58.Which of the following is an invalid variable?
Error _var_
51.Which of the following is an invalid variable? 1var
odd_num_1 _var_1
1_odd_num All the above
num Correct answer
Correct answer 1var
1_odd_num 59.Which of the following is an invalid statement?
52.What is the output of the following code? Page 13 of 391
JhonsJhonsJhonsJhons a_b_c = 100
Jhons abc = 100, 'python'
JhonsJhonsJhonsJhonsJhonsJhons a b c = 1 00
Syntax Error a, b, c = 1, 0, 0
Correct answer 60.Which of the following statements assigns the
JhonsJhonsJhonsJhonsJhonsJhons value 100 to the variable x in Python:
53.In Python, a variable must be declared before it is let x = 100
assigned a value: x := 100
True x ← 100
False x = 100
54.What is the output of the following code? x << 100
Page 12 of 391 Correct answer
25 x = 100
15 61.In Python if a variable is assigned a value
Error anywhere within the function’s body, it’s
None assumed to be a local unless explicitly declared as
55.Is Python case sensitive while dealing with global.
identifiers? True
Yes False
No 62.Which of the following is true for variable names
OS dependent in Python?
None of the above all private members must have leading and trailing
Correct answer underscores
Yes underscore and ampersand are the only two special
56.What is the output of the following code? characters allowed
5
Page

25 unlimited length

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


none of the mentioned 69.What gets printed
Correct answer <class 'set'>
unlimited length <class 'dict'>
63.Which of the following is not a complex number? <class 'list'>
a = 2 + 3j Page 15 of 391
a = complex(2, 3) <class 'tuple'>
a = 2 + 3l <class 'object'>
a = 2 + 3J 70.In order to store values in terms of key and value
Correct answer which core data type is used.
a = 2 + 3l list
64.Boolean type is a subtype of Integer data type in tuple
Python class
True dictionary
False Correct answer
Correct answer dictionary
True 71.What will be the output of the following Python
65.What is the result of round(0.5) - round(-0.5) code snippet?
Page 14 of 391 indentation Error
1.0 cannot perform mathematical operation on strings
2.0 hello2
0.0 hello2hello2
None of the mentioned Correct answer
66.Given a function that does not return any value, indentation Error
What value is thrown by default 72.If x and y are strings, which of the following is
when executed in shell. equivalent to [x] + [y] ?
int [x].extend([y])
bool [x,y]
void [x + y]
None [x].append(y)
Correct answer Correct answer
None [x,y]
67.Select all immutable basic data types: 73.What gets printed?
Dictionary <class 'function'>
String <class 'tuple'>
Integer <class 'NoneType'>
Set <class 'str'>
Float <class 'type'>
List Page 16 of 391
Tuple 74.Which of the following is incorrect?
68.What gets printed? a = 0b101
abb a = 0x4f5
abb abb a = 19023
abb 2 a = 03964
2 75.In order to execute an operation over arguments
Error of different data types, convert all of
Correct answer them to the same type beforehand.
6
Page

Error True

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


False int
Correct answer bool
False float
76.What gets printed? None
<class 'int'> Correct answer
<class 'list'> int
<class 'tuple'> 82.What gets printed?
<class 'dict'> <class 'int'>
<class 'set'> <class 'number'>
77.What should the below code print? <class 'float'>
<class 'complex'> <class 'double'>
<class 'unicode'> <class 'tuple'>
<class 'int'> Page 18 of 391
<class 'float'> Correct answer
<class 'dict'> <class 'float'>
Correct answer 83.What is the output of print 0.2 + 0.3 == 0.5?
<class 'complex'> True
78.Select all valid basic data types in Python 3 False
Double Error
String Correct answer
Integer True
Boolean 84.Which of the following is incorrect?
Float float('inf')
Page 17 of 391 float('nan')
Decimal float('56'+'78')
Union float('12+34')
Complex number Correct answer
Correct answers float('12+34')
String 85.Complex numbers in Python have real and
Integer imaginary parts. In Python they are
Float represented as:
Complex number One Integer and one floating point number
79.Select all numeric data types in Python Each is floating point number
String Each is Integer
Integer Both are strings
Double 86.List in Python can hold elements of same type
Float only. True or False?
Complex number True
80.What error occurs when you execute the False
following Python code snippet? Correct answer
SyntaxError False
NameError 87.Strings in Python should be en-quoted in double
ValueError quotation marks (“). True or False?
TypeError True
Correct answer False
NameError Correct answer
7
Page

81.What is the return value of trunc()? False

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


88.What data type is the object below? All of the mentioned
Page 19 of 391 94.Only immutable data types can be used as keys
list for dictionaries in Python. True or
dictionary False?
array True
tuple False
89.What is the output of the following code? 95.What does 3 ^ 8 evaluate to?
<class 'NoneType'> 81
<class 'tuple'> 24
<class 'type'> 11
<class 'function'> 5
<class 'bool'> Correct answer
Correct answer 11
<class 'function'> 96.What is the type of inf?
90.Which of the following data types can be used as Boolean
keys in dictionaries in Python? Integer
Select all that apply Float
List Complex
Set 97.Which of the following can be used as a dictionary
Integer key?
String list
Dictionary set
Any type of value dictionary
Correct answer tuple
Any type of value None of the above
91.What does ~~~~~~6 evaluate to? 98.Which of the following will run without errors?
6 -5 - round(45.8)
11 round(6352.898,2,5)
11 round()
Correct answer Page 21 of 391
6 round(7463.123,2,1)
92.Which of the following results in a SyntaxError? Correct answer
‘”Once upon a time…”, she said.’ round(45.8)
“He said, ‘Yes!'” 99.What is the return type of function id?
‘3\’ int
”’That’s okay”’ float
93.In Python types are directly interpreted by the bool
compiler, so check the following dict
operation to be performed. Correct answer
Page 20 of 391 int
Objective is to make sure a has a integer value, select 100. What does ~5 evaluate to?
all that apply (Python 3.xx) -5
a = 15 // 3 -7
a = int(15 / 3) -6
a = 15 % 3 5
All of the mentioned Correct answer
8
Page

Correct answer -6

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


101. Which of these in not a core data type? variables and that have by default some
Lists meaning in that language. So, Option B is correct.
Dictionary 04. Which one of the following is the correct
Tuples extension of the Python file?
Class A. .py
Correct answer B. .python
Class C. .p
102. What is the output of the following code? D. None of these
<class 'tuple'> View Answer
<class 'int'> Answer : A
<class 'set'> Explanation: “.py” is the extension of the python file.
<class 'complex'> 05. What is output for - min(”hello world”)
<class 'list'> A. e
Correct answer B. a blank space character
<class 'list'> C. w
Page 22 of 391 D. hello world
OBJECCTIVE TYPE QUESTIONS: View Answer
01. In which year was the Python language Page 23 of 391
developed? Answer : B
A. 1995 Explanation: python considers a blank space
B. 1972 character as the minimum value in a string.
C. 1981 06. How to output the string “May the odds favor
D. 1989 you” in Python?
View Answer A. print(“May the odds favor you”)
Answer : D B. echo(“May the odds favor you”)
Explanation: Python language was developed by C. System.out(“May the odds favor you”)
Guido van Rossum in 1989 (late 1980s). D. printf(“May the odds favor you”)
02. Who developed the Python language? View Answer
A. Zim Den Answer : A
B. Guido van Rossum Explanation: print() function is used to display
C. Niene Stom something to the user in python.
D. Wick van Rossum 07. In which year was the Python 3.0 version
View Answer developed?
Answer : B A. 2005
Explanation: Python language was developed by B. 2000
Guido van Rossum in the Netherlands in C. 2010
the late 1980s. D. 2008
03. How many keywords are there in python 3.7? View Answer
A. 32 Answer : D
B. 33 Explanation: Python 3.0 version was developed on
C. 31 December 3, 2008.
D. 30 08. Which character is used in Python to make a
View Answer single line comment?
Answer : B A. /
Explanation: There are 33 keywords in Python 3.7. B. //
Keywords are reserved words of the C. #
9
Page

programming language that can not be used as D. ?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


View Answer type. But we can create classes on our
Answer : C own.
Explanation: “#” character is used in the Python to 13. . Which of the following has more precedence?
make a single-line comment. A. +
09. Python is often described as a: B. ()
A. Batteries excluded language C. /
B. Gear included language D. –
C. Batteries included language View Answer
D. Gear excluded language Answer : B
View Answer Explanation: () has more precedence in python
Answer : C programming language.
Explanation: Python programming language is often 14. In which language is Python written?
described as a “batteries included” A. English
language due to its comprehensive standard library B. PHP
10. What do we use to define a block of code in C. C
Python language? D. All of the above
A. Indentation View Answer
B. Key Answer : C
C. Brackets Explanation: Python is written in the C programming
D. None of these language, and it is also called CPython.
View Answer 15. Do we need to compile a program before
Page 24 of 391 execution in Python?
Answer : A A. No
Explanation: Python uses indentation to define B. Yes
blocks of code. Indentations are simply View Answer
spaces or tabs used as an indicator that is part of the Page 25 of 391
indent code child as Curly braces are Answer : A
used in the C programming language. Explanation: We don’t need to compile a program
11. Mathematical operations can be performed on a before execution in Python.
string in Python? State whether 16. How to convert the uppercase letters in the
true or false: string to lowercase in Python?
A. False A. lowercase()
B. True B. capilaize()
View Answer C. lower()
Answer : A D. toLower()
Explanation: We can’t perform mathematical View Answer
operations on the string even if the string is in Answer : C
the form: ‘1234…’. Explanation: lower() function is used to convert
12. . Which one of the following is not a python’s string into lower case in python.
predefined data type? 17. How to capitalize only the first letter of a
A. List sentence in Python?
B. Dictionary A. uppercase() method
C. Tuple B. capitalize() method
D. Class C. upper() method
View Answer D. None of the above
10

Answer : D View Answer


Page

Explanation: Class is not a python’s predefined data Answer : B

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: capitalize() method is used to capitalize 02. Which is the correct operator for power(xy)?
only the first letter of a sentence in A. X^y
Python. B. X**y
18. How to convert the lowercase letters in the C. X^^y
string to uppercase in Python? D. None of the mentioned
A. uppercase() View Answer
B. toUpper() Answer : B
C. capitalize() Explanation: In python, power operator is x**y i.e.
D. upper() 2**5=32.
View Answer 03. What is the output of the following addition (+)
Answer : D operator
Explanation: upper() function is used to convert the a = [10, 20]
lowercase letters in the string to b=a
uppercase in Python. b += [30, 40]
19. How to check whether all the characters in a print(a)
string is printable? print(b)
A. print() method A. [10, 20, 30, 40]
B. printable() method [10, 20, 30, 40]
C. isprintable() method B. [10, 20]
D. echo() method [10, 20, 30, 40]
View Answer C. [10, 20, 10, 20]
Answer : C [10, 20, 30, 40]
Explanation: isprintable() method. D. [10, 20]
20. How to swap case in Python i.e. lowercase to [30, 40]
uppercase and vice versa? View Answer
A. casefold() method Answer : A
B. case() method Explanation: Because since b and a reference to the
C. convert() method same object, when we use the addition
D. swapcase() method assignment operator += on b, it changes both a and
View Answer b.
Page 26 of 391 04. Which function overloads the >> operator?
Answer : D A. more()
Explanation: swapcase(). B. gt()
Page 27 of 391 C. ge()
01. In the Python statement x = a + 5 – b: Page 28 of 391
a and b are ________ D. None of the above
a + 5 - b is ________ View Answer
A. terms, a group Answer : D
B. operators, a statement Explanation: rshift() function overloads the >>
C. operands, an expression operator
D. operands, an equation 05. What is the value of the expression 100 / 25?
View Answer A. 4
Answer : C B. 4.0
Explanation: The objects that operators act on are C. 0
called operands. An expression involving D. 25
11

operators and operands is called an expression So, View Answer


Page

option C is correct. Answer : B

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: The result of standard division is always Answer : A
float. The value of 100 // 25 (integer Explanation: Internal representation of float objects
division) is 4. is not precise, so they can’t be relied on
06. Which one of these is floor division? to equal exactly what you think they will:
A. // >>> 1.1 + 2.2 == 3.3
B. / False
C. % You should instead compute whether the numbers
D. None of the above are close enough to one another to satisfy
View Answer a specified tolerance:
Answer : A >>> tolerance = 0.00001
Explanation: When both of the operands are integer >>> abs((1.1 + 2.2) – 3.3) < tolerance
then python chops out the fraction part True
and gives you the round-off value, to get the 10. What is the order of precedence in python?
accurate answer use, floor division. This is floor i) Parentheses
division. For ex, 5/2 = 2.5 but both of the operands ii) Exponential
are integers so the answer of this iii) Multiplication
expression in Python is 2. To get the 2.5 as an iv) Division
answer, use floor division. v) Addition
07. What is the output of the following assignment vi) Subtraction
operator A. ii,i,iii,iv,v,vi
a = 10 B. ii,i,iv,iii,v,vi
b = a -= 2 C. i,ii,iii,iv,vi,v
print(b) D. i,ii,iii,iv,v,vi
A. 8 View Answer
B. 10 Answer : D
C. Syntax Error Explanation: For order of precedence, just remember
D. No error but no output too this PEMDAS-Parentheses>
View Answer Exponential> Multiplication> Division> Addition>
Answer : C Subtraction (similar to BODMAS).
Explanation: b = a -= 2 expression is Invalid 11. What is the output of the following code
08. Which operator is overloaded by the or() x=6
function? y=2
A. || print(x ** y)
B. | print(x // y)
C. // A. 66
D. / 0
View Answer B. 36
Page 29 of 391 0
Answer : B Page 30 of 391
Explanation: or() function overloads the bitwise OR C. 66
operator “|”. 3
09. Should you use the == operator to determine D. 36
whether objects of type float are 3
equal? View Answer
A. Nope, not a good idea. Answer : D
12

B. Sure! Go for it. Explanation: The Exponent (**) operator performs


Page

View Answer exponential (power) calculation. so here

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


6 ** 2 means 6*6 = 36 The // is the Floor Division 16. Given a function that does not return any value,
operator so 6//2=3 what value is shown when executed
12. What is the output of the following program : at the shell?
i=0 A. int
while i < 3: B. bool
print i C. void
i++ D. None
print i+1 View Answer
A. 0 2 1 3 2 4 Answer : D
B. 0 1 2 3 4 5 Explanation: Python explicitly defines the None
C. Error object that is returned if no value is
D. 1 0 2 4 3 5 specified.
View Answer 17. The function sqrt() from the math module
Answer : C computes the square root of a number.
Explanation: Python Programming language does not Will the highlighted line of code raise an exception?
support ‘++’ operator. x = -100
13. Suppose the following statements are executed: from math import sqrt
a = 100 x > 0 and sqrt(x)
b = 200 A. Yes
What is the value of the expression a and b? B. No
A. True C. void
B. 0 D. None
C. False View Answer
D. 200 Answer : B
E. 100 Explanation: In the highlighted line, x > 0 is False. The
View Answer expression is already known to be
Answer : D falsy at that point. Due to short-circuit evaluation,
Explanation: None sqrt(x) (which would raise an exception) is
14. Operators with the same precedence are not evaluated.
evaluated in which manner? 18. Which one of the following has the same
A. Left to Right precedence level?
B. Right to Left A. Addition and Subtraction
C. Can’t say B. Multiplication, Division and Addition
D. None of the mentioned C. Multiplication, Division, Addition and Subtraction
View Answer D. Addition and Multiplication
Answer : A View Answer
Explanation: None Answer : A
Page 31 of 391 Explanation: “Addition and Subtraction” are at the
15. Which of the following operators has the same precedence level. Similarly,
highest precedence? “Multiplication and Division” are at the same
A. not precedence level. However, Multiplication and
B. & Division operators are at a higher precedence level
C. * than Addition and Subtraction operators.
D. + Page 32 of 391
View Answer 19. What is the output of the following code
13

Answer : C print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j))


Page

Explanation: None A. True True False True

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


B. False True True True D. declare x=7
C. True True False True View Answer
D. False True False True Answer : C
View Answer Explanation: The correct way of declaring and
Answer : B initializing a variable, x with the value 7 is
Explanation: If we pass A zero value to the bool() x=7.
constructor, it will treat it as false. Any 04. What will be the output of statement
non-zero value is true. 2**2**2**2
20. What is the output of the expression print(-18 // A. 16
4) B. 256
A. -4 C. 32768
B. -5 D. 65536
C. 4 View Answer
D. 5 Answer : D
View Answer Explanation: The statement is equivalent to 2^16. So,
Answer : B Option D is correct.
Explanation: In the case of the floor division 05. Which of the following statement is False?
operator(//), when the result is negative, the A. Variable names can be arbitrarily long.
result is rounded down to the next smallest (big B. They can contain both letters and numbers.
negative) integer. C. Variable name can begin with underscore.
Page 33 of 391 D. Variable name can begin with number.
01. Which of the following statements assigns the View Answer
value 25 to the variable x in Python: Page 34 of 391
A. x ← 25 Answer : D
B. x = 25 Explanation: Variable name can not begin with the
C. x := 25 number, it can only begin with a letter or
D. int x = 25 underscore.
E. x << 25 06. What is the output of the following code: print
View Answer 9//2
Answer : B A. 4
02. In Python, a variable may be assigned a value of B. 4.5
one type, and then later assigned a C. 4.0
value of a different type: D. Error
A. False View Answer
B. True Answer : A
View Answer Explanation: Floor Division operator “//” – The
Answer : B division of operands where the result is the
Explanation: Variables are not statically typed in quotient in which the digits after the decimal point
Python, as they are in some other are removed. So in this case we get 4 as
programming languages. the answer. So, Option A is correct.
03. Which one of the following is the correct way of 07. Which of the following is not a valid variable
declaring and initializing a name in Python?
variable, x with the value 7? A. _var
A. int x B. var_name
x=7 C. var11
14

B. int x=7 D. 5var


Page

C. x=7 View Answer

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer : D C. It indicates a private variable of a class
Explanation: 5var is not a valid variable name in D. None of these
python. View Answer
08. What is the maximum length of an identifier in Answer : C
python? Explanation: Since there is no concept of private
A. 32 variables in Python language, majorly
B. 31 underscore is used to denote variables that cannot
C. 63 be accessed from outside the class.
D. None of the above 13. Which of the following will run without errors?
View Answer A. round(75.8)
Answer : D B. round()
Explanation: In python, the Identifier can be of any C. round(5352.898,9,5)
length. So, Option D is correct. D. round(6463.123,2,6)
09. Which of the following declarations is incorrect? View Answer
A. None Of the below Answer : A
B. _x = 2 Explanation: Execute help(round) in the shell to get
C. __x = 3 details of the parameters that are passed
D. __xyz__ = 5 into the round function.
View Answer 14. Which of the following is a valid variable?
Answer : A A. var@
Explanation: All declarations will execute successfully B. 32var
but at the expense of low readability. C. in
10. What is the result of round(0.5) – round(-0.5)? D. abc_x
A. 1.0 View Answer
B. 2.0 Answer : D
C. 0 Explanation: Variable name should not be a keyword,
D. None Of the above cannot begin with a digit, and should
Page 35 of 391 not contain any special symbol. Hence D is the
View Answer correct identifier or variable. So, Option D is
Answer : B correct.
Explanation: Python rounds off numbers away from 0 15. Is Python case sensitive when dealing with
when the number to be rounded off is identifiers?
exactly halfway through. round(0.5) is 1 and round (- A. Yes
0.5) is -1 So, 1-(-1)=2.0 B. No
11. In Python, a variable must be declared before it Page 36 of 391
is assigned a value: C. Machine dependent
A. True D. None of the above
B. False View Answer
View Answer Answer : A
Answer : B Explanation: Case is always significant.
Explanation: Variables need not be declared or 16. In which data type, indexing is not valid?
defined in advance in Python programming. A. List
To create a variable, you just assign it a value. B. String
12. Why does the name of local variables start with C. Dictionary
an underscore discouraged? D. None of the above
15

A. To identify the variable View Answer


Page

B. It confuses the interpreter Answer : C

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: Indexing is not valid in dictionary. View Answer
17. Select the correct example of complex datatype Answer : D
in Python Explanation: int() will convert the float value into
A. 3 + 2j integer value.
B. -100j 22. Which of the following is the example of
C. 5j typecasting?
D. All of the above are correct A. int(5)
View Answer B. str(5)
Answer : D C. str(xyz)
Explanation: All of the above are complex data types D. All of the above
in python View Answer
18. What is output of: 35 == 35.0 Answer : D
A. False Explanation: All
B. True 23. What is type casting in python?
C. 33 A. Declaration of data type
D. None of the above B. Destroy data type
View Answer C. Change data type property
Answer : B D. None of the above
Explanation: comparison operator (==) evaluates true View Answer
and false. And in python, we need not Answer : C
specify whether the number is int or float. Explanation: Type casting means changing the
19. l = [ 4, 8, 9, 2.6, 5 ] is a type of which data type in property of data types.
python? 24. In Python 3, the maximum value for an integer is
A. List 263 – 1:
B. Tuple A. True
C. Set B. Flase
D. None of these View Answer
View Answer Answer : B
Answer : A Explanation: In Python 2, there was an internal limit
Explanation: List in python is created by writing to how large an integer value could be.
values inside []. But that limit was removed in Python 3.
20. How can we create an empty list in python? This means there is no explicitly defined limit, but the
A. list=() amount of available address space
B. list.null forms a practical limit depending on the machine
C. null.list Python runs on.
Page 37 of 391 25. Which of the following is not a data type in
D. list=[] python?
View Answer A. List
Answer : D B. Tuple
Explanation: List in python is created by writing C. Dictionary
values inside []. So, for creating an empty Page 38 of 391
list just leave the list as []. D. Book
21. If x=3.123, then int(x) will give ? View Answer
A. 3.1 Answer : D
B. 0 Explanation: Book is not a data type
16

C. 1 26. Which of the following is a valid way to specify


Page

D. 3 the string literal foo'bar in Python:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


A. “foo’bar” 31. In order to store values in terms of key and
B. ‘foo”bar’ value we use that core data type in
C. ‘foo’bar’ python?
D. None of the above A. List
View Answer B. Class
Answer : A C. Dictionary
27. Correct way to declare a variable x of float data D. Tupple
type in python: View Answer
A. x = 2.5 Answer : C
B. float x = 2.5 Explanation: Dictionary is the collection of keys and
C. float(2.5) their value.
D. All of the above 32. How can we get 6 from the given list:
View Answer list=[9,5,6,3]
Answer : A A. list[-2]
Explanation: We just write the variable name and can B. list[-1]
assign any type of value and then the C. list[3]
type of variable will change according to the value D. None of the above
we assign in it. View Answer
28. All keywords in Python are in ____ Answer : A
A. None of the below Explanation: list[-2] will give the second last element
B. lower case of the list.
C. UPPER CASE Page 40 of 391
D. Capitalized Questions and Answers – Variable Names
View Answer 1. Is Python case sensitive when dealing with
Answer : A identifiers?
Explanation: True, False, and None are capitalized a) yes
while the others are in lower case. b) no
29. Which of the following is true for variable c) machine dependent
names in Python? d) none of the mentioned
A. Underscore and ampersand are the only two Answer: a
special characters allowed Explanation: Case is always significant.
B. All private members must have leading and trailing 2. What is the maximum possible length of an
underscores identifier?
C. Unlimited length a) 31 characters
D. none of the mentioned b) 63 characters
View Answer c) 79 characters
Answer : C d) none of the mentioned
Explanation: Variable names can be of any length. Answer: d
30. What does ~4 evaluate to? Explanation: Identifiers can be of any length.
A. -4 3. Which of the following is invalid?
B. -5 a) _a = 1
C. -3 b) __a = 1
D. +3 c) __str__ = 1
View Answer d) none of the mentioned
Page 39 of 391 Answer: d
17

Answer : B Explanation: All the statements will execute


Page

Explanation: ~x is equivalent to -(x+1). successfully but at the cost of reduced

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


readability. 9. Which of the following is an invalid statement?
4. Which of the following is an invalid variable? a) abc = 1,000,000
a) my_string_1 b) a b c = 1000 2000 3000
b) 1st_string c) a,b,c = 1000, 2000, 3000
c) foo d) a_b_c = 1,000,000
d) _ Answer: b
Answer: b Explanation: Spaces are not allowed in variable
Explanation: Variable names should not start with a names.
number. 10. Which of the following cannot be a variable?
5. Why are local variable names beginning with an a) __init__
underscore discouraged? b) in
a) they are used to indicate a private variables of a c) it
class d) on
b) they confuse the interpreter Page 42 of 391
c) they are used to indicate global variables Answer: b
d) they slow down execution Explanation: in is a keyword.
Page 41 of 391 Page 43 of 391
Answer: a Python Questions and Answers – Basic Operators
Explanation: As Python has no concept of private 1. Which is the correct operator for power(xy)?
variables, leading underscores are a) X^y
used to indicate variables that must not be accessed b) X**y
from outside the class. c) X^^y
6. Which of the following is not a keyword? d) None of the mentioned
a) eval Answer: b
b) assert Explanation: In python, power operator is x**y i.e.
c) nonlocal 2**3=8.
d) pass 2. Which one of these is floor division?
Answer: a a) /
Explanation: eval can be used as a variable. b) //
7. All keywords in Python are in _________ c) %
a) lower case d) None of the mentioned
b) UPPER CASE Answer: b
c) Capitalized Explanation: When both of the operands are integer
d) None of the mentioned then python chops out the
Answer: d fraction part and gives you the round off value, to
Explanation: True, False and None are capitalized get the accurate answer use floor
while the others are in lower case. division. This is floor division. For ex, 5/2 = 2.5 but
8. Which of the following is true for variable names both of the operands are integer so
in Python? answer of this expression in python is 2. To get the
a) unlimited length 2.5 answer, use floor division.
b) all private members must have leading and trailing 3. What is the order of precedence in python?
underscores i) Parentheses
c) underscore and ampersand are the only two ii) Exponential
special characters allowed iii) Multiplication
d) none of the mentioned iv) Division
18

Answer: a v) Addition
Page

Explanation: Variable names can be of any length. vi) Subtraction

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) i,ii,iii,iv,v,vi b) Multiplication, Division and Addition
b) ii,i,iii,iv,v,vi c) Multiplication, Division, Addition and Subtraction
c) ii,i,iv,iii,v,vi d) Addition and Multiplication
d) i,ii,iii,iv,vi,v Answer: a
Answer: a Explanation: “Addition and Subtraction” are at the
Explanation: For order of precedence, just same precedence level. Similarly,
remember this PEMDAS (similar to “Multiplication and Division” are at the same
BODMAS). precedence level. However,
4. What is the answer to this expression, 22 % 3 is? Multiplication and Division operators are at a higher
a) 7 precedence level than Addition
b) 1 and Subtraction operators.
c) 0 9. The expression Int(x) implies that the variable x is
d) 5 converted to integer.
Page 44 of 391 a) True
Answer: b b) False
Explanation: Modulus operator gives the Page 45 of 391
remainder. So, 22%3 gives the remainder, Answer: a
that is, 1. Explanation: None.
5. Mathematical operations can be performed on a 10. Which one of the following has the highest
string. precedence in the expression?
a) True a) Exponential
b) False b) Addition
Answer: b c) Multiplication
Explanation: You can’t perform mathematical d) Parentheses
operation on string even if the string is Answer: d
in the form: ‘1234…’. Explanation: Just remember: PEMDAS, that is,
6. Operators with the same precedence are Parenthesis, Exponentiation,
evaluated in which manner? Division, Multiplication, Addition, Subtraction. Note
a) Left to Right that the precedence order of
b) Right to Left Division and Multiplication is the same. Likewise,
c) Can’t say the order of Addition and
d) None of the mentioned Subtraction is also the same.
Answer: a Page 46 of 391
Explanation: None. Python Questions and Answers – Core Data types
7. What is the output of this expression, 3*1**3? 1. Which of these in not a core data type?
a) 27 a) Lists
b) 9 b) Dictionary
c) 3 c) Tuples
d) 1 d) Class
Answer: c Answer: d
Explanation: First this expression will solve 1**3 Explanation: Class is a user defined data type.
because exponential has higher 2. Given a function that does not return any value,
precedence than multiplication, so 1**3 = 1 and 3*1 What value is thrown by default when
= 3. Final answer is 3. executed in shell.
8. Which one of the following has the same a) int
19

precedence level? b) bool


Page

a) Addition and Subtraction c) void

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) None Explanation: // is integer operation in python 3.0
Answer: d and int(..) is a type cast operator.
Explanation: Python shell throws a NoneType object 7. What error occurs when you execute the following
back. Python code snippet?
3. What will be the output of the following Python apple = mango
code? a) SyntaxError
1. >>>str="hello" b) NameError
2. >>>str[:2] c) ValueError
3. >>> d) TypeError
a) he Answer: b
b) lo Explanation: Mango is not defined hence name
c) olleh error.
d) hello 8. What will be the output of the following Python
Answer: a code snippet?
Explanation: We are printing only the 1st two bytes 1. def example(a):
of string and hence the answer is 2. a = a + '2'
“he”. 3. a = a*2
4. Which of the following will run without errors? 4. return a
a) round(45.8) 5. >>>example("hello")
b) round(6352.898,2,5) a) indentation Error
c) round() b) cannot perform mathematical operation on strings
d) round(7463.123,2,1) c) hello2
Answer: a d) hello2hello2
Explanation: Execute help(round) in the shell to get Answer: a
details of the parameters that are Explanation: Python codes have to be indented
passed into the round function. properly.
5. What is the return type of function id? 9. What data type is the object below?
a) int L = [1, 23, 'hello', 1]
b) float a) list
Page 47 of 391 b) dictionary
c) bool Page 48 of 391
d) dict c) array
Answer: a d) tuple
Explanation: Execute help(id) to find out details in Answer: a
python shell.id returns a integer Explanation: List data type can store any values
value that is unique. within it.
6. In python we do not specify types, it is directly 10. In order to store values in terms of key and value
interpreted by the compiler, so consider we use what core data type.
the following operation to be performed. a) list
1. >>>x = 13 ? 2 b) tuple
objective is to make sure x has a integer value, select c) class
all that apply (python 3.xx) d) dictionary
a) x = 13 // 2 Answer: d
b) x = int(13 / 2) Explanation: Dictionary stores values in terms of
c) x = 13 % 2 keys and values.
20

d) All of the mentioned 11. Which of the following results in a SyntaxError?


Page

Answer: d a) ‘”Once upon a time…”, she said.’

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) “He said, ‘Yes!'” c) float
c) ‘3\’ d) None
d) ”’That’s okay”’ Answer: a
Answer: c Explanation: Execute help(math.trunc) to get
Explanation: Carefully look at the colons. details.
12. The following is displayed by a print function call. Page 50 of 391
Select all of the function calls that Python Questions and Answers – Numeric Types
result in this output. 1. What is the output of print 0.1 + 0.2 == 0.3?
1. tom a) True
2. dick b) False
3. harry c) Machine dependent
a) d) Error
print('''tom Answer: b
\ndick Explanation: Neither of 0.1, 0.2 and 0.3 can be
\nharry''') represented accurately in binary. The
b) print(”’tomdickharry”’) round off errors from 0.1 and 0.2 accumulate and
c) print(‘tom\ndick\nharry’) hence there is a difference of
d) 5.5511e-17 between (0.1 + 0.2) and 0.3.
print('tom 2. Which of the following is not a complex number?
dick a) k = 2 + 3j
harry') b) k = complex(2, 3)
Answer: c c) k = 2 + 3l
Explanation: The \n adds a new line. d) k = 2 + 3J
13. What is the average value of the following Python Answer: c
code snippet? Explanation: l (or L) stands for long.
1. >>>grade1 = 80 3. What is the type of inf?
2. >>>grade2 = 90 a) Boolean
3. >>>average = (grade1 + grade2) / 2 b) Integer
Page 49 of 391 c) Float
a) 85.0 d) Complex
b) 85.1 Answer: c
c) 95.0 Explanation: Infinity is a special case of floating
d) 95.1 point numbers. It can be obtained by
Answer: a float(‘inf’).
Explanation: Cause a decimal value of 0 to appear 4. What does ~4 evaluate to?
as output. a) -5
14. Select all options that print. b) -4
hello-how-are-you c) -3
a) print(‘hello’, ‘how’, ‘are’, ‘you’) d) +3
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4) Answer: a
c) print(‘hello-‘ + ‘how-are-you’) Explanation: ~x is equivalent to -(x+1).
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’) 5. What does ~~~~~~5 evaluate to?
Answer: c a) +5
Explanation: Execute in the shell. b) -11
15. What is the return value of trunc()? c) +11
21

a) int d) -5
Page

b) bool Page 51 of 391

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: a Page 52 of 391
Explanation: ~x is equivalent to -(x+1). 1.0
6. Which of the following is incorrect? >>> round(-0.5)
a) x = 0b101 -1.0
b) x = 0x4f5 >>>
c) x = 19023 In the above output, you can see that the round()
d) x = 03964 functions on 0.5 and -0.5 are moving
Answer: d away from 0 and hence “round(0.5) – (round(-0.5))
Explanation: Numbers starting with a 0 are octal = 1 – (-1) = 2”
numbers but 9 isn’t allowed in octal Here’s the runtime output for Python version 3.6
numbers. interpreter.
7. What is the result of cmp(3, 1)? $ python3
a) 1 Python 3.6.8 (default, Oct 7 2019, 12:59:55)
b) 0 >>> round(0.5)
c) True 0
d) False >>> round(-0.5)
Answer: a 0
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y >>> round(2.5)
and -1 if x < y. 2
8. Which of the following is incorrect? >>> round(3.5)
a) float(‘inf’) 4
b) float(‘nan’) >>>
c) float(’56’+’78’) In the above output, you can see that the round()
d) float(’12+34′) functions on 0.5 and -0.5 are moving
Answer: d towards 0 and hence “round(0.5) – (round(-0.5)) = 0
Explanation: ‘+’ cannot be converted to a float. – 0 = 0“. Also note that the
9. What is the result of round(0.5) – round(-0.5)? round(2.5) is 2 (which is an even number) whereas
a) 1.0 round(3.5) is 4 (which is an even
b) 2.0 number).
c) 0.0 10. What does 3 ^ 4 evaluate to?
d) Value depends on Python version a) 81
Answer: d b) 12
Explanation: The behavior of the round() function is c) 0.75
different in Python 2 and Python d) 7
3. In Python 2, it rounds off numbers away from 0 Answer: d
when the number to be rounded off Explanation: ^ is the Binary XOR operator.
is exactly halfway through. round(0.5) is 1 and Page 53 of 391
round(-0.5) is -1 whereas in Python 3, Python Questions and Answers – Operator
it rounds off numbers towards nearest even Precedence and Associativity – 1
number when the number to be rounded 1. The value of the expressions 4/(3*(2-1)) and
off is exactly halfway through. See the below 4/3*(2-1) is the same.
output. a) True
Here’s the runtime output for Python version 2.7 b) False
interpreter. Answer: a
$ python Explanation: Although the presence of parenthesis
22

Python 2.7.17 (default, Nov 7 2019, 10:07:09) does affect the order of
Page

>>> round(0.5) precedence, in the case shown above, it is not

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


making a difference. The result of both example of explicit conversion. It is
of these expressions is 1.333333333. Hence the evaluated as int(43.55+1) = int(44.55) = 44. Hence
statement is true. the result of this expression is 44.
2. What will be the value of the following Python 6. What is the value of the following expression?
expression? 2+4.00, 2**4.0
4+3%5 a) (6.0, 16.0)
a) 4 b) (6.00, 16.00)
b) 7 c) (6, 16)
c) 2 d) (6.00, 16.0)
d) 0 Answer: a
Answer: b Explanation: The result of the expression shown
Explanation: The order of precedence is: %, +. above is (6.0, 16.0). This is because
Hence the expression above, on the result is automatically rounded off to one
simplification results in 4 + 3 = 7. Hence the result is decimal place.
7. 7. Which of the following is the truncation division
3. Evaluate the expression given below if A = 16 and operator?
B = 15. a) /
A % B // A b) %
a) 0.0 c) //
b) 0 d) |
c) 1.0 Answer: c
d) 1 Explanation: // is the operator for truncation
Answer: b division. It is called so because it returns
Explanation: The above expression is evaluated as: only the integer part of the quotient, truncating the
16%15//16, which is equal to 1//16, decimal part. For example: 20//3 =
which results in 0. 6.
4. Which of the following operators has its 8. What are the values of the following Python
associativity from right to left? expressions?
a) + 2**(3**2)
b) // (2**3)**2
c) % 2**3**2
d) ** a) 64, 512, 64
Answer: d b) 64, 64, 64
Explanation: All of the operators shown above have c) 512, 512, 512
associativity from left to right, d) 512, 64, 512
except exponentiation operator (**) which has its Answer: d
associativity from right to left. Explanation: Expression 1 is evaluated as: 2**9,
5. What will be the value of x in the following Python which is equal to 512. Expression 2 is
expression? evaluated as 8**2, which is equal to 64. The last
x = int(43.55+2/2) expression is evaluated as 2**(3**2).
a) 43 This is because the associativity of ** operator is
b) 44 from right to left. Hence the result of
Page 54 of 391 the third expression is 512.
c) 22 9. What is the value of the following expression?
d) 23 8/4/2, 8/(4/2)
23

Answer: b Page 55 of 391


Page

Explanation: The expression shown above is an a) (1.0, 4.0)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) (1.0, 1.0) b) 7.9 * 6.3
c) (4.0. 1.0) c) 1.7 % 2
d) (4.0, 4.0) d) 3.4 + 4.6
Answer: a Answer: c
Explanation: The above expressions are evaluated Explanation: Coercion is the implicit (automatic)
as: 2/2, 8/2, which is equal to (1.0, conversion of operands to a common
4.0). type. Coercion is automatically performed on
10. What is the value of the following expression? mixed-type expressions. The expression
float(22//3+3/3) 1.7 % 2 is evaluated as 1.7 % 2.0 (that is, automatic
a) 8 conversion of int to float).
b) 8.0 4. What will be the output of the following Python
c) 8.3 expression?
d) 8.33 24//6%3, 24//4//2
Answer: b a) (1,3)
Explanation: The expression shown above is b) (0,3)
evaluated as: float( 7+1) = float(8) = 8.0. c) (1,0)
Hence the result of this expression is 8.0. d) (3,1)
Page 56 of 391 Answer: a
Python Questions and Answers – Precedence and Explanation: The expressions are evaluated as: 4%3
Associativity – 2 and 6//2 respectively. This results
1. What will be the output of the following Python in the answer (1,3). This is because the associativity
expression? of both of the expressions shown
print(4.00/(2.0+2.0)) above is left to right.
a) Error Page 57 of 391
b) 1.0 5. Which among the following list of operators has
c) 1.00 the highest precedence?
d) 1 +, -, **, %, /, <<, >>, |
Answer: b a) <<, >>
Explanation: The result of the expression shown b) **
above is 1.0 because print rounds off c) |
digits. d) %
2. What will be the value of X in the following Python Answer: b
expression? Explanation: The highest precedence is that of the
X = 2+9*((3*12)-8)/10 exponentiation operator, that is of
a) 30.0 **.
b) 30.8 6. What will be the value of the following Python
c) 28.4 expression?
d) 27.2 float(4+int(2.39)%2)
Answer: d a) 5.0
Explanation: The expression shown above is b) 5
evaluated as: 2+9*(36-8)/10, which c) 4.0
simplifies to give 2+9*(2.8), which is equal to 2+25.2 d) 4
= 27.2. Hence the result of this Answer: c
expression is 27.2. Explanation: The above expression is an example of
3. Which of the following expressions involves explicit conversion. It is evaluated
24

coercion when evaluated in Python? as: float(4+int(2.39)%2) = float(4+2%2) = float(4+0) =


Page

a) 4.7 – 1.5 4.0. Hence the result of this

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


expression is 4.0. evaluated as 2**(2**3). This is because the
7. Which of the following expressions is an example associativity of exponentiation operator
of type conversion? (**) is from right to left and not from left to right.
a) 4.0 + float(3) Page 59 of 391
b) 5.3 + 6.3 Python Questions and Answers – Bitwise – 1
c) 5.0 + 3 1. What will be the output of the following Python
d) 3 + 7 code snippet if x=1?
Answer: a x<<2
Explanation: Type conversion is nothing but explicit a) 8
conversion of operands to a b) 1
specific type. Options 5.3 + 6.3 and 5.0 + 3 are c) 2
examples of implicit conversion d) 4
whereas option 4.0 + float(3) is an example of Answer: d
explicit conversion or type conversion. Explanation: The binary form of 1 is 0001. The
8. Which of the following expressions results in an expression x<<2 implies we are
error? performing bitwise left shift on x. This shift yields
a) float(‘10’) the value: 0100, which is the binary
b) int(‘10’) form of the number 4.
c) float(’10.8’) 2. What will be the output of the following Python
d) int(’10.8’) expression?
Answer: d bin(29)
Explanation: All of the above examples show a) ‘0b10111’
explicit conversion. However the b) ‘0b11101’
expression int(’10.8’) results in an error. c) ‘0b11111’
9. What will be the value of the following Python d) ‘0b11011’
expression? Answer: b
4+2**5//10 Explanation: The binary form of the number 29 is
Page 58 of 391 11101. Hence the output of this
a) 3 expression is ‘0b11101’.
b) 7 3. What will be the value of x in the following Python
c) 77 expression, if the result of that
d) 0 expression is 2?
Answer: b x>>2
Explanation: The order of precedence is: **, //, +. a) 8
The expression 4+2**5//10 is b) 4
evaluated as 4+32//10, which is equal to 4+3 = 7. c) 2
Hence the result of the expression d) 1
shown above is 7. Answer: a
10. The expression 2**2**3 is evaluates as: Explanation: When the value of x is equal to 8
(2**2)**3. (1000), then x>>2 (bitwise right shift)
a) True yields the value 0010, which is equal to 2. Hence the
b) False value of x is 8.
Answer: b 4. What will be the output of the following Python
Explanation: The value of the expression (2**2)**3 expression?
= 4**3 = 64. When the expression int(1011)?
25

2**2**3 is evaluated in python, we get the result as a) 1011


Page

256, because this expression is b) 11

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) 13 c) |
d) 1101 d) !
Answer: a Answer: b
Explanation: The result of the expression shown will Explanation: The ^ operator represent bitwise XOR
be 1011. This is because we have operation. &: bitwise AND, | :
not specified the base in this expression. Hence it bitwise OR and ! represents bitwise NOT.
automatically takes the base as 10. 9. What is the value of the following Python
Page 60 of 391 expression?
5. To find the decimal value of 1111, that is 15, we bin(0x8)
can use the function: a) ‘0bx1000’
a) int(1111,10) b) 8
b) int(‘1111’,10) Page 61 of 391
c) int(1111,2) c) 1000
d) int(‘1111’,2) d) ‘0b1000’
Answer: d Answer: d
Explanation: The expression int(‘1111’,2) gives the Explanation: The prefix 0x specifies that the value is
result 15. The expression hexadecimal in nature. When we
int(‘1111’, 10) will give the result 1111. convert this hexadecimal value to binary form, we
6. What will be the output of the following Python get the result as: ‘0b1000’.
expression if x=15 and y=12? 10. What will be the output of the following Python
x&y expression?
a) b1101 0x35 | 0x75
b) 0b1101 a) 115
c) 12 b) 116
d) 1101 c) 117
Answer: c d) 118
Explanation: The symbol ‘&’ represents bitwise Answer: c
AND. This gives 1 if both the bits are Explanation: The binary value of 0x35 is 110101 and
equal to 1, else it gives 0. The binary form of 15 is that of 0x75 is 1110101. On ORing these two values
1111 and that of 12 is 1100. Hence we get the output as: 1110101, which is equal to
on performing the bitwise AND operation, we get 117. Hence the
1100, which is equal to 12. result of the above expression is 117.
7. Which of the following expressions results in an Page 62 of 391
error? Python Questions and Answers – Bitwise – 2
a) int(1011) 1. It is not possible for the two’s complement value
b) int(‘1011’,23) to be equal to the original value in any
c) int(1011,2) case.
d) int(‘1011’) a) True
Answer: c b) False
Explanation: The expression int(1011,2) results in an Answer: b
error. Had we written this Explanation: In most cases the value of two’s
expression as int(‘1011’,2), then there would not be complement is different from the
an error. original value. However, there are cases in which
8. Which of the following represents the bitwise XOR the two’s complement value may be
operator? equal to the original value. For example, the two’s
26

a) & complement of 10000000 is also


Page

b) ^ equal to 10000000. Hence the statement is false.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


2. The one’s complement of 110010101 is: 6. What will be the value of the following Python
a) 001101010 expression?
b) 110010101 bin(10-2)+bin(12^4)
c) 001101011 a) 0b10000
d) 110010100 b) 0b10001000
Answer: a c) 0b1000b1000
Explanation: The one’s complement of a value is d) 0b10000b1000
obtained by simply changing all the Answer: d
1’s to 0’s and all the 0’s to 1’s. Hence the one’s Explanation: The output of bin(10-2) = 0b1000 and
complement of 110010101 is that of bin(12^4) is ob1000. Hence
001101010. the output of the above expression is:
3. Bitwise _________ gives 1 if either of the bits is 1 0b10000b1000.
and 0 when both of the bits are 1. 7. Which of the following expressions can be used to
a) OR multiply a given number ‘a’ by 4?
b) AND a) a<<2
c) XOR b) a<<4
d) NOT c) a>>2
Answer: c d) a>>4
Explanation: Bitwise XOR gives 1 if either of the bits Answer: a
is 1 and 0 when both of the bits Explanation: Let us consider an example wherein
are 1. a=2. The binary form of 2 is 0010.
4. What will be the output of the following Python When we left shift this value by 2, we get 1000, the
expression? value of which is 8. Hence if we
4^12 want to multiply a given number ‘a’ by 4, we can
a) 2 use the expression: a<<2.
b) 4 8. What will be the output of the following Python
c) 8 code if a=10 and b =20?
d) 12 a=10
Answer: c b=20
Explanation: ^ is the XOR operator. The binary form a=a^b
of 4 is 0100 and that of 12 is b=a^b
1100. Therefore, 0100^1100 is 1000, which is equal a=a^b
to 8. print(a,b)
5. Any odd number on being AND-ed with ________ a) 10 20
always gives 1. Hint: Any even b) 10 10
number on being AND-ed with this value always c) 20 10
gives 0. d) 20 20
Page 63 of 391 Answer: c
a) 10 Explanation: The code shown above is used to swap
b) 2 the contents of two memory
c) 1 locations using bitwise X0R operator. Hence the
d) 0 output of the code shown above is: 20
Answer: c 10.
Explanation: Any odd number on being AND-ed Page 64 of 391
with 1 always gives 1. Any even 9. What is the two’s complement of -44?
27

number on being AND-ed with this value always a) 1011011


Page

gives 0. b) 11010100

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) 11101011 code snippet?
d) 10110011 ['hello', 'morning'][bool('')]
Answer: b a) error
Explanation: The binary form of -44 is 00101100. b) no output
The one’s complement of this value c) hello
is 11010011. On adding one to this we get: d) morning
11010100 (two’s complement). Answer: c
10. What will be the output of the following Python Explanation: The line of code shown above can be
expression? simplified to state that ‘hello’
~100? should be printed if the argument passed to the
a) 101 Boolean function amounts to zero, else
b) -101 ‘morning’ will be printed.
c) 100 3. What will be the output of the following Python
d) -100 code snippet?
Answer: b not(3>4)
Explanation: Suppose we have an expression ~A. not(1&1)
This is evaluated as: -A – 1. a)
Therefore, the expression ~100 is evaluated as -100 True
– 1, which is equal to -101. True
Page 65 of 391 b)
Python Questions and Answers – Boolean True
1. What will be the output of the following Python False
code snippet? c)
bool(‘False’) False
bool() Page 66 of 391
a) True
True d)
True False
b) False
False Answer: b
True Explanation: The function not returns true if the
c) argument amounts to false, and false
False if the argument amounts to true. Hence the first
False function returns false, and the second
d) function returns false.
True 4. What will be the output of the following Python
False code?
Answer: d ['f', 't'][bool('spam')]
Explanation: The Boolean function returns true if a) t
the argument passed to the bool b) f
function does not amount to zero. In the first c) No output
example, the string ‘False’ is passed to d) Error
the function bool. This does not amount to zero and Answer: a
hence the output is true. In the Explanation: The line of code can be translated to
second function, an empty list is passed to the state that ‘f’ is printed if the
28

function bool. Hence the output is false. argument passed to the Boolean function amount
Page

2. What will be the output of the following Python to zero. Else ‘t’ is printed. The

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


argument given to the Boolean function in the x=Truth()
above case is ‘spam’, which does not bool(x)
amount to zero. Hence the output is t. a) pass
5. What will be the output of the following Python b) true
code? c) false
l=[1, 0, 2, 0, 'hello', '', []] d) error
list(filter(bool, l)) Answer: b
a) Error Explanation: If the truth method is not defined, the
b) [1, 0, 2, 0, ‘hello’, ”, []] object is considered true. Hence
c) [1, 0, 2, ‘hello’, ”, []] the output of the code shown above is true.
d) [1, 2, ‘hello’] 8. What will be the output of the following Python
Answer: d code?
Explanation: The code shown above returns a new if (9 < 0) and (0 < -9):
list containing only those elements print("hello")
of the list l which do not amount to zero. Hence the elif (9 > 0) or False:
output is: [1, 2, ‘hello’]. print("good")
6. What will be the output of the following Python else:
code if the system date is 21st June, print("bad")
2017 (Wednesday)? a) error
[] or {} b) hello
{} or [] c) good
a) d) bad
[] Answer: c
{} Explanation: The code shown above prints the
b) appropriate option depending on the
[] conditions given. The condition which matches is
[] (9>0), and hence the output is: good.
c) 9. Which of the following Boolean expressions is not
{} logically equivalent to the other
Page 67 of 391 three?
[] a) not(-6<0 or-6>10)
d) b) -6>=0 and -6<=10
{} c) not(-6<10 or-6==10)
{} Page 68 of 391
Answer: c d) not(-6>10 or-6==10)
Explanation: The code shown above shows two Answer: d
functions. In both the cases the right Explanation: The expression not(-6<0 or -6>10)
operand is returned. This is because each function is returns the output False.
evaluated from left to right. The expression -6>=0 and -6<=10 returns the output
Since the left operand is false, it is assumed that the False.
right operand must be true and The expression not(-6<10 or -6==10) returns the
hence the right operand is returned in each of the output False.
above case. The expression not(-6>10 or -6==10) returns the
7. What will be the output of the following Python output True.
code? 10. What will be the output of the following Python
29

class Truth: code snippet?


Page

pass not(10<20) and not(10>30)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) True d) error
b) False Answer: c
c) Error Explanation: The expression shown above results in
d) No output the output 456.
Answer: b 4. What will be the output of the following Python
Explanation: The expression not(10<20) returns expression if X=345?
false. The expression not(10>30) print(“%06d”%X)
returns true. The and operation between false and a) 345000
true returns false. Hence the b) 000345
output is false. c) 000000345
Page 69 of 391 d) 345000000
Python Question and Answers – Formatting – 1 Answer: b
1. What will be the output of the following Python Explanation: The above expression returns the
code snippet? output 000345. It adds the required
X=”hi” Page 70 of 391
print(“05d”%X) number of zeroes before the given number in order
a) 00000hi to make the number of digits 6 (as
b) 000hi specified in this case).
c) hi000 5. Which of the following formatting options can be
d) error used in order to add ‘n’ blank spaces
Answer: d after a given string ‘S’?
Explanation: The code snippet shown above results a) print(“-ns”%S)
in an error because the above b) print(“-ns”%S)
formatting option works only if ‘X’ is a number. c) print(“%ns”%S)
Since in the above case ‘X’ is a d) print(“%-ns”%S)
string, an error is thrown. Answer: d
2. What will be the output of the following Python Explanation: In order to add ‘n’ blank spaces after a
code snippet? given string ‘S’, we use the
X=”san-foundry” formatting option:(“%-ns”%S).
print(“%56s”,X) 6. What will be the output of the following Python
a) 56 blank spaces before san-foundry expression if X = -122?
b) 56 blank spaces before san and foundry print("-%06d"%x)
c) 56 blank spaces after san-foundry a) -000122
d) no change b) 000122
Answer: a c) –00122
Explanation: The formatting option print(“%Ns”,X) d) -00122
helps us add ‘N’ number of Answer: c
spaces before a given string ‘X’. Hence the output Explanation: The given number is -122. Here the
for the code snippet shown above total number of digits (including the
will be 56 blank spaces before the string “san- negative sign) should be 6 according to the
foundry”. expression. In addition to this, there is a
3. What will be the output of the following Python negative sign in the given expression. Hence the
expression if x=456? output will be – -00122.
print("%-06d"%x) 7. What will be the output of the following Python
a) 000456 expression if the value of x is 34?
30

b) 456000 print(“%f”%x)
Page

c) 456 a) 34.00

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) 34.0000 is incorrect.
c) 34.000000 Page 72 of 391
d) 34.00000000 Python Question and Answers – Formatting – 2
Answer: c 1. What will be the output of the following Python
Explanation: The expression shown above normally code snippet?
returns the value with 6 decimal '%d %s %g you' %(1, 'hello', 4.0)
points if it is not specified with any number. Hence a) Error
the output of this expression will b) 1 hello you 4.0
be: 34.000000 (6 decimal points). c) 1 hello 4 you
8. What will be the output of the following Python d) 1 4 hello you
expression if x=56.236? Answer: c
print("%.2f"%x) Explanation: In the snippet of code shown above,
a) 56.00 three values are inserted into the
b) 56.24 target string. When we insert more than one value,
c) 56.23 we should group the values on the
d) 0056.236 right in a tuple. The % formatting expression
Answer: b operator expects either a single item or
Explanation: The expression shown above rounds a tuple of one or more items on its right side.
off the given number to the number 2. The output of which of the codes shown below will
Page 71 of 391 be: “There are 4 blue birds.”?
of decimal places specified. Since the expression a) ‘There are %g %d birds.’ %4 %blue
given specifies rounding off to two b) ‘There are %d %s birds.’ %(4, blue)
decimal places, the output of this expression will be c) ‘There are %s %d birds.’ %[4, blue]
56.24. Had the value been d) ‘There are %d %s birds.’ 4, blue
x=56.234 (last digit being any number less than 5), Answer: b
the output would have been 56.23. Explanation: The code ‘There are %d %s birds.’ %(4,
9. What will be the output of the following Python blue) results in the output:
expression if x=22.19? There are 4 blue birds. When we insert more than
print("%5.2f"%x) one value, we should group the
a) 22.1900 values on the right in a tuple.
b) 22.00000 3. What will be the output of the python code shown
c) 22.19 below for various styles of format
d) 22.20 specifiers?
Answer: c x=1234
Explanation: The output of the expression above res='integers:...%d...%-6d...%06d' %(x, x, x)
will be 22.19. This expression res
specifies that the total number of digits (including a) ‘integers:…1234…1234 …001234’
the decimal point) should be 5, b) ‘integers…1234…1234…123400’
rounded off to two decimal places. c) ‘integers:… 1234…1234…001234’
10. The expression shown below results in an error. d) ‘integers:…1234…1234…001234’
print("-%5d0",989) Answer: a
a) True Explanation: The code shown above prints 1234 for
b) False the format specified %d, ‘1234 ’
Answer: b for the format specifier %-6d (minus ‘-‘ sign signifies
Explanation: The expression shown above does not left justification), and 001234
31

result in an error. The output of for the format specifier %06d. Hence the output of
Page

this expression is -%5d0 989. Hence this statement this code is:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


‘integers:…1234…1234 …001234’ 7. What will be the output of the following Python
4. What will be the output of the following Python code snippet?
code snippet? '%(qty)d more %(food)s' %{'qty':1, 'food': 'spam'}
x=3.3456789 a) Error
'%f | %e | %g' %(x, x, x) b) No output
a) Error c) ‘1 more foods’
b) ‘3.3456789 | 3.3456789+00 | 3.345678’ d) ‘1 more spam’
Page 73 of 391 Answer: d
c) ‘3.345678 | 3.345678e+0 | 3.345678’ Explanation: String formatting also allows
d) ‘3.345679 | 3.345679e+00 | 3.34568’ conversion targets on the left to refer to the
Answer: d keys in a dictionary coded on the right and fetch the
Explanation: The %f %e and %g format specifiers corresponding values. In the code
represent floating point numbers shown above, (qty) and (food) in the format string
in different ways. %e and %E are the same, except on the left refers to keys in the
that the exponent is in lowercase. Page 74 of 391
%g chooses the format by number content. Hence dictionary literal on the right and fetch their
the output of this code is: ‘3.345679 assorted values. Hence the output of the
| 3.345679e+00 | 3.34568’. code shown above is: 1 more spam.
5. What will be the output of the following Python 8. What will be the output of the following Python
code snippet? code snippet?
x=3.3456789 a='hello'
'%-6.2f | %05.2f | %+06.1f' %(x, x, x) q=10
a) ‘3.35 | 03.35 | +003.3’ vars()
b) ‘3.3456789 | 03.3456789 | +03.3456789’ a) {‘a’ : ‘hello’, ‘q’ : 10, ……..plus built-in names set by
c) Error Python….}
d) ‘3.34 | 03.34 | 03.34+’ b) {……Built in names set by Python……}
Answer: a c) {‘a’ : ‘hello’, ‘q’ : 10}
Explanation: The code shown above rounds the d) Error
floating point value to two decimal Answer: a
places. In this code, a variety of addition formatting Explanation: The built in function vars() returns a
features such as zero padding, dictionary containing all the
total field width etc. Hence the output of this code variables that exist in the place. Hence the output
is: ‘3.35 | 03.35 | +003.3’. of the code shown above is: {‘a’ :
6. What will be the output of the following Python ‘hello’, ‘q’ : 10, ……..plus built-in names set by
code snippet? Python….}
x=3.3456789 9. What will be the output of the following Python
'%s' %x, str(x) code?
a) Error s='{0}, {1}, and {2}'
b) (‘3.3456789’, ‘3.3456789’) s.format('hello', 'good', 'morning')
c) (3.3456789, 3.3456789) a) ‘hello good and morning’
d) (‘3.3456789’, 3.3456789) b) ‘hello, good, morning’
Answer: b c) ‘hello, good, and morning’
Explanation: We can simply convert strings with a d) Error
%s format expression or the str Answer: c
built-in function. Both of these methods have been Explanation: Within the subject string, curly braces
32

shown in this code. Hence the designate substitution targets and


Page

output is: ) (‘3.3456789’, ‘3.3456789’) arguments to be inserted either by position or

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


keyword. Hence the output of the code '{0:.2f}'.format(1.234)
shown above:’hello, good,and morning’. a) ‘1’
10. What will be the output of the following Python b) ‘1.234’
code? c) ‘1.23’
s='%s, %s & %s' d) ‘1.2’
s%('mumbai', 'kolkata', 'delhi') Answer: c
a) mumbai kolkata & delhi Explanation: The code shown above displays the
b) Error string method to round off a given
c) No output decimal number to two decimal places. Hence the
d) ‘mumbai, kolkata & delhi’ output of the code is: ‘1.23’.
Answer: d 14. What will be the output of the following Python
Explanation: In the code shown above, the format code?
specifier %s is replaced by the '%x %d' %(255, 255)
designated substitution. Hence the output of the a) ‘ff, 255’
code shown above is: ‘mumbai, b) ‘255, 255’
kolkata & delhi’. c) ‘15f, 15f’
11. What will be the output of the following Python d) Error
code? Answer: a
t = '%(a)s, %(b)s, %(c)s' Explanation: The code shown above converts the
t % dict(a='hello', b='world', c='universe') given arguments to hexadecimal and
Page 75 of 391 decimal values and prints the result. This is done
a) ‘hello, world, universe’ using the format specifiers %x and
b) ‘hellos, worlds, universes’ %d respectively. Hence the output of the code
c) Error shown above is: ‘ff, 255’.
d) hellos, world, universe 15. The output of the two codes shown below is the
Answer: a same.
Explanation: Within the subject string, curly braces i. '{0:.2f}'.format(1/3.0)
represent substitution targets Page 76 of 391
and arguments to be inserted. Hence the output of ii. '%.2f'%(1/3.0)
the code shown above: a) True
‘hello, world, universe’. b) False
12. What will be the output of the following Python Answer: a
code? Explanation: The two codes shown above represent
'{a}, {0}, {abc}'.format(10, a=2.5, abc=[1, 2]) the same operation but in
a) Error different formats. The output of both of these
b) ‘2.5, 10, [1, 2]’ functions is: ‘0.33’. Hence the statement
c) 2.5, 10, 1, 2 is true.
d) ’10, 2.5, [1, 2]’ Page 77 of 391
Answer: b Python Questions and Answers – Advanced
Explanation: Since we have specified that the order Formatting Tools
of the output be: {a}, {0}, {abc}, 1. What will be the output of the following Python
hence the value of associated with {a} is printed code?
first followed by that of {0} and {abc}. l=list('HELLO')
Hence the output of the code shown above is: ‘2.5, 'first={0[0]}, third={0[2]}'.format(l)
10, [1, 2]’. a) ‘first=H, third=L’
33

13. What will be the output of the following Python b) ‘first=0, third=2’
Page

code? c) Error

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) ‘first=0, third=L’ 0xff. The value ‘FF’ into integer. Hence the output of
Answer: a the code shown is: (‘0xff’, 255,
Explanation: In the code shown above, the value for 255).
first is substituted by l[0], that is 5. The output of the two codes shown below is the
H and the value for third is substituted by l[2], that same.
is L. Hence the output of the code i. bin((2**16)-1)
shown above is: ‘first=H, third=L’. The list l= [‘H’, ‘E’, ii. '{}'.format(bin((2**16)-1))
‘L’, ‘L’, ‘O’]. a) True
2. What will be the output of the following Python b) False
code? Answer: a
l=list('HELLO') Explanation: The output of both of the codes shown
p=l[0], l[-1], l[1:3] above is ‘0b1111111111111111’.
'a={0}, b={1}, c={2}'.format(*p) Hence the statement is true.
a) Error 6. What will be the output of the following Python
b) “a=’H’, b=’O’, c=(E, L)” code?
c) “a=H, b=O, c=[‘E’, ‘L’]” '{a}{b}{a}'.format(a='hello', b='world')
d) Junk value a) ‘hello world’
Answer: c b) ‘hello’ ‘world’ ‘hello’
Explanation: In the code shown above, the value for c) ‘helloworldhello’
a is substituted by l[0], that is d) ‘hello’ ‘hello’ ‘world’
‘H’, the value of b is substituted by l[-1], that is ‘O’ Answer: c
and the value for c is substituted Explanation: The code shown above prints the
by l[1:3]. Here the use of *p is to unpack a tuple values substituted for a, b, a, in the
items into individual function same order. This operation is performed using the
arguments. format function. Hence the output
3. The formatting method {1:<10} represents the of the code is: ‘helloworldhello’.
___________ positional argument, 7. What will be the output of the following Python
_________ justified in a 10 character wide field. code?
a) first, right D=dict(p='san', q='foundry')
b) second, left '{p}{q}'.format(**D)
c) first, left a) Error
d) second, right b) sanfoundry
Answer: b c) san foundry
Explanation: The formatting method {1:<10} d) {‘san’, ‘foundry’}
represents the second positional Answer: b
argument, left justified in a 10 character wide field. Explanation: The code shown above prints the
4. What will be the output of the following Python values substituted for p and q in the
code? same order. Note that there is no blank space
hex(255), int('FF', 16), 0xFF between p and q. Hence the output is:
a) [0xFF, 255, 16, 255] sanfoundry.
b) (‘0xff’, 155, 16, 255) 8. What will be the output of the following Python
c) Error code?
Page 78 of 391 'The {} side {1} {2}'.format('bright', 'of', 'life')
d) (‘0xff’, 255, 255) a) Error
Answer: d b) ‘The bright side of life’
34

Explanation: The code shown above converts the c) ‘The {bright} side {of} {life}’
Page

value 255 into hexadecimal, that is, Page 79 of 391

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) No output tuple, a tuple to be formatted must be provided as
Answer: a a tested tuple. Hence the output of
Explanation: The code shown above results in an the code is: >>> ‘%s’ %((1.23,),).
error. This is because we have 12. What will be the output of the following two
switched from automatic field numbering to manual codes?
field numbering, that is, from {} i. '{0}'.format(4.56)
to {1}. Hence this code results in an error. ii. '{0}'.format([4.56,])
9. What will be the output of the following Python Page 80 of 391
code? a) ‘4.56’, ‘4.56,’
'{0:f}, {1:2f}, {2:05.2f}'.format(1.23456, 1.23456, b) ‘4.56’, ‘[4.56]’
1.23456) c) 4.56, [4.56,]
a) Error d) 4.56, [4.56,]
b) ‘1.234560, 1.22345, 1.23’ Answer: b
c) No output Explanation: The code shown above shows the
d) ‘1.234560, 1.234560, 01.23’ formatting option on the same value,
Answer: d that is 4.56, where in the second case, the value is
Explanation: In the code shown above, various enclosed in a list. Hence the output
formatting options are displayed using of the code shown above is:
the format option. Hence the output of this code is: ‘4.56’, ‘[4.56]’
‘1.234560, 1.234560, 01.23’ Page 81 of 391
10. What will be the output of the following Python Python Questions and Answers – While and For
code? Loops – 1
'%.2f%s' % (1.2345, 99) 1. What will be the output of the following Python
a) ‘1.2345’, ‘99’ code?
b) ‘1.2399’ x = ['ab', 'cd']
c) ‘1.234599’ for i in x:
d) 1.23, 99 i.upper()
Answer: b print(x)
Explanation: In this code, we must notice that since a) [‘ab’, ‘cd’]
multiple values haven been given, b) [‘AB’, ‘CD’]
they should be enclosed in a tuple. Since the c) [None, None]
formatting format is %.2f, the value d) none of the mentioned
1.2345 is reduced to two decimal places. Hence the Answer: a
output of the code shown above: Explanation: The function upper() does not modify a
‘1.2399’. string in place, it returns a new
11. What will be the output of the following Python string which isn’t being stored anywhere.
code? 2. What will be the output of the following Python
'%s' %((1.23,),) code?
a) ‘(1.23,)’ x = ['ab', 'cd']
b) 1.23, for i in x:
c) (,1.23) x.append(i.upper())
d) ‘1.23’ print(x)
Answer: a a) [‘AB’, ‘CD’]
Explanation: The formatting expression accepts b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
either a single substitution value, or a c) [‘ab’, ‘cd’]
35

tuple of one or more items. Since single item can be d) none of the mentioned
Page

given either by itself or within the Answer: d

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: The loop does not terminate as new Explanation: 0O11 is an octal number.
elements are being added to the list 6. What will be the output of the following Python
in each iteration. code?
3. What will be the output of the following Python i=5
code? while True:
i=1 if i%0O9 == 0:
while True: break
if i%3 == 0: print(i)
break i += 1
print(i) a) 5 6 7 8
i+=1 b) 5 6 7 8 9
a) 1 2 c) 5 6 7 8 9 10 11 12 13 14 15 ….
b) 1 2 3 d) error
c) error Answer: d
d) none of the mentioned Explanation: 9 isn’t allowed in an octal number.
Answer: c 7. What will be the output of the following Python
Explanation: SyntaxError, there shouldn’t be a space code?
between + and = in +=. i=1
4. What will be the output of the following Python while True:
code? Page 83 of 391
Page 82 of 391 if i%2 == 0:
i=1 break
while True: print(i)
if i%0O7 == 0: i += 2
break a) 1
print(i) b) 1 2
i += 1 c) 1 2 3 4 5 6 …
a) 1 2 3 4 5 6 d) 1 3 5 7 9 11 …
b) 1 2 3 4 5 6 7 Answer: d
c) error Explanation: The loop does not terminate since i is
d) none of the mentioned never an even number.
Answer: a 8. What will be the output of the following Python
Explanation: Control exits the loop when i becomes code?
7. i=2
5. What will be the output of the following Python while True:
code? if i%3 == 0:
i=5 break
while True: print(i)
if i%0O11 == 0: i += 2
break a) 2 4 6 8 10 …
print(i) b) 2 4
i += 1 c) 2 3
a) 5 6 7 8 9 10 d) error
b) 5 6 7 8 Answer: b
c) 5 6 Explanation: The numbers 2 and 4 are printed. The
36

d) error next value of i is 6 which is


Page

Answer: b divisible by 3 and hence control exits the loop.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


9. What will be the output of the following Python Explanation: The else part is not executed if control
code? breaks out of the loop.
i=1 2. What will be the output of the following Python
while False: code?
if i%2 == 0: i=0
break while i < 3:
print(i) print(i)
i += 2 i += 1
a) 1 else:
b) 1 3 5 7 … print(0)
c) 1 2 3 4 … a) 0 1 2 3 0
d) none of the mentioned b) 0 1 2 0
Answer: d c) 0 1 2
Explanation: Control does not enter the loop d) error
because of False. Answer: b
10. What will be the output of the following Python Explanation: The else part is executed when the
code? condition in the while statement is
True = False false.
while True: 3. What will be the output of the following Python
print(True) code?
Page 84 of 391 x = "abcdef"
break while i in x:
a) True print(i, end=" ")
b) False a) a b c d e f
c) None b) abcdef
d) none of the mentioned c) i i i i i i …
Answer: d d) error
Explanation: SyntaxError, True is a keyword and it’s Answer: d
value cannot be changed. Explanation: NameError, i is not defined.
Page 85 of 391 Page 86 of 391
Python Questions and Answers – While and For 4. What will be the output of the following Python
Loops – 2 code?
1. What will be the output of the following Python x = "abcdef"
code? i = "i"
i=0 while i in x:
while i < 5: print(i, end=" ")
print(i) a) no output
i += 1 b) i i i i i i …
if i == 3: c) a b c d e f
break d) abcdef
else: Answer: a
print(0) Explanation: “i” is not in “abcdef”.
a) 0 1 2 0 5. What will be the output of the following Python
b) 0 1 2 code?
c) error x = "abcdef"
37

d) none of the mentioned i = "a"


Page

Answer: b while i in x:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


print(i, end = " ") d) a
a) no output Answer: c
b) i i i i i i … Explanation: String x is not being altered and i is in
c) a a a a a a … x[:-1].
d) a b c d e f 9. What will be the output of the following Python
Answer: c code?
Explanation: As the value of i or x isn’t changing, the x = "abcdef"
condition will always evaluate to i = "a"
True. while i in x:
6. What will be the output of the following Python x = x[1:]
code? print(i, end = " ")
x = "abcdef" a) a a a a a a
i = "a" b) a
while i in x: c) no output
print('i', end = " ") d) error
a) no output Answer: b
b) i i i i i i … Explanation: The string x is being shortened by one
c) a a a a a a … character in each iteration.
d) a b c d e f 10. What will be the output of the following Python
Answer: b code?
Explanation: As the value of i or x isn’t changing, the x = "abcdef"
condition will always evaluate to i = "a"
True. while i in x[1:]:
7. What will be the output of the following Python print(i, end = " ")
code? a) a a a a a a
x = "abcdef" b) a
i = "a" c) no output
while i in x: d) error
x = x[:-1] Answer: c
print(i, end = " ") Explanation: i is not in x[1:].
Page 87 of 391 Page 88 of 391
a) i i i i i i Python Questions and Answers – While and For
b) a a a a a a Loops – 3
c) a a a a a 1. What will be the output of the following Python
d) none of the mentioned code?
Answer: b x = 'abcd'
Explanation: The string x is being shortened by one for i in x:
character in each iteration. print(i)
8. What will be the output of the following Python x.upper()
code? a) a B C D
x = "abcdef" b) a b c d
i = "a" c) A B C D
while i in x[:-1]: d) error
print(i, end = " ") Answer: b
a) a a a a a Explanation: Changes do not happen in-place,
38

b) a a a a a a rather a new instance of the string is


Page

c) a a a a a a … returned.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


2. What will be the output of the following Python 6. What will be the output of the following Python
code? code snippet?
x = 'abcd' x = 'abcd'
for i in x: for i in range(len(x)):
print(i.upper()) i.upper()
a) a b c d print (x)
b) A B C D a) a b c d
c) a B C D b) 0 1 2 3
d) error c) error
Answer: b d) none of the mentioned
Explanation: The instance of the string returned by Answer: c
upper() is being printed. Explanation: Objects of type int have no attribute
3. What will be the output of the following Python upper().
code? 7. What will be the output of the following Python
x = 'abcd' code snippet?
for i in range(x): x = 'abcd'
print(i) for i in range(len(x)):
a) a b c d x[i].upper()
b) 0 1 2 3 print (x)
c) error a) abcd
d) none of the mentioned b) ABCD
Answer: c c) error
Explanation: range(str) is not allowed. d) none of the mentioned
4. What will be the output of the following Python Answer: a
code? Explanation: Changes do not happen in-place,
x = 'abcd' rather a new instance of the string is
for i in range(len(x)): returned.
print(i) 8. What will be the output of the following Python
a) a b c d code snippet?
b) 0 1 2 3 x = 'abcd'
c) error for i in range(len(x)):
Page 89 of 391 Page 90 of 391
d) 1 2 3 4 i[x].upper()
Answer: b print (x)
Explanation: i takes values 0, 1, 2 and 3. a) abcd
5. What will be the output of the following Python b) ABCD
code? c) error
x = 'abcd' d) none of the mentioned
for i in range(len(x)): Answer: c
print(i.upper()) Explanation: Objects of type int aren’t
a) a b c d subscriptable. However, if the statement was
b) 0 1 2 3 x[i], an error would not have been thrown.
c) error 9. What will be the output of the following Python
d) 1 2 3 4 code snippet?
Answer: c x = 'abcd'
39

Explanation: Objects of type int have no attribute for i in range(len(x)):


Page

upper(). x = 'a'

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


print(x) 3. What will be the output of the following Python
a) a code?
b) abcd abcd abcd d = {0: 'a', 1: 'b', 2: 'c'}
c) a a a a for x, y in d:
d) none of the mentioned print(x, y)
Answer: c a) 0 1 2
Explanation: range() is computed only at the time of b) a b c
entering the loop. 2 c 1 b c) 0 a
10. What will be the output of the following Python d) none of the mentioned
code snippet? Answer: d
x = 'abcd' Explanation: Error, objects of type int aren’t
for i in range(len(x)): iterable.
print(x) 4. What will be the output of the following Python
x = 'a' code?
a) a d = {0: 'a', 1: 'b', 2: 'c'}
b) abcd abcd abcd abcd for x, y in d.items():
c) a a a a print(x, y)
d) none of the mentioned a) 0 1 2
Answer: d b) a b c
Explanation: abcd a a a is the output as x is 2 c 1 b c) 0 a
modified only after ‘abcd’ has been d) none of the mentioned
printed once. Page 92 of 391
Page 91 of 391 Answer: c
Python Questions and Answers – While and For Explanation: Loops over key, value pairs.
Loops – 4 5. What will be the output of the following Python
1. What will be the output of the following Python code?
code? d = {0: 'a', 1: 'b', 2: 'c'}
x = 123 for x in d.keys():
for i in x: print(d[x])
print(i) a) 0 1 2
a) 1 2 3 b) a b c
b) 123 2 c 1 b c) 0 a
c) error d) none of the mentioned
d) none of the mentioned Answer: b
Answer: c Explanation: Loops over the keys and prints the
Explanation: Objects of type int are not iterable. values.
2. What will be the output of the following Python 6. What will be the output of the following Python
code? code?
d = {0: 'a', 1: 'b', 2: 'c'} d = {0: 'a', 1: 'b', 2: 'c'}
for i in d: for x in d.values():
print(i) print(x)
a) 0 1 2 a) 0 1 2
b) a b c b) a b c
2 c 1 b c) 0 a 2 c 1 b c) 0 a
d) none of the mentioned d) none of the mentioned
40

Answer: a Answer: b
Page

Explanation: Loops over the keys of the dictionary. Explanation: Loops over the values.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


7. What will be the output of the following Python set.add() returns None which is
code? printed.
d = {0: 'a', 1: 'b', 2: 'c'} 11. What will be the output of the following Python
for x in d.values(): code?
print(d[x]) for i in range(0):
a) 0 1 2 print(i)
b) a b c a) 0
2 c 1 b c) 0 a b) no output
d) none of the mentioned c) error
Answer: d d) none of the mentioned
Explanation: Causes a KeyError. Answer: b
8. What will be the output of the following Python Explanation: range(0) is empty.
code? Page 94 of 391
d = {0, 1, 2} Python Questions and Answers – While and For
for x in d.values(): Loops – 5
print(x) 1. What will be the output of the following Python
a) 0 1 2 code?
b) None None None for i in range(2.0):
c) error print(i)
Page 93 of 391 a) 0.0 1.0
d) none of the mentioned b) 0 1
Answer: c c) error
Explanation: Objects of type set have no attribute d) none of the mentioned
values. Answer: c
9. What will be the output of the following Python Explanation: Object of type float cannot be
code? interpreted as an integer.
d = {0, 1, 2} 2. What will be the output of the following Python
for x in d: code?
print(x) for i in range(int(2.0)):
a) 0 1 2 print(i)
b) {0, 1, 2} {0, 1, 2} {0, 1, 2} a) 0.0 1.0
c) error b) 0 1
d) none of the mentioned c) error
Answer: a d) none of the mentioned
Explanation: Loops over the elements of the set and Answer: b
prints them. Explanation: range(int(2.0)) is the same as range(2).
10. What will be the output of the following Python 3. What will be the output of the following Python
code? code?
d = {0, 1, 2} for i in range(float('inf')):
for x in d: print (i)
print(d.add(x)) a) 0.0 0.1 0.2 0.3 …
a) 0 1 2 b) 0 1 2 3 …
b) 0 1 2 0 1 2 0 1 2 … c) 0.0 1.0 2.0 3.0 …
c) None None None d) none of the mentioned
d) None of the mentioned Answer: d
41

Answer: c Explanation: Error, objects of type float cannot be


Page

Explanation: Variable x takes the values 0, 1 and 2. interpreted as an integer.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


4. What will be the output of the following Python a) None
code? b) (nothing is printed)
for i in range(int(float('inf'))): c) error
print (i) d) none of the mentioned
a) 0.0 0.1 0.2 0.3 … Answer: b
b) 0 1 2 3 … Explanation: The string does not have any character
c) 0.0 1.0 2.0 3.0 … to loop over.
d) none of the mentioned 9. What will be the output of the following Python
Answer: d code snippet?
Explanation: OverflowError, cannot convert float x=2
infinity to integer. for i in range(x):
Page 95 of 391 Page 96 of 391
5. What will be the output of the following Python x += 1
code snippet? print (x)
for i in [1, 2, 3, 4][::-1]: a) 0 1 2 3 4 …
print (i) b) 0 1
a) 1 2 3 4 c) 3 4
b) 4 3 2 1 d) 0 1 2 3
c) error Answer: c
d) none of the mentioned Explanation: Variable x is incremented and printed
Answer: b twice.
Explanation: [::-1] reverses the list. 10. What will be the output of the following Python
6. What will be the output of the following Python code snippet?
code snippet? x=2
for i in ''.join(reversed(list('abcd'))): for i in range(x):
print (i) x -= 2
a) a b c d print (x)
b) d c b a a) 0 1 2 3 4 …
c) error b) 0 -2
d) none of the mentioned c) 0
Answer: b d) error
Explanation: ‘ ‘.join(reversed(list(‘abcd’))) reverses a Answer: b
string. Explanation: The loop is entered twice.
7. What will be the output of the following Python Page 97 of 391
code snippet? Python Questions and Answers – While and For
for i in 'abcd'[::-1]: Loops – 6
print (i) 1. What will be the output of the following Python
a) a b c d code?
b) d c b a for i in range(10):
c) error if i == 5:
d) none of the mentioned break
Answer: b else:
Explanation: [::-1] reverses the string. print(i)
8. What will be the output of the following Python else:
code snippet? print("Here")
42

for i in '': a) 0 1 2 3 4 Here


Page

print (i) b) 0 1 2 3 4 5 Here

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) 0 1 2 3 4 only once.
d) 1 2 3 4 5 5. What will be the output of the following Python
Answer: c code?
Explanation: The else part is executed if control string = "my name is x"
doesn’t break out of the loop. for i in string:
2. What will be the output of the following Python print (i, end=", ")
code? a) m, y, , n, a, m, e, , i, s, , x,
for i in range(5): b) m, y, , n, a, m, e, , i, s, , x
if i == 5: c) my, name, is, x,
break d) error
else: Answer: a
print(i) Explanation: Variable i takes the value of one
else: character at a time.
print("Here") 6. What will be the output of the following Python
a) 0 1 2 3 4 Here code?
b) 0 1 2 3 4 5 Here string = "my name is x"
c) 0 1 2 3 4 for i in string.split():
d) 1 2 3 4 5 print (i, end=", ")
Answer: a a) m, y, , n, a, m, e, , i, s, , x,
Explanation: The else part is executed if control b) m, y, , n, a, m, e, , i, s, , x
doesn’t break out of the loop. c) my, name, is, x,
3. What will be the output of the following Python d) error
code? Answer: c
x = (i for i in range(3)) Explanation: Variable i takes the value of one word
for i in x: at a time.
print(i) 7. What will be the output of the following Python
a) 0 1 2 code snippet?
b) error a = [0, 1, 2, 3]
c) 0 1 2 0 1 2 for a[-1] in a:
d) none of the mentioned print(a[-1])
Answer: a a) 0 1 2 3
Explanation: The first statement creates a generator b) 0 1 2 2
object. c) 3 3 3 3
4. What will be the output of the following Python d) error
code? Page 99 of 391
Page 98 of 391 Answer: b
x = (i for i in range(3)) Explanation: The value of a[-1] changes in each
for i in x: iteration.
print(i) 8. What will be the output of the following Python
for i in x: code snippet?
print(i) a = [0, 1, 2, 3]
a) 0 1 2 for a[0] in a:
b) error print(a[0])
c) 0 1 2 0 1 2 a) 0 1 2 3
d) none of the mentioned b) 0 1 2 2
43

Answer: a c) 3 3 3 3
Page

Explanation: We can loop over a generator object d) error

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: a Correct answer
Explanation: The value of a[0] changes in each False
iteration. Since the first value that it 3. What will be the output of the following Python
takes is itself, there is no visible error in the current code?
example. pqrst
9. What will be the output of the following Python pqrst
code snippet? pqrst
a = [0, 1, 2, 3] pqrst
i = -2 Correct answer
for i not in a: pqrst
print(i) 4. What will be the output of the following Python
i += 1 code?
a) -2 -1 True
b) 0 False
c) error None
d) none of the mentioned Error
Answer: c 5. What will be the output of the following Python
Explanation: SyntaxError, not in isn’t allowed in for code snippet?
loops. Page 101 of 391
10. What will be the output of the following Python XY!@
code snippet? xy12
string = "my name is x" xY!4
for i in ' '.join(string.split()): xY1@
print (i, end=", ") Correct answer
a) m, y, , n, a, m, e, , i, s, , x, xY!4
b) m, y, , n, a, m, e, , i, s, , x 6. What will be the output of the following Python
c) my, name, is, x, code?
d) error 20
Answer: a error
Explanation: Variable i takes the value of one none of the mentioned
character at a time. 7. What will be the output of the following Python
Page 100 of 391 statement?
CHAPTER-2 - PYTHON REVISION TOUR-2 p
(STRING, LIST, TUPLE, DICTIONARY, MODULE) pq
MULTIPLE CHOICE QUESTIONS: rs
1. What will be the output of the following Python sr
code? Correct answer
201 rs
error 8. What will be the output of the following Python
Correct answer code snippet?
0 mn22qr
2. What will be the output of the following Python mn22qr22
code snippet? mnopqr22
True none of the mentioned
False Correct answer
44

None mn22qr22
Page

Error 9. What will be the output of the following Python

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


code snippet? 15.print(0xA + 0xB + 0xC):
Error 0xA0xB0xC
The sum of 5 and 12 is 17 Error
The sum of 0 and 1 is 2 0x22
None of the mentioned 33
Page 102 of 391 Correct answer
10.What will be the output of the following Python 33
code snippet? 16.What will be the output of the following Python
True code snippet?
False 10b10b1010a10
None abbabbababaab
Error none of the mentioned
Correct answer error
True Correct answer
11.What will be the output of the following Python 10b10b1010a10
code snippet? 17.To concatenate two strings to a third what
0+88 statements are applicable?
0088 s3 = s1 . s2
+088 s3 = s1.add(s2)
++88 s3 = s1.__add__(s2)
Correct answer s3 = s1 s2
+088 18.What will be the output of the following Python
12.Which of the following statement prints code?
hello\example\test.txt? terwarldwo
print(“hello\example\test.txt”) True
print(“hello\\example\\test.txt”) -1
print(“hello\”example\”test.txt”) None
print(“hello”\example”\test.txt”) 19.What will be the output of the following Python
Correct answer code?
print(“hello\\example\\test.txt”) Page 104 of 391
13.What will be the output of the following Python snow
code snippet? beautiful world
['pq', 'rs', 'tv'] Error
[‘pq\n’, ‘rs\n’, ‘tv\n’] beabtiful world
[‘pq\n’, ‘rs\n’, ‘tv’] Correct answer
[‘pq’, ‘rs’, ‘tv\n’] Error
Correct answer 20.What will be the output of the following Python
['pq', 'rs', 'tv'] code snippet?
14.What will be the output of the following Python (‘pqtv’)
code snippet? (‘pqtv’, ‘rs’, ”)
Pq rs tu ('pqtv', '', '')
Pq rs tU error
Page 103 of 391 21.What will be the output of the following Python
Pq Rs Tu code?
None of the mentioned Python fbb and fbb
45

Correct answer Python 'fbb' and fbb


Page

Pq Rs Tu Python fbb and ‘bin’

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Error True
Correct answer False
Python 'fbb' and fbb None
22.What will be the output of the following Python Error
code snippet? 30.What will be the output of the following Python
[‘mn’, ‘qr’, ‘st’] code snippet?
['mn', 'qr', 'st', ''] Page 106 of 391
('mn', 'qr', 'st') True
('mn', 'qr', 'st', '') False
Correct answer None
['mn', 'qr', 'st', ''] Error
23.What will be the output of the “hello” +1+2+3? Correct answer
hello123 True
hello 31.What will be the output of the following Python
Error code snippet?
hello6 True
24.What will be the output of the following Python False
code snippet? None
Page 105 of 391 Error
True Correct answer
False True
None 32.What will be the output of the following Python
Error code?
25.What will be the output of the following Python 201
code? error
True Correct answer
False 0
None 33.What will be the output of the following Python
Error code snippet?
Correct answer ['mnopqropstop']
True 'mnopqropstop'
26.What will be the output of the following Python error
code? none of the mentioned
error Correct answer
(‘wx’, ‘yz’) ['mnopqropstop']
('wx', 'yz', '') 34.What will be the output of the following Python
none of the mentioned code snippet?
Correct answer 2,223,334,445
('wx', 'yz', '') 222,333,444,5
27.What will be the output of the following Python 223334445
code snippet? Page 107 of 391
Pq rs-tu Error
Pq Rs-tu Correct answer
Pq Rs-Tu 2,223,334,445
28.None of the mentioned 35.What will be the output of the following Python
46

29.What will be the output of the following Python code?


Page

code snippet? pqrstv

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


pqrstv Correct answer
pqrstv y
pqrstv 42.What will be the output of the following Python
Correct answer statement?
pqrstv Error
36.What is “Hello”.replace(“l”, “e”)? Option 2
Heeeo x\95˜
Heelo \x95\x98
Heleo Correct answer
None x\95˜
Correct answer 43.What will be the output of the following Python
Heeeo code?
37.What will be the output of the following Python True
code? False
esorder Page 109 of 391
red None
rose error
redrose Correct answer
Correct answer True
esorder 44.What is the default value of encoding in encode()?
38.What will be the output of the following Python ascii
code? qwerty
{88: 50, 89: 51, 90: 52} utf-8
{80: 50, 81: 51, 82: 52} utf-16
432 Correct answer
234 utf-8
Correct answer 45.What will be the output of the following Python
{88: 50, 89: 51, 90: 52} code?
39.What will be the output of the following Python 12mnopqr12
code? mnopqr1212
Page 108 of 391 1212mnopqr
1pqrstv error
pqrstv1 Correct answer
pqrstv error
error 46.What will be the output of the following Python
Correct answer code?
1pqrstv x
40.What will be the output of the following Python 2xy@
code snippet? xy
The sum of 2 and 12 is 14 y
The sum of 10 and c is 16 47.What will be the output of the following Python
The sum of 10 and a is c code?
Error \tboo
41.What will be the output of the following Python boo
code? \boo
47

error none of the mentioned


Page

uty Correct answer

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


boo yzx
48.What will be the output of the following Python xyz
code? Correct answer
Page 110 of 391 xyz
mnopqr 54.What will be the output of the following Python
mnopqr code snippet?
mnopqr True
mnopqr False
Correct answer None
mnopqr Error
49.What will be the output of the following Python 55.What will be the output of the following Python
code? code?
a new line and world mn op qr
\nworld mnopqr
the letter r and then world mn\top\tqr
error mn op qr
Correct answer Correct answer
\nworld mn op qr
50.What will be the output of the following Python 56.What will be the output of the following Python
code? code snippet?
0.33 True
40.40% False
40.00% None
42.00% Error
Correct answer Correct answer
40.00% True
51.What will be the output of the following Python 57.Given a string example=”hello” what is the output
code snippet? of example.count(‘l’)?
True 21
False Page 112 of 391
None None
Error 0
Correct answer Correct answer
True 2
52.To return the length of string s what command do 58.What will be the output of the following Python
we execute? code?
s.__len__() 01
len(s) True
size(s) False
s.size() Correct answer
Correct answer False
Page 111 of 391 59.Say s=”hello” what will be the return value of
s.__len__() type(s)?
53.What will be the output of the following Python int
statement? bool
48

x str
Page

yz String

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


60.What will be the output of the following Python 66.Suppose s is “\t\tWorld\n”, what is s.strip()?
code snippet? \t\tworld\n
3,334,445,556 \t\tWorld\n
333,444,555,6 \t\tWORLD\n
3334445556 World
Error Page 114 of 391
Correct answer Correct answer
Error World
61.What will be the output of the following Python 67.What will be the output of the following Python
code? code snippet?
True pq1tvo
False pqrtvs
None pq1tvs
Error pq12ts2
Correct answer Correct answer
False pqrtvs
62.What will be the output of the following Python 68.What will be the output of the following Python
code? code snippet?
Page 113 of 391 00xy
op x00y
mnopqr xy00
error x0y0
none of the mentioned Correct answer
Correct answer 00xy
mnopqr 69.What will be the output of the following Python
63.To check whether string s1 contains another code snippet?
string s2, use _______ pqtv
s1.__contains__(s2) 10
s2 in s1 error
s1.contains(s2) none of the mentioned
si.in(s2) Correct answer
Correct answer pqtv
s1.__contains__(s2) 70.What will be the output of the following Python
64.What will be the output of the following Python code?
code? 4350
Python faa and bin Correct answer
Python (‘faa’, ‘bin’) and (‘faa’, ‘bin’) 5
Error Page 115 of 391
None of the mentioned 71.What will be the output of the following Python
Correct answer code?
Error pqr xyz
65.What will be the output of the following Python PQR XYZ
code? Pqr xyz
201 Pqr Xyz
error 72.What will be the output of the following Python
49

Correct answer code snippet?


Page

2 ['mn', 'qr', 'stop']

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


[‘mn’, ‘qropstop’] code?
[‘qropstop’,‘mn’ ] 0.677777
none of the mentioned 0.67
Correct answer 0.6777:.2
['mn', 'qr', 'stop'] Error
73.What will be the output of the following Python Correct answer
code snippet? Page 117 of 391
pqrs 0.67
2345 79.What will be the output of the following Python
error code?
none of the mentioned Jack Roy
Correct answer Robin Roy
pqrs Jack Smith
74.What will be the output of the following Python Robin Smith
code? Correct answer
Python {} and {} Robin Roy
Python fbb and bin 80.What will be the output of the following Python
Error code snippet?
Python and [‘mn’, ‘qr’, ‘st’]
Correct answer ['mn', 'qr', 'st', '']
Python fbb and bin ('mn', 'qr', 'st',)
75.What will be the output of the following Python ['mn', 'qr', 'st']
code snippet? 81.What will be the output of the following Python
Page 116 of 391 code snippet?
xyzz True
wxyz False
xzyz None
zxyz Error
Correct answer Correct answer
xyzz True
76.What will be the output of the following Python 82.What will be the output of the following Python
code? code?
SRQP Page 118 of 391
SRQP rs
PQRS pqrstv
pqrs error
Correct answer none of the mentioned
SRQP Correct answer
77.What will be the output of the following Python error
code snippet? 83.What will be the output of the following Python
('rs') statement?
(") Error
('rs', ", ") Output equivalent to print ‘black\berry’
('', 'rs', '') blackberry
Correct answer black berry
50

('', 'rs', '') Correct answer


Page

78.What will be the output of the following Python blackberry

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


84.What will be the output of the following Python 2223334445
code? Error
Python faa and bin 91.What will be the output of the following Python
Python {name1} and {name2} code?
Error Page 120 of 391
Python and 1
Correct answer True
Python faa and bin 32
85.What will be the output of the following Python 92.What function do you use to read a string?
code? input(“Enter a string”)
201 eval(input(“Enter a string”))
none of the mentioned enter(“Enter a string”)
Correct answer eval(enter(“Enter a string”))
1 Correct answer
86.What will be the output of the following Python input(“Enter a string”)
code? 93.What will be the output of the following Python
{120: 50, 121: 51, 122: 52} code snippet?
{97: 49, 98: 50, 99: 51} 3,334,445,556
Page 119 of 391 333,444,555,6
{100: 50, 101: 51, 102: 52} 3334445556
234 Error
Correct answer 94.What will be the output of the following Python
{120: 50, 121: 51, 122: 52} code snippet?
87.What will be the output of the following Python True
code? False
True None
False Error
Error 95.What will be the output of the following Python
None of the mentioned code snippet?
88.Suppose x is 6 and y is 4, x + y is same as True
________ False
x.__add(y) None
x.__add__(y) Error
x.__Add(y) Correct answer
x.__ADD(y) True
Correct answer 96.What will be the output of the following Python
x.__add__(y) code?
89.What arithmetic operators cannot be used with Page 121 of 391
strings? None None
+_ None 22
All of the mentioned 22 None
Correct answer Error is generated
_ Correct answer
90.What will be the output of the following Python Error is generated
code snippet? 97.What will be the output of the following Python
51

2,223,334,445 code?
Page

222,333,444,5 w

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


world 104. What will be the output of the following Python
he code?
rl Page 123 of 391
98.What will be the output of the following Python 40
statement? Error
Pp True
Error Correct answer
b 0
Correct answer 105. What will be the output of the following Python
P code snippet?
99.What will be the output of the following Python True
code snippet? False
True None
False Error
None Correct answer
Error True
Correct answer 106. If a class defines the __str__(self) method, for
True an object obj for the class, you
Page 122 of 391 can use which command to invoke the __str__
100. What will be the output of the following Python method.
code? obj.__str__()
1pqrstv str(obj)
pqrstv1 print obj
pqrstv all of the mentioned
error Correct answer
101. What will be the output of the following Python all of the mentioned
code? 107. What will be the output of the following Python
224 statement?
Error aqrQ
12 Correct answer
None q
Correct answer 108. What will be the output of the following Python
12 code?
102. What will be the output of the following Python Python bin and fab
code? Python fab and bin
pq+rs+tv Error
pq++++++++rs++++++++tv None of the mentioned
pq rs tv Page 124 of 391
None of the mentioned Correct answer
Correct answer Python fab and bin
None of the mentioned 109. What will be the output of the following Python
103. What will be the output of the following Python code?
code? nthopy
(‘mn’, ‘op’, ‘qr’, ‘st’, ‘uv’) python
('mn', 'op', 'qrstuv') hn
52

(‘mnopqr’, ‘st, ‘uv’) Correct answer


Page

error n

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


110. What will be the output of the following Python Error
statement?(python 3.xx) None of the mentioned
Python# 100#900.66 Correct answer
Python#100# 900.67 Python fff and bbb
Python # 100#900.67 117. The format function, when applied on a string
Python#100#900.67 returns ________
Correct answer Error
Python # 100#900.67 Page 126 of 391
111. What will be the output of the following Python int
code? bool
True str
23 118. What will be the output of the following Python
None of the mentioned code?
Correct answer rppq
2 rq
112. What will be the output of the following Python rppqrqrp
code? none of the mentioned
(‘pq’, ‘tv’) Correct answer
(‘pqtv’) rppq
('pq', 'rs', 'tv') 119. What will be the output of the following Python
2 code?
Page 125 of 391 xyz
113. What will be the output of the following Python 'xyz'
code? b’xyz’
error h’xyz’
rppqpqq Correct answer
r b’xyz’
pqr 120. What will be the output of the following Python
Correct answer code?
rppqpqq Python fff and bin
114. What will be the output of the following Python Python {name1} and {name2}
code? Error
Error Python and
-1 Correct answer
40 Error
Correct answer 121. What will be the output of the following Python
4 code?
115. What will be the output of the following Python pq rs tu
code? pqrstu
xyz. PQR pq\trs\ttu
XYZ. PQR Page 127 of 391
Xyz. pqr pq rs tu
Xyz. Pqr Correct answer
116. What will be the output of the following Python pq rs tu
code? 122. What will be the output of the following Python
53

Python fff and bbb code?


Page

Python (‘fff’, ‘bbb’) and (‘fff’, ‘bbb’) Python fff and bin

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Python {0} and {1} fff bin {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}
Error Correct answer
Python 0 and 1 {0: 'X0', 1: 'X1', 2: 'X2', 3: 'X3', 4: 'X4'}
Correct answer 130. What will be the output of the following Python
Python fff and bin code snippet?
123. What will be the output of the following Python True
code? False
201 None
none of the mentioned Error
Correct answer Correct answer
2 True
124. What will be the output of the following Python 131. What will be the output of the following Python
code? code?
True {1: 'x', 2: 'y', 3: 'z'}
False An exception is thrown
None {‘x’: ‘y’: ‘z’: }
Error {1: ‘x’, 2: ‘y’, 3: ‘z’}
Correct answer Correct answer
False {1: 'x', 2: 'y', 3: 'z'}
125. What will be the output of the following Python 132. What will be the output of the following Python
code snippet? code snippet?
abbabbababaab Page 130 of 391
10b10b1010a10 Counter({4: 4, 3: 3, 5: 3})
12babbababaab Counter({4: 3, 3: 2, 5: 2})
Page 128 of 391 Counter({4: 3})
babbababaab12 Counter({5: 3})
Correct answer Correct answer
abbabbababaab Counter({4: 3, 3: 2, 5: 2})
126. What will be displayed by print(ord('b') - 133. What will be the output of the following Python
ord('a'));? code snippet?
1 0 -1 2 {'x': 2, 'y': [3, 4, 5]}
Correct answer Exception is thrown
1 {‘x’: [2], ‘y’: 3}
127. Suppose y is 345.3546, what is format(y, {‘y’: [2], ‘x’: [3]}
“10.3f”) (_ indicates space). 134. What will be the output of the following Python
__345.355 code snippet?
___345.355 0
____345.355 None
_____345.354 An exception is thrown
Correct answer 3
___345.355 135. What will be the output of the following Python
Page 129 of 391 code?
129. What will be the output of the following Python Syntax error
code? “check”
An exception is thrown Page 131 of 391
54

{0: 'X0', 1: 'X1', 2: 'X2', 3: 'X3', 4: 'X4'} {2: 'check', 3: 'check', 4: 'check'}
Page

{0: ‘X’, 1: ‘X’, 2: ‘X’, 3: ‘X’, 4: ‘X’} {2:None,3:None,4:None}

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Correct answer {3:2}
{2: 'check', 3: 'check', 4: 'check'} [(5, 3), (3, 2)]
136. What will be the output of the following Python {4:3}
code? Correct answer
None [(5, 3), (3, 2)]
{ None:None, None:None, None:None} 144. What will be the output of the following Python
{1:None, 2:None, 3:None} code?
{} 25
Correct answer 17
{} 19
137. If b is a dictionary, what does any(b) do? Tuples can’t be made keys of a dictionary
Returns True if any key of the dictionary is true Correct answer
Returns False if dictionary is empty 19
Returns True if all keys of the dictionary are true 145. What will be the output of the following Python
Method any() doesn’t exist for dictionary code?
Correct answer {1: 'P', 2: 'Q', 3: 'R', 4: 'S', 5: 'T'}
Returns True if any key of the dictionary is true Page 134 of 391
138. What will be the output of the following Python Method update() doesn’t exist for dictionaries
code snippet? {1: ‘P’, 2: ‘Q’, 3: ‘R’}
Counter({2: 15, 4: 1, 3: 1}) {4: ‘S’, 5: ‘T’}
Counter({2: 1, 3: 1, 4: 1}) 146. What will be the output of the following Python
Counter({4: 2}) code snippet?
Counter({4: 1}) Error, dictionary in a dictionary can’t exist
Correct answer ‘Numbers’: {2: 90, 3: 9}
Counter({2: 1, 3: 1, 4: 1}) {'Numbers': {2: 90, 3: 9}, 'Letters': {5: 'A'}}
139. What will be the output of the following Python {‘Numbers’: {2: 90}, ‘Letters’: {5: ‘A’}}
code snippet? 147. What will be the output of the following Python
Page 132 of 391 code?
124 [3,4,5]
140. Error, the keys can’t be a mixture of letters and 53
numbers An exception is thrown
141. What will be the output of the following Python 148. What will be the output of the following Python
code snippet? code snippet?
865 {2,3,4,5}
An exception is thrown Counter({5, 4, 3, 2})
142. What will be the output of the following Python Page 135 of 391
code snippet? Counter({5: 3, 2: 2, 4: 2, 3: 1})
method del doesn’t exist for the dictionary {5: 3, 2: 3, 3: 4, 3: 2}
del deletes the values in the dictionary Correct answer
del deletes the entire dictionary Counter({5: 3, 2: 2, 4: 2, 3: 1})
del deletes the keys in the dictionary 149. What will be the output of the following Python
Correct answer code?
del deletes the entire dictionary An exception is thrown since the dictionary is empty
Page 133 of 391 ‘‘
143. What will be the output of the following Python 1
55

code snippet? Error


Page

Counter({5: 4, 4: 4, 3: 2}) Correct answer

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Error del x(“jack”:30)
150. What will be the output of the following Python Correct answer
code snippet? del x[“jack”]
{1: ‘X’, 2: ‘Y’, 3: ‘Z’} 155. Which of the statements about dictionary
Z values if false?
{1: 3, 2: 3, 3: 3} More than one key can have the same value
No method called setdefault() exists for dictionary The values of the dictionary can be accessed as
Correct answer dict[key]
Z Values of a dictionary must be unique
151. Which of the following is not a declaration of Values of a dictionary can be a mixture of letters and
the dictionary? numbers
{1: ‘A’, 2: ‘B’} Page 137 of 391
dict([[1,”A”],[2,”B”]]) Correct answer
{1,”A”,2”B”} Values of a dictionary must be unique
{} 156. What will be the output of the following Python
Correct answer code?
{1,”A”,2”B”} ['X', 'Y', 'Z']
1. Suppose x = {“jack”:30, “henry”:35}. To obtain the [‘Y’,’Z’,’X’]
number of entries in dictionary [3,5,7]
which command do we use? [7,5,3]
x.size() Correct answer
len(x) ['X', 'Y', 'Z']
size(x) 157. What will be the output of the following Python
Page 136 of 391 code snippet?
x.len() {1: 'P', 2: 'Q', 3: 'R', 4: 'S'}
Correct answer Error
len(x) None
152. What will be the output of the following Python [1,2,3,4]
code? Correct answer
{2: 6} {1: 'P', 2: 'Q', 3: 'R', 4: 'S'}
{2: 6, 4: 5} 158. What will be the output of the following Python
Error, syntax error for pop() method code?
{2: 6, 3: 4} {1: 'P', 2: 'Q', 3: 'R'}
Correct answer {1: ‘P’, 2: ‘S’, 3: ‘R’}
{2: 6, 4: 5} Error, copy() method doesn’t exist for dictionaries
153. What will be the output of the following Python “None” is printed
code snippet? 159. What will be the output of the following Python
True code snippet?
False Page 138 of 391
None True
Error False
154. Suppose x = {“jack”:30, “henry”:35}, to delete Error
the entry for “jack” what None
command do we use? Correct answer
x.delete(“jack”:30) Error
56

x.delete(“jack”) 160. What will be the output of the following Python


Page

del x[“jack”] code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


{} Correct answer
False The keys of a dictionary can be accessed using
True values
An exception is thrown 167. What will be the output of the following Python
Correct answer code snippet?
True 3210
161. What will be the output of the following Python Correct answer
code? 2
407 168. What will be the output of the following Python
An exception is thrown code snippet?
Correct answer 55
7 50
162. What will be the output of the following Python peter
code? henry
Page 139 of 391 Correct answer
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16} 50
{0: 0, 1: 1, 4: 4, 9: 9, 4: 16} 169. What will be the output of the following Python
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} code?
Dictionary comprehension doesn’t exist 35
163. What will be the output of the following Python Page 141 of 391
code? 4
Error, invalid syntax Too many arguments for pop() method
P76 Correct answer
Correct answer 5
6 170. What will be the output of the following Python
164. Which of the following statements create a code?
dictionary? 10
d = {} An exception is thrown
d = {“jack”:30, “peter”:35} ‘‘
d = {30:”jack”, 35:”peter”} If a is a dictionary with some key-value pairs, what
All of the mentioned does a.popitem() do?
Correct answer Removes an arbitrary element
All of the mentioned Removes all the key-value pairs
165. What will be the output of the following Python Removes the key-value pair for the key given as an
code? argument
{‘2’:2, ‘0’:0, ‘1’:1} Invalid method for dictionary
OrderedDict([('0', 0), ('1', 1), ('2', 2)]) Correct answer
An exception is thrown Removes an arbitrary element
'' 171. What will be the output of the following Python
Correct answer code snippet?
OrderedDict([('0', 0), ('1', 1), ('2', 2)]) Error as the key-value pair of 1:’A’ is already deleted
166. Which of these about a dictionary is false? 021
The values of a dictionary can be accessed using keys 172. What will be the output of the following Python
Page 140 of 391 code snippet?
The keys of a dictionary can be accessed using values Page 142 of 391
57

Dictionaries aren’t ordered [“jack”:30, “john”:35]


Page

Dictionaries are mutable ['jack', 'john']

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


(“jack”, “john”) dict_items([(‘P’), (‘Q’), (‘R’)])
(“jack”:30, “john”:35) Correct answer
Correct answer dict_items([(1, 'P'), (2, 'Q'), (3, 'R')])
['jack', 'john'] Page 144 of 391
173. What will be the output of the following Python 180. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1
code snippet? after list1.extend([34, 5])?
“jack”, 30, 35, and “henry” [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
{'jack': 30, 'henry': 35} [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
“jack” and “henry” [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
30 and 35 [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
Correct answer [3, 1, 25, 5, 20, 5, 4, 3, 34, 5]
{'jack': 30, 'henry': 35} Correct answer
174. What will be the output of the following Python [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
code snippet? 181. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], What is list1[-1]?
1X2Y3Z 3510
123 Correct answer
XYZ 0
1:”X” 2:”Y” 3:”Z” 182. Let list1 = [0.5 a for a in range(0, 4)], list1 is
Correct answer ________
1X2Y3Z [0, 1, 2, 3]
175. Which of the following isn’t true about [0, 1, 2, 3, 4]
dictionary keys? [0.0, 0.5, 1.0, 1.5]
More than one key isn’t allowed [0.0, 0.5, 1.0, 1.5, 2.0]
Keys must be immutable Correct answer
Keys must be integers [0.0, 0.5, 1.0, 1.5]
When duplicate keys encountered, the last 183. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], What is list1[:-1]?
assignment wins 0
Correct answer [1, 3, 2, 4, 5, 2, 1]
Keys must be integers [1, 3, 2, 4, 5, 2]
176. What will be the output of the following Python [1, 3, 2, 4, 5, 2, 1, 0]
code snippet? Correct answer
Page 143 of 391 [1, 3, 2, 4, 5, 2, 1]
14X 184. What Will be The output Of the following code
Invalid syntax for get method snippet?
177. What will be the output of the following Python Page 145 of 391
code? 11
123 1 33
‘X’ ‘Y’ ‘Z’ 31
1 ‘X’ 2 ‘Y’ 3 ‘Z’ 3 33
Error, it should be: for i in a.items(): Correct answer
Correct answer 3 33
123 185. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], Which of the
178. What will be the output of the following Python following is correct?
code? print(list1[0])
dict_items([(1, 'P'), (2, 'Q'), (3, 'R')]) print(list1[:2])
58

Syntax error print(list1[:-2])


Page

dict_items([(1,2,3)]) print(list1[4:6])

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


186. list1 = [11, 2, 23] and list2 = [2, 11, 23], list1 == list1.add(3, 5)
list2 is ________ Page 147 of 391
True list1.append(3, 5)
False Correct answer
187. "Welcome to Python".split() is ________ list1.insert(3, 5)
["Welcome", "to", "Python"] 194. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is
("Welcome", "to", "Python") max(list1)?
{"Welcome", "to", "Python"} 548
"Welcome", "to", "Python" 25
188. Let list1 = [2, 3, 4], What is list1 2? 1
[2, 6, 4] Correct answer
[2, 4, 3, 2, 4] 25
[2, 3, 4, 2, 3, 4] 195. To shuffle list1, use _______.
[2, 3, 4, 4, 3, 2] list1.shuffle()
Page 146 of 391 shuffle(list1)
189. Let list1 = [3, 4, 5, 18, 5, 22, 1, 2], what is random.shuffle(list1)
len(list1)? random.shuffleList(list1)
67854 Correct answer
Correct answer random.shuffle(list1)
8 196. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is
190. __________ creates a list. list1.count(5)?
list1 = list() 0412
list1 = [] Correct answer
list1 = list([12, 4, 4]) 2
list1 = [12, 4, 4] 197. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1
list1 = [1, "3", "red"] after list1.reverse()?
191. What is the output when we execute [3, 4, 5, 20, 5, 25, 1, 3]
list(“hello”)? [1, 3, 3, 4, 5, 5, 20, 25]
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’] [25, 20, 5, 5, 4, 3, 3, 1]
[‘hello’] [1, 3, 4, 5, 20, 5, 25, 3]
[‘llo’] [3, 1, 25, 5, 20, 5, 4, 3]
[‘olleh’] Correct answer
Correct answer [3, 1, 25, 5, 20, 5, 4, 3]
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’] 198. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1
192. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.sort()?
after list1.pop(1)? Page 148 of 391
[3, 4, 5, 20, 5, 25, 1, 3] [3, 4, 5, 20, 5, 25, 1, 3]
[1, 3, 3, 4, 5, 5, 20, 25] [1, 3, 3, 4, 5, 5, 20, 25]
[3, 5, 20, 5, 25, 1, 3] [25, 20, 5, 5, 4, 3, 3, 1]
[1, 3, 4, 5, 20, 5, 25] [1, 3, 4, 5, 20, 5, 25, 3]
[3, 1, 25, 5, 20, 5, 4] Correct answer
Correct answer [1, 3, 3, 4, 5, 5, 20, 25]
[3, 5, 20, 5, 25, 1, 3] 199. What will be the output of the following code
193. To insert 5 to the third position in list1, use snippet?
_______. [2] [3] [4]
59

list1.insert(3, 5) 123
Page

list1.insert(2, 5) [2, 3, 4]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


[2] [2, 3] [2, 3, 4] ['a b c d']
Correct answer ['a#b#c#d']
[2, 3, 4] ['abcd']
200. Let list1 = [3, 2, 5, 10, 5, 24, 1, 3], what is Correct answer
min(list1)? ['a', 'b', 'c', 'd']
548 207. To add 5 to the end of list1, use _______.
25 list1.add(5)
1 list1.append(5)
Correct answer list1.addLast(5)
1 list1.addEnd(5)
201. What will be the output of the following code Correct answer
snippet? list1.append(5)
[2, 3] 208. list1 = [11, 2, 23] and list2 = [11, 2, 2], list1 <
Page 149 of 391 list2 is ________
[1, 3] True
[3, 2] False
[1, 2, 3] 209. What will be the output of the following code
Correct answer snippet?
[3, 2] Page 151 of 391
202. What Will be The output Of the following code [1, 2, 3, 33]
snippet? [1, 2, 3]
01234 [1, 33]
Correct answer [33, 2, 3]
1 Correct answer
203. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is [33, 2, 3]
list1.index(5)? 210. Let list1 = [0, 3, 2], what is sum(list1)?
0412 54621
Correct answer Correct answer
2 5
204. What is list("pqrs")? 211. To remove string "red" from list1, use _______.
['p', 'q', 'r', 's'] list1.remove("red")
['pq'] list1.remove(red)
['rs'] list1.removeAll("red")
['pqrs'] list1.removeOne("red")
Correct answer Correct answer
['p', 'q', 'r', 's'] list1.remove("red")
Page 150 of 391 Page 152 of 391
205. What will be the output of the following code 212. What will be the output of the following code?
snippet? False
234561 True
112345 Error
612345 None
12344 213. What will be the output of the following code?
Correct answer 674
12344 22
60

206. What is list("a#b#c#d".split('#'))? Correct answer


Page

['a', 'b', 'c', 'd'] 4

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


214. What will be the output of the following code? [12,48,15, [77]40,60]
bmd [12, 48, 15, [77], 40, 60]
None [12, 48, 15, 77,[ 40, 60]]
215. What will be the output of the following code? [12,48,15,77,[ 40, 60]]
[(‘P’, 1), (‘Y’, 1), (‘T’, 1), (‘H’, 1), (‘O’, 1), (‘N’, 1)] 223. What will be the output of the following code?
[(‘PYTHON’, 5)] Page 155 of 391
[('P', 1), ('Y', 1), ('T', 1), ('H', 1), ('O', 1), ('N', 1)] 5148
Syntax error Correct answer
Page 153 of 391 5
216. 224. What will be the output of the following code?
To which of the following the “in” operator can be used to check if an item is
in it? None [4, 6, 8]
Dictionary [4,6,8] None
Set [1, 2, 3] [4,5,6]
Lists None [1, 2, 3]
All of the above 225. What will be the output of the following code?
Correct answer Option 1
All of the above Option 2
217. What will be the output of the following code? Option 3
[ 45, 6, 4,] Page 156 of 391
[45, 4] Syntax error
[4, 6, 45 ] Correct answer
[45, 4, 6] Option 2
Correct answer 226. What will be the output of the following code?
[45, 4, 6] 2846
218. Suppose list1 is [3, 4, 15, 15, 25, 15], what is Correct answer
list1.index(15)? 8
0523 227. What will be the output of the following code?
219. What will be the output of the following code? Option 1
2234336334523445455 Option 2
2234334544523423345 Option 3
22345233452344523455 Option 4
22234522223453452345 Correct answer
Page 154 of 391 Option 3
Correct answer 228. What will be the output of the following code?
22345233452344523455 Page 157 of 391
220. What will be the output of the following code? 2367
1234 229. What will be the output of the following code?
Correct answer ['2, 4, 6']
2 [2] [ 2, 4] [2, 4, 6]
221. What will be the output of the following code? [2, 4, 6]
[5,8] [2] [4] [6]
[] Correct answer
[5, 7] [2, 4, 6]
Invalid arguments for filter function 230. What will be the output of the following code?
Correct answer 14
61

[5, 7] [2,3,5,7]
Page

222. What will be the output of the following code? 5

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


[2, 5, 9, 14] Page 160 of 391
Correct answer Option 3
[2, 5, 9, 14] Syntax error
231. How many elements are in a? Correct answer
Page 158 of 391 Option 3
[[0, 1], [0, 2], [2, 0], [0, 1]] 237. What will be the output of the following code?
[[0, 0], [0, 1], [1, 0], [1, 1]] True
[[0, 10], [0, 2], [0, 3], [0, 4]] False
None Correct answer
Correct answer False
[[0, 0], [0, 1], [1, 0], [1, 1]] 238. What will be the output of the following code?
232. What will be the output of the following code? [1, 4, 3]
The program prints two rows 3 5 6 2 followed by 44 7 [2, 4, 6, 5]
23 [ 2, 4, 5]
The program prints on row 3 6 5 2 44 7 3 2 [ 2, 4, 6]
The program prints two rows 2 4 5 6 followed by 2 3 Correct answer
7 44 [ 2, 4, 5]
The program prints two rows 3 6 5 2 followed by 44 6 239. What will be the output of the following code?
23 2546
233. What will be the output of the following Python Correct answer
code? 6
5340 240. What will be the output of the following code?
Correct answer Page 161 of 391
4 [20,33,60,[90]]
234. What will be the output of the following code? [20,33,60,[80]]
Page 159 of 391 [20, 33, 60, [80]]
Return a list containing every third item from L [20, 33, 60, [90]]
starting at index 0 Correct answer
Return an empty list [20, 33, 60, [80]]
Return a list containing every third index from L 241. What will be the output of the following code?
starting at index 0 Option 1
Return a list containing the items from L starting Option 2
from index 0, omitting every third Option 3
item Option 4
Correct answer Correct answer
Return a list containing every third item from L Option 4
starting at index 0 242. What will be the output of the following code?
235. What will be the output of the following code? [2] [3]
['Monkey', 'Fox', 'Deer'] Page 162 of 391
['Monkey', 'Fox', 'Lion'] [49] [50]
['Monkey', 'Fox', 'Tiger'] [[2]] [[3]]
['Monkey', 'Tiger', 'Lion'] Syntax error
Correct answer 243. What will be the output of the following code?
['Monkey', 'Fox', 'Lion'] [‘Mango’, ‘Nail’, ‘Ox’]
236. What will be the output of the following code? ['Ox', 'Nail', 'Mango']
62

Option 1 ['Ox', 'Mango', 'Nail' ]


Page

Option 2 Invalid syntax for sort()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Correct answer Option 1
['Ox', 'Nail', 'Mango'] 251. What will be the output of the following code?
244. What will be the output of the following code? Option 1
['mango', 'berry', 'apple', 'banana', 'cherry'] Option 2
['mango', 'berry', 'banana', 'cherry'] Option 3
['mango', 'apple', 'berry', 'banana', 'cherry'] Syntax error
['mango', 'apple', 'berry', 'cherry' 'banana' ] Page 165 of 391
Correct answer 252. What will be the output of the following code?
['mango', 'berry', 'apple', 'banana', 'cherry'] 1: 2: 3:
245. What will be the output of the following code? Exception is thrown
2345 One Two Three
5678 0: One 1: Two 2: Three
2 3 9 15 Correct answer
3 6 10 14 0: One 1: Two 2: Three
Correct answer 253. What will be the output of the following code?
Page 163 of 391 [2, 5]
3 6 10 14 [5, 2]
246. What will be the output of the following code? [3, 5]
[20,33,60,[90]] [5, 3]
[20, 33, 60, [88]] 254. What will be the output of the following code?
[20, 33, 60, [90]] Syntax error
[20,33,60,[88]] [[5], [], []]
247. What will be the output of the following code? [[5], [5], [5]]
A [[],5, [], []]
Dhiman Correct answer
Error [[5], [5], [5]]
n 255. What will be the output of the following code?
248. What will be the output of the following code? Page 166 of 391
561 132
12 None
8 Correct answer
Syntax error 1
Correct answer 256. What will be the output of the following code?
8 [4, 8, 9, 7, 2, 3]
249. Which of the following commands will create a Syntax error
list? [4,[8,9],5,2,3]
list1 = [] [4,5,6,7,8]
list1 = list() Correct answer
list1 = list([1, 2, 3]) [4, 8, 9, 7, 2, 3]
all of the mentioned 257. What will be the output of the following code?
Page 164 of 391 66234
250. What will be the output of the following code? 62345
Option 1 34562
Option 2 34566
Option 3 Correct answer
63

Option 4 34566
Page

Correct answer 258. What will be the output of the following code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


14 print(list1[:-2])
[2,5,7,9] all of the mentioned
[2, 5, 9, 14] 265. What will be the output of the following code?
[2,3,9,14] Page 169 of 391
Page 167 of 391 Error
Correct answer [2,5]
[2, 5, 9, 14] [7]
259. What is the maximum number of elements List 7
can contain in Python? 266. What will be the output of the following code?
10 million items 10
10 million on 32-bit system and 20 million on 64-bit 12
system 28
There is no limit Correct answer
20 million items 2
Another limit 267. Suppose list1 = [0.5 x for x in range(0, 5)], list1
Correct answer is:
There is no limit [1.0, 0.5, 0.0, 1.5, 2.0]
260. What will be the output of the following code? [0.0, 0.5, 1.0, 1.5, 2.0]
("Welcome", "to", "Python") [2.0, 1.5, 1.0, 0.5, 0.0]
{"Welcome", "to", "Python"} [0.1, 0.2, 0.3, 0.4, 0.5]
['Welcome', 'to', 'Python'] Correct answer
"Welcome", "to", "Python" [0.0, 0.5, 1.0, 1.5, 2.0]
Correct answer 268. What will be the output of the following code?
['Welcome', 'to', 'Python'] [[3],[8]]
261. What will be the output of the following code? [2, 3, 4, 5]
2456 Error
Correct answer Page 170 of 391
5 [14]
Page 168 of 391 Correct answer
262. What will be the output of the following code? [2, 3, 4, 5]
56 269. What will be the output of the following code?
44 3 44
7 4 44
Correct answer 5 44
44 67
263. What will be the output of the following code? 270. What will be the output of the following code?
[[4, 2.5], [2, 3], [0.7, 0.7]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[0.7, 0.7], [2, 3], [4, 2.5]] [[0, 2, 3], [1, 3, 4], [2, 4, 5]]
[[0.7, 0.7], [4, 2.5], [2, 3]] [1, 2, 3, 4, 5, 6, 7, 8, 9]
[[2, 3], [4, 2.5], [0.7, 0.7]] [0, 1, 2, 1, 2, 3, 2, 3, 4]
Correct answer Correct answer
[[0.7, 0.7], [2, 3], [4, 2.5]] [[0, 2, 3], [1, 3, 4], [2, 4, 5]]
264. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of Page 171 of 391
the following is correct syntax 272. Which of the following is a Python tuple?
for slicing operation? [1, 2, 3]
64

print(list1[0]) (1, 2, 3)
Page

print(list1[:2]) {1, 2, 3}

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


{} Error, tuple has no attribute sort
Correct answer 279. What will be the output of the following Python
(1, 2, 3) code?
273. What is the data type of (1)? Page 173 of 391
Tuple (4,5)
Integer (2, 3, 4, 5)
List Error as tuples are immutable
Both tuple and integer None
Correct answer Correct answer
Integer (2, 3, 4, 5)
274. If x=(1,2,3,4), x[1:-1] is _________ 280. What will be the output of the following Python
Error, tuple slicing doesn’t exist code?
[2,3] 523
(2,3,4) None
(2,3) Correct answer
275. What will be the output of the following Python 3
code? 281. What will be the output of the following Python
Error, tuples are immutable code?
Option 2 [2, 3, 9]
((‘check’,)’check’,) [2, 3, 5, 4, 8, 9]
Page 172 of 391 (2, 4, 8)
Option 4 [2, 5, 8]
Correct answer Correct answer
Option 2 [2, 5, 8]
276. What will be the output of the following Python 282. What will be the output of the following Python
code? code?
(min - 5) (False, False, False)
5 False
Error True
None of these above Page 174 of 391
Correct answer None
5 Correct answer
277. What will be the output of the following Python False
code? 283. Is the following Python code valid?
40 No because tuple is immutable
45 Yes, first element in the tuple is deleted
“jimmy” Yes, the entire tuple is deleted
“jack” No, invalid syntax for del method
Correct answer Correct answer
45 Yes, the entire tuple is deleted
278. What will be the output of the following Python 284. What will be the output of the following Python
code? code?
(2,3,4,6) Now, a=(1,2,4)
(3,4,2,6) Now, a=(1,3,4)
None Now a=(3,4)
65

Error, tuple has no attribute sort Error as tuple is immutable


Page

Correct answer Correct answer

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Error as tuple is immutable 12
285. Is the following Python code valid? 9
Yes, 1 is printed Correct answer
Yes, [1,2,3,4] is printed 9
No, too many values to unpack 292. Tuples can’t be made keys of a dictionary.
Yes, (1,2,3,4) is printed True
Correct answer False
Yes, (1,2,3,4) is printed Correct answer
286. What will be the output of the following Python False
code? 293. What will be the output of the following Python
Page 175 of 391 code?
(1, 2, 4) True
(2, 4, 3) False
(3, 5, 4) Error
(1, 2) None
Correct answer 294. What will be the output of the following Python
(3, 5, 4) code?
287. What will be the output of the following Python Page 177 of 391
code? [(2, 3), (3, 4), (4, 9)]
True [(2,3),(3,2),(4,9)]
(False, True, False) Error because tuples are immutable
False Error, tuple has no sort attribute
None Correct answer
288. What will be the output of the following Python [(2, 3), (3, 4), (4, 9)]
code? 295. Suppose p = (1, 2, 4, 3), which of the following
fga Python code is incorrect?
None print(p[3])
Correct answer p[3] = 45
g print(max(p))
289. What will be the output of the following Python print(len(p))
code? Correct answer
gaf p[3] = 45
None 296. What will be the output of the following Python
Correct answer code?
f (max - 75)
290. What will be the output of the following Python 75
code? Error
Page 176 of 391 None of these above
False Correct answer
True 75
Error, < operator is not valid for tuples 297. What will be the output of the following Python
Error, < operator is valid for tuples but not if there code?
are sub-tuples 125
291. What will be the output of the following Python Error
code? Correct answer
66

Too many arguments for sum() method Error


Page

The method sum() doesn’t exist for tuples 298. What will be the output of the following Python

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


code? 304. What will be the output of the following Python
Page 178 of 391 code?
Option 1 Page 180 of 391
Option 2 x(i=2, j=5)
Option 3 obj(i=2, j=5)
None of these above (2,5)
299. What will be the output of the following Python An exception is thrown
code? Correct answer
30 x(i=2, j=5)
24 305. Is the following Python code valid?
51 Yes, x=(1,2,3,4) and y=(1,2,3,4)
12 Yes, a=(2,3,4) and b=(1,2,3,4)
Correct answer No because tuples are immutable
51 No because wrong syntax for update() method
300. What will be the output of the following Python 306. What type of data is: x=[(1,1),(2,4),(3,9)]?
code? Array of tuples
(apple, mango) List of tuples
('apple', 'mango') Tuples of lists
('apple''mango') Invalid type
Page 179 of 391 Correct answer
None List of tuples
Correct answer 307. Is the following Python code valid?
('apple', 'mango') Yes, z will be ((0, 1, 2),(‘X’,’Y’,’Z’))
301. What will be the output of the following Python Yes, z will be ((1,2,3),(‘X’,’Y’,’Z’))
code? No because tuples are immutable
Invalid syntax for slicing No because the syntax for zip function isn’t valid
[0,2] Page 181 of 391
(0, 1) Correct answer
(0, 2) Yes, z will be ((0, 1, 2),(‘X’,’Y’,’Z’))
Correct answer 308. What will be the output of the following Python
(0, 2) code?
302. What will be the output of the following Python (2, 3, 2, 3)
code? [2, 3, 2, 3]
("Yellow", "Green", "Blue") (2, 2, 3, 3)
'tuple' object does not support item assignment [2, 2, 3, 3]
("Red", "Green", "Blue") Correct answer
None (2, 3, 2, 3)
Correct answer 309. What will be the output of the following Python
'tuple' object does not support item assignment code?
303. What will be the output of the following Python (1, 2)
code? (1, 2, 4)
True (3, 4)
False (2, 4, 3)
Error 310. What will be the output of the following Python
None code?
67

Correct answer (‘Check’,’Check’,’Check’)


Page

False Operator not valid for tuples

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


(‘CheckCheckCheck’) a. Longest Word
Syntax error b. Zee
Correct answer c. Amit
(‘CheckCheckCheck’) d. Error
311. What will be the output of the following Python Ans. d. Error
code? Q6. Write the output of the following code :
(6,8) >>>L=[1,5,9]
Invalid syntax >>>print(sum(L),max(L),min(L))
Page 182 of 391 Page 184 of 391
(8,6) a. 15 9 1
Nothing is printed b. Error
Correct answer c. Max and Min are only for String Value
(8,6) d. None of the above
Page 183 of 391 Ans. a. 15 9 1
MCQ on List in Python Q7. Do we have any inbuilt function for shuffling the
Q1. Which of the following statement will create list? values of List. :
a. L1=list( ) a. True
b. L1=[1,2,3,4] b. False
c. Both of the above Ans. a. True
d. None of the above Q8. Write the output of the following code :
Ans. c. Both of the above >>>L=[1,2,3,4,5,[6,7,8]]
Q2. Write the output of the following code : >>>print(L[5])
list(“welcome”) a. [6, 7, 8]
a. [‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’] b. 6, 7, 8
b. (‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’) c. Error
c. [‘welcome’] d. 6
d. None of the above Ans. a. [6, 7, 8]
Ans. a. [‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’] Q9. Write the output of the following code :
Q3. Write the output of the following code : L=list(“www.csiplearninghub.com”)
>>> L=[‘w’,’e’,’l’,’c’,’o’,’m’,’e’] print(L[20 : -1])
>>> print(len(L)) a. [‘c’ , ‘o’]
a. 7 b. [‘c’ , ‘o’ , ‘m’]
b. 8 c. (com)
c. 9 d. Error
d. None Ans. a. [‘c’ , ‘o’]
Ans. a. 7 Q10. Write the output of the following code :
Q4. Write the output of the following code : >>>L=list(“www.csiplearninghub.com”)
>>> L=[“Amit”,”Anita”,”Zee”,”Longest Word”] >>>print(L[20 : 0])
>>> print(max(L)) a. Error
a. Zee b. No Value
b. Longest Word c. None
c. Error d. [ ]
d. None of the above Ans. d. [ ]
Ans. a. Zee Q11. Write the output of the following code :
Q5. Write the output of the following code : >>>L=[“Amit”,”Sumit”,”Naina”]
68

>>> L=[“Amit”,”Anita”,”Zee”,”Longest Word”,123] >>>print(L[-1][-1])


Page

>>> print(max(L)) a. [Naina]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b. [a] Q17. Write the output of the following code :
c. a L= [1*x for x in range(10,1,-4)]
d. None of the above print(L)
Page 185 of 391 a. [10, 6, 2]
Ans. c. a b. [10, 7, 4]
Q12. Write the output of the following code : c. Error
>>>L=[“Amit”,”Sumit”,”Naina”] d. None of the above
>>>print(L[1:-1]) Ans. a. [10, 6, 2]
a. [‘Sumit’] Q18. Write the output of the following code :
b. [a] L=[1,2,3,4,5]
c. [Naina] for i in L:
d. None of the above print(i,end=” “)
Ans. a. [‘Sumit’] i=i+1
Q13. Write the output of the following code : a. 1, 2, 3, 4, 5
L=[“Amit”,”Sumit”,”Naina”] b. 1, 3, 5
print(L*2) c. Error
a. [‘Amit’, ‘Sumit’, ‘Naina’, ‘Amit’, ‘Sumit’, ‘Naina’] d. None of the above
b. [“Amit” , “Sumit” , “Naina”] Ans. a. 1, 2, 3, 4, 5
c. Error Q19. Write the output of the following code :
d. None of the above L=[“Amit”,”Sumit”,”Naina”]
Ans. a. [‘Amit’, ‘Sumit’, ‘Naina’, ‘Amit’, ‘Sumit’, L1=[“Sunil”]
‘Naina’] print(L + L1)
Q14. Write the output of the following code : a. [‘Amit’ , ‘Sumit’ , ‘Naina’ , [‘Sunil’]]
L=[“Amit”,”Sumit”,”Naina”] b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’]
print(L**2) c. List can not concatenate
a. Error d. None of the above
b. [“Amit”,”Sumit”,”Naina”][“Amit”,”Sumit”,”Naina”] Ans. b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’]
c. [“Amit”,”Sumit”,”Naina”] Q20. Which command is used to add an element in
d. [“Amit”,”Sumit”,”Naina”,”Amit”,”Sumit”,”Naina”] List named L1
Ans. a. Error a. L1.add(4)
Q15. Write the output of the following code : b. L1.append(4)
L=[0.5 * x for x in range(4)] c. L1.new(4)
print(L) d. None of the above
a. [0.0, 0.5, 1.0, 1.5] Ans. b. L1.append(4)
b. (0,.5, 1, 1.5) Q21. Write the output of the following :
c. [0.0, 0.5, 1.0, 1.5, 2.0] L = “123456”
d. Error L = list(L)
Ans. a. [0.0, 0.5, 1.0, 1.5] print(type(L[0]))
Q16. Write the output of the following code : a. class ‘str’
L=[‘a’ * x for x in range(4)] b. class ‘int’
print(L) c. 1
a. [‘ ‘ , ‘a’ , ‘aa’ , ‘aaa’] d. Error
b. [‘a’, ‘aa’, ‘aaa’] Page 187 of 391
c. Error Ans. a. class ‘str’
d. None of the above Q22. Write the output of the following:
69

Ans. a. [‘ ‘ , ‘a’ , ‘aa’ , ‘aaa’] T=(1,2,3,4,5.5)


Page

Page 186 of 391 L = list(T)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


print(L[3]*2.5) Q28. Write the output of the following:
a. Error T = [1,2,3,4]
b. 10 T1=T
c. 10.0 T[0] = “A”
d. 4 print(T)
Ans. c. 10.0 print(T1)
Q23. Index value in list and string start from 0(T/F) a.
a. True ['A', 2, 3, 4]
b. False [1, 2, 3, 4]
Ans. a. True b.
Q24. Write the output of the following: ['A', 2, 3, 4]
T=(1,2,3,4,5.5) ['A', 2, 3, 4]
L = list(T) c.
print(L*2) [1, 2, 3, 4]
a. [2, 4, 6, 8, 11] [1, 2, 3, 4]
b. [1, 2, 3, 4, 5.5, 1, 2, 3, 4, 5.5] d. Error
c. Error Ans. b.
d. None of the above ['A', 2, 3, 4]
Ans. b. [1, 2, 3, 4, 5.5, 1, 2, 3, 4, 5.5] ['A', 2, 3, 4]
Q25. Write the output of the following: Q29. What type of error is returned by the following
T = [1,2,3,4] statement?
T1 = [3,4,5,6] T = [1,2,3,4]
T2 = T + T1 print(T.index(9))
print(T2) a. IndexError
a. [1, 2, 3, 4, 5, 6] b. TypeError
b. [1, 2, 3, 4, 3, 4, 5, 6] c. ValueError
c. [4, 6, 8, 10] d. None of the above
d. Error Ans. c. ValueError
Ans. b. [1, 2, 3, 4, 3, 4, 5, 6] Q30. Write the output of the following.
Q26. Write the output of the following: T = [1,2,3,4]
T = [1,2,3,4] T1=[5,6,7]
T1 = [3,4,5,6] L=T.append(T1)
T2 = T.append(T1) print(L)
print(T2) a. None
a. [1, 2, 3, 4, [3, 4, 5, 6]] b. [1, 2, 3, 4, [5, 6, 7]]
b. [1, 2, 3, 4, 3, 4, 5, 6] c. [ ]
c. None Page 189 of 391
Page 188 of 391 d. Error
d. None of the above Ans. a. None
Ans. c. None Q31. Write the output of the following:
Q27. del statement can delete the following from the L=["Amit","Sumit","Naina"]
List? L1=["Sunil"]
a. Single Element print(L + L1)
b. Multiple Elements a. [“Amit” , “Sumit” , “Naina” , [“Sunil”] ]
c. All elements along with List object b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’]
70

d. All of the above c. Error


Page

Ans. d. All of the above d. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’][‘Amit’ , ‘Sumit’ ,

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


‘Naina’ , ‘Sunil’] d. //
Ans. b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’] Ans. a. *
Q32. Result of list slice is also a list?(T/F) Q39. Following two print statement will return same
a. True result.(T/F)
b. False L1 = [1, 5, 9]
Ans. a. True L2 = [2, 3, 4]
Q33. What we call the operation which is used to print(L1 + L1)
extract particular range from a sequence. print(L1 * 2)
a. Slicing a. True
b. range b. False
c. Indexing Ans. a. True
d. Replication Q40. Which of the following is not list operation?
Ans. a. Slicing a. Indexing
Q34. Index of last element in list is n-1, where n is b. Slicing
total number of elements.(T/F) c. Dividing
a. True d. Concatenation
b. False Ans. c. Dividing
Ans. a. True Q41. Which of the following is true about List data
Q35. Write the output of the following : type in Python?
L=[2 * x for x in range(3,14,3)] a. List is a Sequence data type
print(L) b. List is mutable
a. [6, 12, 18, 24] c. List can have elements of different data type
b. [6, 12, 18] d. All of the above
c. [6, 12, 18, 24, 30] Ans. d. All of the above
d. Error Q42. Identify data type of ‘T’ in following line of
Ans. a. [6, 12, 18, 24] Code:
Q36. Write the output of the following : T = list(tuple([1,2,3]))
L=["Amit","Sumit","Naina"] print(type(T))
L1=["Sumit"] a. Tuple
print(L - L1) b. List
a. [“Amit” , “Naina”] Page 191 of 391
b. [“Amit” , “Naina”, “Sumit”] c. Nested List
Page 190 of 391 d. None of the above
c. Show Error Ans. b. List
d. None of the above Q43. List and String are different
Ans. c. Show Error a. in reference to their indexing
Q37. Write the output of the following: b. in reference to data type of elements they contain
a. Error c. None of the above
b. 14 + 9 -1 d. Both of the above
c. 23 Ans. b. in reference to data type of elements they
d. 24 contain
Ans. c. 23 Q44. List can have elements of _____________ data
Q38. Which mathematical operator is used for types.
repetition? a. Same
a. * b. Different
71

b. ** c. Both of the above


Page

c. + d. None of the above

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Ans. b. Different d. None of the above
Q45. Write the output of the following: Ans. b. Concatenation of String
L =[['Physics',101],['Chemistry',202], Q51. Which mathematical operator is used to
['Maths',303],45, 6, 'j'] concatenate list?
print(len(L)) a. +
a. 3 b. //
b. 4 c. **
c. 5 d. None of the above
d. 6 Ans. a. +
Ans. d. 6 Q52. Write the output of the following :
Q46. Write the output of the following : L1 = [1,2,3]
L = [1,2,3,4,5,6,7,8,9,10] L2=[5,6,7]
print(L[L[3]]) L1 + L2
a. 3 print(L1)
b. 4 a. [1, 2, 3, 4, 5, 6, 7]
c. 5 b. [1, 2, 3, 5, 6, 7]
d. 6 c. [1, 2, 3]
Ans. c. 5 d. None of the above
Q47. Which of the following statement will return Ans.c. [1, 2, 3]
first element from right of list ‘L’? Q53. If we try to concatenate a list with elements of
a. L[0] some other data type, _____________
b. L[-1] occurs.
c. L[1] a. SyntaxError
d. None of the Above b. SyntaxError
Ans. b. L[-1] c. TypeError
Q48. Write the output of the following: d. None of the above
L = [1,2,3,4,5,6,7,8,9,10] Page 193 of 391
print(L[len(L) - 1]) Ans. c. TypeError
Page 192 of 391 Q54. Name the operator which is used in the
a. 9 following print statement.
b. 1 a. Concatenation
c. Error b. Repetition
d. None of the above c. Membership
Ans. d. None of the above d. None of the above
Q49. We can concatenate only two list at one Ans. b. Repetition
time.(T/F) Q55. print(L1 + L1) and print(L1 * 2) will produce the
a. True same result.(L1 is a List)(T/F)
b. False a. True
Ans. b. False b. False
Q50. The following statements is showing ______ Ans. a. True
operation in List. Q56. Which operator helps to check whether an
L1 = [1,2,3,4] element is present in list or not?
L2 = [1,2,3,4] a. +
L = L1 + L2 b. in
a. Replication of List c. **
72

b. Concatenation of String d. None of the above


Page

c. Indexing of String Ans. b. in

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Q57. Write the output of the following: a. Len( )
print(1 in [[1],2,3]) b. length( )
a. True c. len( )
b. False d. Length( )
c. Error Ans. c. len( )
d. None of the above Q64. Write the output of the following :
Ans. b. False D = list[ ]
Q58. Which operation of List is shown in following print(len(D))
lines? a. 0
L1 = [1, 2, 3, 4, 5, 6, 7, 8] b. 1
print(L1[3 : 6]) c. SyntaxError
a. Concatenation d. ValueError
b. Repetition Ans. c. SyntaxError
c. Slicing Q65. remove( ) function removes the
d. None of the above _______________ occurrences of an element from
Ans. c. Slicing the
Q59. Which of the following statement will reverse list
the list L1? a. all
a. L1[ : : 1] b. first
b. L1[-1 : : -1] c. last
c. L1[: : -1] d. None of the above
d. None of the above Ans. b. first
Ans. c. L1[: : -1] Page 195 of 391
Q60. Traversing a list can be done with the help of Q66. sort () function Sorts the elements of the given
_________ list in-place(T/F)
a. loop a. True
Page 194 of 391 b. False
b. if Ans. a. True
c. if–elif Q67. Which of the following function creates the
d. None of the above new list?
Ans. a. loop a. sort( )
Q61. Write the output of the following: b. sorted( )
print(len(tuple[1])) c. reverse( )
a. 1 d. All of the above
b. 0 Ans. b. sorted( )
c. Error Q68. Write the output of the following :
d. None of the above D = [1,2,3]
Ans. c. Error D1 = D
Q62. Write the output of the following : D.append(4)
L = [[1,2,3,5,6,7,[1,[2,3]]]] print(D1)
print(len(L)) a. [1, 2, 3, 4]
a. 4 b. [1, 2, 3]
b. 3 c. Error
c. 2 d. None of the above
d. 1 Ans. a. [1, 2, 3, 4]
73

Ans. d. 1 Q69. Fill in the blanks with same word in both places
Page

Q63. Which function returns the length of a list? >>> import __________

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


>>> list1 = [1,2,3,4,5] a. [13,12,15, 27, 46]
>>> list2 = _________copy(list1) b. [13, 12, 15, 3, 46]
>>> list2 c. [13, 12, 15, 27, 3]
a. copy d. None of the above
b. math Ans. b. [13, 12, 15, 3, 46]
c. pickle Q75. Write the output of the following:
d. None of the above list1=[3,2,5,7,3,6]
Ans. a. copy list1.remove(3)
Q70. Write the output of the following : print(sum(list1))
def listchange(L): a. 23
L.append(45) b. 20
return c. 19
L1 = [1, 2, 3, 4] d. None of the above
listchange(L1) Ans. a. 23
print(L1) Page 197 of 391
a. [1, 2, 3, 4] Q76. Write the output of the following
b. [1, 2, 3, 45] list1=[3,2,5,7,3,6]
c. [1, 2, 3, 4, 45] list1.insert(6,3)
d. None of the above print(list1)
Page 196 of 391 a. [3, 2, 5, 6, 7, 3, 6]
Ans. c. [1, 2, 3, 4, 45] b. [3, 2, 5, 6, 3, 6]
Q71. Write the output of the following: c. [3, 2, 5, 7, 3, 6, 3]
print([] * 2 ) d. None of the above
a. [ ] Ans. c. [3, 2, 5, 7, 3, 6, 3]
b. 0 Q77. Write the output of the following
c. Error L = [14, 2, 3, 16, 15]
d. None of the above L[1:4] = [5, 4, 8]
Ans. a. [ ] print(L)
Q72. Which of the following will give output as a. [14, 5, 4, 8, 15]
[21,2,9,7] ? if list L = [1,21,4,2,5,9,6,7] b. [14, 5, 4, 8, 2, 3, 16, 15]
a. print(L[1 : 8 : 2]) c. Error
b. print(L[1 : : 2]) d. None of the above
c. Both of the above Ans. a. [14, 5, 4, 8, 15]
d. None of the above Q78. Write the output of the following
Ans. print(L[1 : : 2]) L = ["Amit", 'Sumit', 'Ravi']
Q73. Write the output of the following : print(L[0][1])
L = ['Amit', 'anita', 'Sumant', 'Zaid'] a. A
print(max(L)) b. Amit
a. Zaid c. S
b. Sumant d. m
c. anita Ans.d. m
d. Amit Q79. Write the output of the following
Ans. c. anita L = ["Amit", 'Sumit', 'Ravi']
Q74. Write the output of the following: print("@".join(L))
L=[13, 12, 15, 27, 3, 46] a. @Amit
74

list1.pop(3) b. Amit@Sumit@Ravi
Page

print(L) c. Amit@Sumit@Ravi@

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d. None of the above a. [0]
Ans. b. Amit@Sumit@Ravi b. [0, 4]
Q80. Write the output of the following: c. [4, 4]
L = ['A', 'S', 'R'] d. [0, 0]
L = L + L*2 Ans. d. [0, 0]
print(L) Q85. Write the output of the following:
a. [‘A’, ‘S’, ‘R’, ‘2A’, ‘2S’, ‘2R’] Page 199 of 391
b. [‘A’, ‘S’, ‘R’, ‘A’, ‘S’, ‘R’, ‘A’, ‘S’, ‘R’] L = [23, 45, 65, 32, 3]
c. [‘A’, ‘S’, ‘R’] L.insert(L[4], 'Monitor')
d. Error print(L)
Page 198 of 391 a. [23, 45, 65, ‘Monitor’, 32, 3]
Ans. b. [‘A’, ‘S’, ‘R’, ‘A’, ‘S’, ‘R’, ‘A’, ‘S’, ‘R’] b. [23, 45, 65, 32, ‘Monitor’, 3]
Q81. Write the output of the following : c. [23, 45, 65, 32, 3, ‘Monitor’]
L = [[5, 7, 9, 1 ], [12, 23, 4, 9]] d. None of the above
for r in L: Ans. a. [23, 45, 65, ‘Monitor’, 32, 3]
r.reverse( ) Q86. Which statement will give the same output?
for e in r: list1 = [1, 2, 3, 4]
print(e, end = ” “) list2 = [5, 6, 7, 8]
a. 1 9 7 5 9 4 23 12 a. print(len(list1 + list2))
b. b. print(len(list1) + len (list2))
1975 c. print(list2[3])
9 4 23 12 d. All of the above
c. Ans. d. All of the above
Error Q87. Write the output of the following:
d. None of the above L = [11, 21, 31, 41]
Ans. a. 1 9 7 5 9 4 23 12 L.append([51,62,73,84])
Q82. Write the output of the following: print(len(L))
L = [[5, 7, 9, 1 ], [12, 23, 4, 9]] a. 8
for r in L: b. 5
r.sort() c. 4
for e in r: d. None of the above
print(e, end = ” “) Ans. b. 5
a. 1 5 7 9 4 9 12 23 Q88. Write the output of the following :
b. 1 4 5 7 9 9 12 23 L = [11, 21, 31, 41]
c. 9 7 5 1 23 12 9 4 L.extend([51,62,73,84])
d. None of the above print(len(L))
Ans. a. 1 5 7 9 4 9 12 23 a. 8
Q83. How many elements will be there in list ‘L’ b. 4
L = [[p, q] for p in (0, 4) for q in (0, 4)] c. 5
a. 2 d. Error
b. 4 Ans. a. 8
c. 8 Q89. Write the output of the following
d. 16 L1 = ['C++', 'C-Sharp', 'Visual Basic']
Ans. b. 4 L2 = [name.upper() for name in L1]
Q84. Write the output of the following: L3 = [name for name in L1]
75

L = [[p, q] for p in (0, 4) for q in (0, 4)] if(L2[2][0] == L3[2][0]):


Page

print(L[0]) print("YES")

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


else: Ans. a. [12, 11, 10, 9, 8]
print("N0") Q94. Write the output of the following :
Page 200 of 391 L1 = [1, 2, 3]
a. No L2 = [9, 8]
b. Yes S= [m * n for m in L1 for n in L2]
c. Error print(S)
d. None of the above a. [9, 8, 18, 16, 27, 24]
Ans. b. Yes b. [9, 18, 27, 8, 16, 24]
Q90. Write the output of the following : c. [8, 9, 16, 18, 24, 27]
L = [11, 22, 33, 44, 55, 66] d. Error
for i in range(1, 6): Ans. a. [9, 8, 18, 16, 27, 24]
L[i - 1] = L[i]*2 Q95. Write the output of the following :
for i in range(0, 4): L1 = [1, 2, 3]
print(L[i], end = " ") L2 = [9, 8]
a. 44 66 88 110 S= [n + m for m in L1 for n in L1]
b. 22 33 44 55 print(S)
c. 11 22 33 44 a. [2, 3, 4, 3, 4, 5, 4, 5]
d. Error b. [1, 2, 3, 2, 3, 4, 3, 4, 5]
Ans. a. 44 66 88 110 c. [2, 3, 4, 3, 4, 5, 4, 5, 6]
Q91. Write the output of the following : d. Error
L= [1,2,3,4,5] Ans. c. [2, 3, 4, 3, 4, 5, 4, 5, 6]
m = [m and 1 for m in L] Q96. Which of the following statement will generate
print(m) the square of given list L ?
a. [1, 2, 3, 4, 5] L = [1, 2, 3, 4, 5]
b. [1, 1, 1, 1, 1] a. [x ** 2 for x in L
c. [1, 0, 1, 0, 1 b. [x * 2 for x in L]
d. None of the above c. [x ^ 3 for x in L
Ans. b. [1, 1, 1, 1, 1] d. None of the above
Q92. Write the output of the following : Ans. a. [x ** 2 for x in L
L= [1,2,3,4,5] Q97. Which of the following function is used to
m = [m + 3 for m in L] shuffle the list ?
print(m) a. random( )
a. [4, 5, 6, 7, 8, 9] b. swap( )
b. [4, 5, 6, 7, 8, 9, 10] c. shuffle( )
c. [4, 5, 6, 7, 8] d. None of the above
d. Error Ans. a. random( )
Ans. c. [4, 5, 6, 7, 8] Q98. Both the print statement will produce the same
Q93. Write the output of the following : result.(T/F)
L1 = [1, 2, 3, 4, 5] L = ["Amit", "Ananya", "Parth"]
L2 = [9, 8, 7, 6, 5] print(L[-1])
S= [L1 + 3 for L1 in L2] print(L[-1][-1])
print(S) a. True
a. [12, 11, 10, 9, 8] b. False
b. [1, 2, 3, 4, 5, 6, 7, 8, 9] Page 202 of 391
c. [4, 5, 6, 7, 8] Ans. b. False
76

Page 201 of 391 Q99. Write the output of the following:


Page

d. Error L1 = [1, 2, 3]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


L2 = [1, 2, 3, 4, 5, 6] b) hello
print(L1 in L2) c) h
a. True d) o
b. False Answer: d
Ans. b. False Explanation: -1 corresponds to the last index.
Q100. Which of the following command will insert 7 5. What arithmetic operators cannot be used with
in third position of List L. strings?
a. L.insert(3, 7) a) +
b. L.insert(2, 7) b) *
c. L.add(3, 7) Page 204 of 391
d. L.append(3, 7) c) –
Ans. b. L.insert(2, 7) d) All of the mentioned
Page 203 of 391 Answer: c
Questions and Answers –Strings – 1 Explanation: + is used to concatenate and * is used
1. What will be the output of the following Python to multiply strings.
statement? 6. What will be the output of the following Python
1. >>>"a"+"bc" code?
a) a 1. >>>print (r"\nhello")
b) bc a) a new line and hello
c) bca b) \nhello
d) abc c) the letter r and then hello
Answer: d d) error
Explanation: + operator is concatenation operator. Answer: b
2. What will be the output of the following Python Explanation: When prefixed with the letter ‘r’ or ‘R’
statement? a string literal becomes a raw
1. >>>"abcd"[2:] string and the escape sequences such as \n are not
a) a converted.
b) ab 7. What will be the output of the following Python
c) cd statement?
d) dc 1. >>>print('new' 'line')
Answer: c a) Error
Explanation: Slice operation is performed on string. b) Output equivalent to print ‘new\nline’
3. The output of executing string.ascii_letters can c) newline
also be achieved by: d) new line
a) string.ascii_lowercase_string.digits Answer: c
b) string.ascii_lowercase+string.ascii_upercase Explanation: String literal separated by whitespace
c) string.letters are allowed. They are
d) string.lowercase_string.upercase concatenated.
Answer: b 8. What will be the output of the following Python
Explanation: Execute in shell and check. statement?
4. What will be the output of the following Python 1. >>> print('x\97\x98')
code? a) Error
1. >>> str1 = 'hello' b)
2. >>> str2 = ',' 97
3. >>> str3 = 'world' 98
77

4. >>> str1[-1:] c) x\97


Page

a) olleh d) \x97\x98

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: c 1. class tester:
Explanation: \x is an escape sequence that means 2. def __init__(self, id):
the following 2 digits are a 3. self.id = str(id)
hexadecimal number encoding a character. 4. id="224"
9. What will be the output of the following Python 5.
code? 6. >>>temp = tester(12)
1. >>>str1="helloworld" 7. >>>print(temp.id)
2. >>>str1[::-1] a) 224
a) dlrowolleh b) Error
b) hello c) 12
c) world d) None
Page 205 of 391 Answer: c
d) helloworld Explanation: Id in this case will be the attribute of
Answer: a the class.
Explanation: Execute in shell to verify. 3. What will be the output of the following Python
10. print(0xA + 0xB + 0xC): code?
a) 0xA0xB0xC 1. >>>example = "snow world"
b) Error 2. >>>print("%s" % example[4:7])
c) 0x22 a) wo
d) 33 b) world
Answer: d c) sn
Explanation: 0xA and 0xB and 0xC are hexadecimal d) rl
integer literals representing the Answer: a
decimal values 10, 11 and 12 respectively. There Explanation: Execute in the shell and verify.
sum is 33. Page 207 of 391
Page 206 of 391 4. What will be the output of the following Python
Python Questions and Answers – Strings – 2 code?
1. What will be the output of the following Python 1. >>>example = "snow world"
code? 2. >>>example[3] = 's'
1. class father: 3. >>>print example
2. def __init__(self, param): a) snow
3. self.o1 = param b) snow world
4. c) Error
5. class child(father): d) snos world
6. def __init__(self, param): Answer: c
7. self.o2 = param Explanation: Strings cannot be modified.
8. 5. What will be the output of the following Python
9. >>>obj = child(22) code?
10.>>>print "%d %d" % (obj.o1, obj.o2) 1. >>>max("what are you")
a) None None a) error
b) None 22 b) u
c) 22 None c) t
d) Error is generated d) y
Answer: d Answer: d
Explanation: self.o1 was never created. Explanation: Max returns the character with the
78

2. What will be the output of the following Python highest ascii value.
Page

code? 6. Given a string example=”hello” what is the output

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


of example.count(‘l’)? Explanation: __add__ is another method that can
a) 2 be used for concatenation.
b) 1 Page 209 of 391
c) None Python Questions and Answers – Strings – 3
d) 0 1. What will be the output of the following Python
Answer: a statement?
Explanation: l occurs twice in hello. 1. >>>chr(ord('A'))
7. What will be the output of the following Python a) A
code? b) B
1. >>>example = "helle" c) a
2. >>>example.find("e") d) Error
a) Error Answer: a
b) -1 Explanation: Execute in shell to verify.
c) 1 2. What will be the output of the following Python
d) 0 statement?
Answer: c 1. >>>print(chr(ord('b')+1))
Explanation: Returns lowest index. a) a
8. What will be the output of the following Python b) b
code? c) c
1. >>>example = "helle" d) A
2. >>>example.rfind("e") Answer: c
Page 208 of 391 Explanation: Execute in the shell to verify.
a) -1 3. Which of the following statement prints
b) 4 hello\example\test.txt?
c) 3 a) print(“hello\example\test.txt”)
d) 1 b) print(“hello\\example\\test.txt”)
Answer: b c) print(“hello\”example\”test.txt”)
Explanation: Returns highest index. d) print(“hello”\example”\test.txt”)
9. What will be the output of the following Python Answer: b
code? Explanation: \is used to indicate that the next \ is
1. >>>example="helloworld" not an escape sequence.
2. >>>example[::-1].startswith("d") 4. Suppose s is “\t\tWorld\n”, what is s.strip()?
a) dlrowolleh a) \t\tWorld\n
b) True b) \t\tWorld\n
c) -1 c) \t\tWORLD\n
d) None d) World
Answer: b Answer: d
Explanation: Starts with checks if the given string Explanation: Execute help(string.strip) to find
starts with the parameter that is details.
passed. 5. The format function, when applied on a string
10. To concatenate two strings to a third what returns ___________
statements are applicable? a) Error
a) s3 = s1 . s2 b) int
b) s3 = s1.add(s2) c) bool
c) s3 = s1.__add__(s2) d) str
79

d) s3 = s1 * s2 Page 210 of 391


Page

Answer: c Answer: d

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: Format function returns a string. Answer: c
6. What will be the output of the “hello” +1+2+3? Explanation: str is used to represent strings in
a) hello123 python.
b) hello Page 212 of 391
c) Error Python Questions and Answers – Strings – 4
d) hello6 1. What is “Hello”.replace(“l”, “e”)?
Answer: c a) Heeeo
Explanation: Cannot concatenate str and int objects. b) Heelo
7. What will be the output of the following Python c) Heleo
code? d) None
1. >>>print("D", end = ' ') Answer: a
2. >>>print("C", end = ' ') Explanation: Execute in shell to verify.
3. >>>print("B", end = ' ') 2. To retrieve the character at index 3 from string
4. >>>print("A", end = ' ') s=”Hello” what command do we execute
a) DCBA (multiple answers allowed)?
b) A, B, C, D a) s[]
c) D C B A b) s.getitem(3)
d) D, C, B, A will be displayed on four lines c) s.__getitem__(3)
Answer: c d) s.getItem(3)
Explanation: Execute in the shell. Answer: c
8. What will be the output of the following Python Explanation: __getitem(..) can be used to get
statement?(python 3.xx) character at index specified as parameter.
1. >>>print(format("Welcome", "10s"), end = '#') 3. To return the length of string s what command do
2. >>>print(format(111, "4d"), end = '#') we execute?
3. >>>print(format(924.656, "3.2f")) a) s.__len__()
a) Welcome# 111#924.66 b) len(s)
b) Welcome#111#924.66 c) size(s)
c) Welcome#111#.66 d) s.size()
d) Welcome # 111#924.66 Answer: a
Answer: d Explanation: Execute in shell to verify.
Explanation: Execute in the shell to verify. 4. If a class defines the __str__(self) method, for an
9. What will be displayed by print(ord(‘b’) – ord(‘a’))? object obj for the class, you can use
a) 0 which command to invoke the __str__ method.
b) 1 a) obj.__str__()
c) -1 b) str(obj)
d) 2 c) print obj
Answer: b d) all of the mentioned
Explanation: ASCII value of b is one more than a. Answer: d
Hence the output of this code is 98- Explanation: Execute in shell to verify.
97, which is equal to 1. 5. To check whether string s1 contains another string
Page 211 of 391 s2, use ________
10. Say s=”hello” what will be the return value of a) s1.__contains__(s2)
type(s)? b) s2 in s1
a) int c) s1.contains(s2)
b) bool d) si.in(s2)
80

c) str Page 213 of 391


Page

d) String Answer: a

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: s2 in s1 works in the same way as c) Peter Smith
calling the special function __contains__ d) John Smith
. Answer: b
6. Suppose i is 5 and j is 4, i + j is same as ________ Explanation: Execute in the shell to verify.
a) i.__add(j) 9. What function do you use to read a string?
b) i.__add__(j) a) input(“Enter a string”)
c) i.__Add(j) b) eval(input(“Enter a string”))
d) i.__ADD(j) c) enter(“Enter a string”)
Answer: b d) eval(enter(“Enter a string”))
Explanation: Execute in shell to verify. Answer: a
7. What will be the output of the following Python Explanation: Execute in shell to verify.
code? 10. Suppose x is 345.3546, what is format(x, “10.3f”)
1. class Count: (_ indicates space).
2. def __init__(self, count = 0): a) __345.355
3. self.__count = count b) ___345.355
4. c) ____345.355
5. c1 = Count(2) d) _____345.354
6. c2 = Count(2) Answer: b
7. print(id(c1) == id(c2), end = " ") Explanation: Execute in the shell to verify.
8. Page 215 of 391
9. s1 = "Good" Python Questions and Answers – Strings – 5
10.s2 = "Good" 1. What will be the output of the following Python
11.print(id(s1) == id(s2)) code?
a) True False print("abc DEF".capitalize())
b) True True a) abc def
c) False True b) ABC DEF
d) False False c) Abc def
Answer: c d) Abc Def
Explanation: Execute in the shell objects cannot Answer: c
have same id, however in the case of Explanation: The first letter of the string is
strings its different. converted to uppercase and the others are
8. What will be the output of the following Python converted to lowercase.
code? 2. What will be the output of the following Python
1. class Name: code?
2. def __init__(self, firstName, mi, lastName): print("abc. DEF".capitalize())
3. self.firstName = firstName a) abc. def
4. self.mi = mi b) ABC. DEF
5. self.lastName = lastName c) Abc. def
6. d) Abc. Def
7. firstName = "John" Answer: c
8. name = Name(firstName, 'F', "Smith") Explanation: The first letter of the string is
9. firstName = "Peter" converted to uppercase and the others are
10.name.lastName = "Pan" converted to lowercase.
11.print(name.firstName, name.lastName) 3. What will be the output of the following Python
Page 214 of 391 code?
81

a) Peter Pan print("abcdef".center())


Page

b) John Pan a) cd

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) abcdef d) * abcde*
c) error Answer: c
d) none of the mentioned Explanation: Padding is done towards the right-
Answer: c hand-side first when the final string is
Explanation: The function center() takes at least one of even length.
parameter. 8. What will be the output of the following Python
4. What will be the output of the following Python code?
code? print("abcdef".center(7, 1))
print("abcdef".center(0)) a) 1abcdef
a) cd b) abcdef1
b) abcdef c) abcdef
c) error d) error
d) none of the mentioned Answer: d
Answer: b Explanation: TypeError, the fill character must be a
Explanation: The entire string is printed when the character, not an int.
argument passed to center() is less 9. What will be the output of the following Python
than the length of the string. code?
5. What will be the output of the following Python print("abcdef".center(7, '1'))
code? a) 1abcdef
print('*', "abcdef".center(7), '*') b) abcdef1
Page 216 of 391 c) abcdef
a) * abcdef * Page 217 of 391
b) * abcdef * d) error
c) *abcdef * Answer: a
d) * abcdef* Explanation: The character ‘1’ is used for padding
Answer: b instead of a space.
Explanation: Padding is done towards the left-hand- 10. What will be the output of the following Python
side first when the final string is of code?
odd length. Extra spaces are present since we print("abcdef".center(10, '12'))
haven’t overridden the value of sep. a) 12abcdef12
6. What will be the output of the following Python b) abcdef1212
code? c) 1212abcdef
print('*', "abcdef".center(7), '*', sep='') d) error
a) * abcdef * Answer: d
b) * abcdef * Explanation: The fill character must be exactly one
c) *abcdef * character long.
d) * abcdef* Page 218 of 391
Answer: d Python Questions and Answers – Strings – 6
Explanation: Padding is done towards the left-hand- 1. What will be the output of the following Python
side first when the final string is of code?
odd length. print("xyyzxyzxzxyy".count('yy'))
7. What will be the output of the following Python a) 2
code? b) 0
print('*', "abcde".center(6), '*', sep='') c) error
a) * abcde * d) none of the mentioned
82

b) * abcde * Answer: a
Page

c) *abcde * Explanation: Counts the number of times the

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


substring ‘yy’ is present in the given position 11.
string. 6. What will be the output of the following Python
2. What will be the output of the following Python code?
code? print("xyyzxyzxzxyy".count('xyy', -10, -1))
print("xyyzxyzxzxyy".count('yy', 1)) a) 2
a) 2 b) 0
b) 0 c) 1
c) 1 d) error
d) none of the mentioned Answer: b
Answer: a Explanation: Counts the number of times the
Explanation: Counts the number of times the substring ‘xyy’ is present in the given
substring ‘yy’ is present in the given string, starting from position 2 and ending at
string, starting from position 1. position 11.
3. What will be the output of the following Python 7. What will be the output of the following Python
code? code?
print("xyyzxyzxzxyy".count('yy', 2)) print('abc'.encode())
a) 2 a) abc
b) 0 b) ‘abc’
c) 1 c) b’abc’
d) none of the mentioned d) h’abc’
Answer: c Answer: c
Explanation: Counts the number of times the Explanation: A bytes object is returned by encode.
substring ‘yy’ is present in the given 8. What is the default value of encoding in encode()?
string, starting from position 2. a) ascii
4. What will be the output of the following Python b) qwerty
code? c) utf-8
print("xyyzxyzxzxyy".count('xyy', 0, 100)) d) utf-16
a) 2 Answer: c
b) 0 Explanation: The default value of encoding is utf-8.
c) 1 9. What will be the output of the following Python
d) error code?
Answer: a print("xyyzxyzxzxyy".endswith("xyy"))
Explanation: An error will not occur if the end value a) 1
is greater than the length of the b) True
string itself. c) 3
5. What will be the output of the following Python d) 2
code? Page 220 of 391
Page 219 of 391 Answer: b
print("xyyzxyzxzxyy".count('xyy', 2, 11)) Explanation: The function returns True if the given
a) 2 string ends with the specified
b) 0 substring.
c) 1 10. What will be the output of the following Python
d) error code?
Answer: b print("xyyzxyzxzxyy".endswith("xyy", 0, 2))
Explanation: Counts the number of times the a) 0
83

substring ‘xyy’ is present in the given b) 1


Page

string, starting from position 2 and ending at c) True

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) False Page 222 of 391
Answer: d 6. Suppose list1 is [1, 5, 9], what is sum(list1)?
Explanation: The function returns False if the given a) 1
string does not end with the b) 9
specified substring c) 15
Page 221 of 391 d) Error
Python Questions and Answers – Lists – 1 Answer: c
1. Which of the following commands will create a Explanation: Sum returns the sum of all elements in
list? the list.
a) list1 = list() 7. To shuffle the list(say list1) what function do we
b) list1 = [] use?
c) list1 = list([1, 2, 3]) a) list1.shuffle()
d) all of the mentioned b) shuffle(list1)
Answer: d c) random.shuffle(list1)
Explanation: Execute in the shell to verify d) random.shuffleList(list1)
2. What is the output when we execute list(“hello”)? Answer: c
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] Explanation: Execute in the shell to verify.
b) [‘hello’] 8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the
c) [‘llo’] following is correct syntax for slicing
d) [‘olleh’] operation?
Answer: a a) print(list1[0])
Explanation: Execute in the shell to verify. b) print(list1[:2])
3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is c) print(list1[:-2])
len(listExample)? d) all of the mentioned
a) 5 Answer: d
b) 4 Explanation: Slicing is allowed in lists just as in the
c) None case of strings.
d) Error 9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-
Answer: a 1]?
Explanation: Execute in the shell and verify. a) Error
4. Suppose list1 is [2445,133,12454,123], what is b) None
max(list1)? c) 25
a) 2445 d) 2
b) 133 Answer: c
c) 12454 Explanation: -1 corresponds to the last index in the
d) 123 list.
Answer: c 10. Suppose list1 is [2, 33, 222, 14, 25], What is
Explanation: Max returns the maximum element in list1[:-1]?
the list. a) [2, 33, 222, 14]
5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)? b) Error
a) 3 c) 25
b) 5 d) [25, 14, 222, 33, 2]
c) 25 Answer: a
d) 1 Explanation: Execute in the shell to verify.
Answer: d Page 223 of 391
84

Explanation: Min returns the minimum element in Page 224 of 391


Page

the list. Python Questions and Answers – Lists – 2

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


1. What will be the output of the following Python 4. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:
code? a) [0, 1, 2, 3]
1. >>>names = ['Amir', 'Bear', 'Charlton', 'Daman'] b) [0, 1, 2, 3, 4]
2. >>>print(names[-1][-1]) c) [0.0, 0.5, 1.0, 1.5]
a) A d) [0.0, 0.5, 1.0, 1.5, 2.0]
b) Daman Answer: c
c) Error Explanation: Execute in the shell to verify.
d) n 5. What will be the output of the following Python
Answer: d code?
Explanation: Execute in the shell to verify. 1. >>>list1 = [11, 2, 23]
2. What will be the output of the following Python 2. >>>list2 = [11, 2, 2]
code? 3. >>>list1 < list2 is
1. names1 = ['Amir', 'Bear', 'Charlton', 'Daman'] a) True
2. names2 = names1 b) False
3. names3 = names1[:] c) Error
4. d) None
5. names2[0] = 'Alice' Answer: b
6. names3[1] = 'Bob' Explanation: Elements are compared one by one.
7. 6. To add a new element to a list we use which
8. sum = 0 command?
9. for ls in (names1, names2, names3): a) list1.add(5)
10. if ls[0] == 'Alice': b) list1.append(5)
11. sum += 1 c) list1.addLast(5)
12. if ls[1] == 'Bob': d) list1.addEnd(5)
13. sum += 10 Answer: b
14. Explanation: We use the function append to add an
15.print sum element to the list.
a) 11 7. To insert 5 to the third position in list1, we use
b) 12 which command?
c) 21 a) list1.insert(3, 5)
d) 22 b) list1.insert(2, 5)
Answer: b c) list1.add(3, 5)
Explanation: When assigning names1 to names2, we d) list1.append(3, 5)
create a second reference to the Answer: b
same list. Changes to names2 affect names1. When Explanation: Execute in the shell to verify.
assigning the slice of all elements in 8. To remove string “hello” from list1, we use which
names1 to names3, we are creating a full copy of command?
names1 which can be modified a) list1.remove(“hello”)
independently. b) list1.remove(hello)
3. Suppose list1 is [1, 3, 2], What is list1 * 2? c) list1.removeAll(“hello”)
a) [2, 6, 4] Page 226 of 391
b) [1, 3, 2, 1, 3] d) list1.removeOne(“hello”)
c) [1, 3, 2, 1, 3, 2] Answer: a
d) [1, 3, 2, 3, 2, 1] Explanation: Execute in the shell to verify.
Page 225 of 391 9. Suppose list1 is [3, 4, 5, 20, 5], what is
85

Answer: c list1.index(5)?
Page

Explanation: Execute in the shell and verify. a) 0

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) 1 Answer: a
c) 4 Explanation: pop() by default will remove the last
d) 2 element.
Answer: d 5. What will be the output of the following Python
Explanation: Execute help(list.index) to get details. code?
10. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is 1. >>>"Welcome to Python".split()
list1.count(5)? a) [“Welcome”, “to”, “Python”]
a) 0 b) (“Welcome”, “to”, “Python”)
b) 4 c) {“Welcome”, “to”, “Python”}
c) 1 d) “Welcome”, “to”, “Python”
d) 2 Page 228 of 391
Answer: d Answer: a
Explanation: Execute in the shell to verify. Explanation: split() function returns the elements in
Page 227 of 391 a list.
Python Questions and Answers – Lists – 3 6. What will be the output of the following Python
1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 code?
after list1.reverse()? 1. >>>list("a#b#c#d".split('#'))
a) [3, 4, 5, 20, 5, 25, 1, 3] a) [‘a’, ‘b’, ‘c’, ‘d’]
b) [1, 3, 3, 4, 5, 5, 20, 25] b) [‘a b c d’]
c) [25, 20, 5, 5, 4, 3, 3, 1] c) [‘a#b#c#d’]
d) [3, 1, 25, 5, 20, 5, 4, 3] d) [‘abcd’]
Answer: d Answer: a
Explanation: Execute in the shell to verify. Explanation: Execute in the shell to verify.
2. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], 7. What will be the output of the following Python
what is list1 after listExample.extend([34, code?
5])? 1. myList = [1, 5, 5, 5, 5, 1]
a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5] 2. max = myList[0]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5] 3. indexOfMax = 0
c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5] 4. for i in range(1, len(myList)):
d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5] 5. if myList[i] > max:
Answer: a 6. max = myList[i]
Explanation: Execute in the shell to verify. 7. indexOfMax = i
3. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], 8.
what is list1 after listExample.pop(1)? 9. >>>print(indexOfMax)
a) [3, 4, 5, 20, 5, 25, 1, 3] a) 1
b) [1, 3, 3, 4, 5, 5, 20, 25] b) 2
c) [3, 5, 20, 5, 25, 1, 3] c) 3
d) [1, 3, 4, 5, 20, 5, 25] d) 4
Answer: c Answer: a
Explanation: pop() removes the element at the Explanation: First time the highest number is
position specified in the parameter. encountered is at index 1.
4. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3], 8. What will be the output of the following Python
what is list1 after listExample.pop()? code?
a) [3, 4, 5, 20, 5, 25, 1] 1. myList = [1, 2, 3, 4, 5, 6]
b) [1, 3, 3, 4, 5, 5, 20, 25] 2. for i in range(1, 6):
86

c) [3, 5, 20, 5, 25, 1, 3] 3. myList[i - 1] = myList[i]


Page

d) [1, 3, 4, 5, 20, 5, 25] 4.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


5. for i in range(0, 6): 8. print(v)
6. print(myList[i], end = " ") a) [1] [2] [3]
a) 2 3 4 5 6 1 b) [1] [1, 2] [1, 2, 3]
b) 6 1 2 3 4 5 c) [1, 2, 3]
c) 2 3 4 5 6 6 d) 1 2 3
d) 1 1 2 3 4 5 Answer: c
Answer: c Explanation: Execute in the shell to verify
Explanation: Execute in the shell to verify. 2. What will be the output of the following Python
9. What will be the output of the following Python code?
code? 1. names1 = ['Amir', 'Bala', 'Chales']
Page 229 of 391 2.
1. >>>list1 = [1, 3] 3. if 'amir' in names1:
2. >>>list2 = list1 4. print(1)
3. >>>list1[0] = 4 5. else:
4. >>>print(list2) 6. print(2)
a) [1, 3] a) None
b) [4, 3] b) 1
c) [1, 4] c) 2
d) [1, 3, 4] d) Error
Answer: b Answer: c
Explanation: Lists should be copied by executing [:] Explanation: Execute in the shell to verify.
operation. 3. What will be the output of the following Python
10. What will be the output of the following Python code?
code? 1. names1 = ['Amir', 'Bala', 'Charlie']
1. def f(values): 2. names2 = [name.lower() for name in names1]
2. values[0] = 44 3.
3. 4. print(names2[2][0])
4. v = [1, 2, 3] a) None
5. f(v) b) a
6. print(v) c) b
a) [1, 44] d) c
b) [1, 2, 3, 44] Answer: d
c) [44, 2, 3] Explanation: List Comprehension are a shorthand
d) [1, 2, 3] for creating new lists.
Answer: c Page 231 of 391
Explanation: Execute in the shell to verify. 4. What will be the output of the following Python
Page 230 of 391 code?
Python Questions and Answers – Lists – 4 1. numbers = [1, 2, 3, 4]
1. What will be the output of the following Python 2.
code? 3. numbers.append([5,6,7,8])
1. def f(i, values = []): 4.
2. values.append(i) 5. print(len(numbers))
3. return values a) 4
4. b) 5
5. f(1) c) 8
87

6. f(2) d) 12
Page

7. v = f(3) Answer: b

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: A list is passed in append so the length 8. print(increment_items(values, 2))
is 5. 9. print(values)
5. To which of the following the “in” operator can be a)
used to check if an item is in it? None
a) Lists [3, 4, 5]
b) Dictionary b)
c) Set None
d) All of the mentioned [1, 2, 3]
Answer: d c)
Explanation: In can be used in all data structures. [3, 4, 5]
6. What will be the output of the following Python [1, 2, 3]
code? d)
1. list1 = [1, 2, 3, 4] [3, 4, 5]
2. list2 = [5, 6, 7, 8] None
3. Answer: a
4. print(len(list1 + list2)) Explanation: Execute in the shell to verify.
a) 2 9. What will be the output of the following Python
b) 4 code?
c) 5 1. def example(L):
d) 8 2. ''' (list) -> list
Answer: d 3. '''
Explanation: + appends all the elements individually 4. i = 0
into a new list. 5. result = []
7. What will be the output of the following Python 6. while i < len(L):
code? 7. result.append(L[i])
1. def addItem(listParam): 8. i = i + 3
2. listParam += [1] 9. return result
3. a) Return a list containing every third item from L
4. mylist = [1, 2, 3, 4] starting at index 0
5. addItem(mylist) b) Return an empty list
6. print(len(mylist)) c) Return a list containing every third index from L
a) 1 starting at index 0
b) 4 d) Return a list containing the items from L starting
c) 5 from index 0, omitting every third item
Page 232 of 391 Page 233 of 391
d) 8 Answer: a
Answer: c Explanation: Run the code to get a better
Explanation: + will append the element to the list. understanding with many arguments.
8. What will be the output of the following Python 10. What will be the output of the following Python
code? code?
1. def increment_items(L, increment): 1. veggies = ['carrot', 'broccoli', 'potato', 'asparagus']
2. i = 0 2. veggies.insert(veggies.index('broccoli'), 'celery')
3. while i < len(L): 3. print(veggies)
4. L[i] = L[i] + increment a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, ‘asparagus’]
5. i = i + 1 Correct 1.00
88

6. b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’]


Page

7. values = [1, 2, 3] c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’, ‘asparagus’]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’, ‘asparagus’] Page 235 of 391
Answer: a 7. v = element
Explanation: Execute in the shell to verify. 8.
Page 234 of 391 9. print(v)
Python Questions and Answers – Lists – 5 a) 1
1. What will be the output of the following Python b) 3
code? c) 5
1. >>>m = [[x, x + 1, x + 2] for x in range(0, 3)] d) 6
a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Answer: a
b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]] Explanation: Execute in the shell to verify.
c) [1, 2, 3, 4, 5, 6, 7, 8, 9] 5. What will be the output of the following Python
d) [0, 1, 2, 1, 2, 3, 2, 3, 4] code?
Answer: b 1. values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]
Explanation: Execute in the shell to verify. 2.
2. How many elements are in m? 3. for row in values:
1. m = [[x, y] for x in range(0, 4) for y in range(0, 4)] 4. row.sort()
a) 8 5. for element in row:
b) 12 6. print(element, end = " ")
c) 16 7. print()
d) 32 a) The program prints two rows 3 4 5 1 followed by
Answer: c 33 6 1 2
Explanation: Execute in the shell to verify. b) The program prints on row 3 4 5 1 33 6 1 2
3. What will be the output of the following Python c) The program prints two rows 3 4 5 1 followed by
code? 33 6 1 2
1. values = [[3, 4, 5, 1], [33, 6, 1, 2]] d) The program prints two rows 1 3 4 5 followed by 1
2. 2 6 33
3. v = values[0][0] Answer: d
4. for row in range(0, len(values)): Explanation: Execute in the shell to verify.
5. for column in range(0, len(values[row])): 6. What will be the output of the following Python
6. if v < values[row][column]: code?
7. v = values[row][column] 1. matrix = [[1, 2, 3, 4],
8. 2. [4, 5, 6, 7],
9. print(v) 3. [8, 9, 10, 11],
a) 3 4. [12, 13, 14, 15]]
b) 5 5.
c) 6 6. for i in range(0, 4):
d) 33 7. print(matrix[i][1], end = " ")
Answer: d a) 1 2 3 4
Explanation: Execute in the shell to verify. b) 4 5 6 7
4. What will be the output of the following Python c) 1 3 8 12
code? d) 2 5 9 13
1. values = [[3, 4, 5, 1], [33, 6, 1, 2]] Answer: d
2. Explanation: Execute in the shell to verify.
3. v = values[0][0] 7. What will be the output of the following Python
4. for lst in values: code?
89

5. for element in lst: 1. def m(list):


Page

6. if v > element: 2. v = list[0]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


3. for e in list: code?
1. points = [[1, 2], [3, 1.5], [0.5, 0.5]]
4. if v < e: v = e 2. points.sort()
5. return v 3. print(points)
6. a) [[1, 2], [3, 1.5], [0.5, 0.5]]
7. values = [[3, 4, 5, 1], [33, 6, 1, 2]] b) [[3, 1.5], [1, 2], [0.5, 0.5]]
8. c) [[0.5, 0.5], [1, 2], [3, 1.5]]
9. for row in values: d) [[0.5, 0.5], [3, 1.5], [1, 2]]
10. print(m(row), end = " ") Answer: c
a) 3 33 Explanation: Execute in the shell to verify.
b) 1 1
c) 5 6 Python Questions and Answers – Lists – 6
d) 5 33 1. What will be the output of the following Python
Answer: d code?
Explanation: Execute in the shell to verify. a=[10,23,56,[78]]
8. What will be the output of the following Python b=list(a)
code? a[3][0]=95
1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] a[1]=34
2. print(b)
3. print(data[1][0][0]) a) [10,34,56,[95]]
a) 1 b) [10,23,56,[78]]
b) 2 c) [10,23,56,[95]]
c) 4 d) [10,34,56,[78]]
d) 5 Answer: c
Answer: d Explanation: The above copy is a type of shallow
Explanation: Execute in the shell to verify. copy and only changes made in sublist
9. What will be the output of the following Python is reflected in the copied list.
code? 2. What will be the output of the following Python
1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] code?
2. print(list(zip((1,2,3),('a'),('xxx','yyy'))))
3. def ttt(m): print(list(zip((2,4),('b','c'),('yy','xx'))))
4. v = m[0][0] a)
5. [(1,2,3),(‘a’),(‘xxx’,’yyy’)]
6. for row in m: [(2,4),(‘b’,’c’),(‘yy’,’xx’)]
7. for element in row: b)
8. if v < element: v = element [(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’ ‘)]
9. [(2, 'b', 'yy'), (4, 'c', 'xx')]
10. return v c) Syntax error
11. d)
12.print(ttt(data[0])) [(1, 'a', 'xxx')]
a) 1 [(2, 'b', 'yy'), (4, 'c', 'xx')]
b) 2 Answer: d
c) 4 Explanation: The zip function combines the
d) 5 individual attributes of the lists into a list
Answer: c of tuples.
90

Explanation: Execute in the shell to verify. 3. What will be the output of the following Python
Page

10. What will be the output of the following Python code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


import copy c) 4
a=[10,23,56,[78]] d) [1,3,6,10]
b=copy.deepcopy(a) Answer: d
a[3][0]=95 Explanation: The above code returns the cumulative
a[1]=34 sum of elements in a list.
print(b) 6. What will be the output of the following Python
a) [10,34,56,[95]] code?
b) [10,23,56,[78]] a="hello"
c) [10,23,56,[95]] b=list((x.upper(),len(x)) for x in a)
d) [10,34,56,[78]] print(b)
Page 239 of 391 a) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
Answer: b b) [(‘HELLO’, 5)]
Explanation: The above copy is deepcopy. Any c) [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
change made in the original list isn’t Page 240 of 391
reflected. d) Syntax error
4. What will be the output of the following Python Answer: a
code? Explanation: Variable x iterates over each letter in
s="a@b@c@d" string a hence the length of each
a=list(s.partition("@")) letter is 1.
print(a) 7. What will be the output of the following Python
b=list(s.split("@",3)) code?
print(b) a=[1,2,3,4]
a) b=[sum(a[0:x+1]) for x in range(0,len(a))]
[‘a’,’b’,’c’,’d’] print(b)
[‘a’,’b’,’c’,’d’] a) 10
b) b) [1,3,5,7]
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’] c) 4
[‘a’,’b’,’c’,’d’] d) [1,3,6,10]
c) Answer: d
[‘a’,’@’,’b@c@d’] Explanation: The above code returns the cumulative
[‘a’,’b’,’c’,’d’] sum of elements in a list.
d) 8. What will be the output of the following Python
[‘a’,’@’,’b@c@d’] code?
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’] a=[[]]*3
Answer: c a[1].append(7)
Explanation: The partition function only splits for print(a)
the first parameter along with the a) Syntax error
separator while split function splits for the number b) [[7], [7], [7]]
of times given in the second c) [[7], [], []]
argument but without the separator. d) [[],7, [], []]
5. What will be the output of the following Python Answer: b
code? Explanation: The first line of the code creates
a=[1,2,3,4] multiple reference copies of sublist.
b=[sum(a[0:x+1]) for x in range(0,len(a))] Hence when 7 is appended, it gets appended to all
print(b) the sublists.
91

a) 10 9. What will be the output of the following Python


Page

b) [1,3,5,7] code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b=[2,3,4,5] None.
a=list(filter(lambda x:x%2,b)) 2. What will be the output of the following Python
print(a) code?
a) [2,4] >>> a=[14,52,7]
b) [ ] >>>> b=a.copy()
c) [3,5] >>> b is a
d) Invalid arguments for filter function a) True
Answer: c b) False
Explanation: The filter function gives value from the Answer: b
list b for which the condition is Explanation: List b is just a copy of the original list.
true, that is, x%2==1. Any copy made in list b will not be
10. What will be the output of the following Python reflected in list a.
code? 3. What will be the output of the following Python
lst=[3,4,6,1,2] code?
lst[1:2]=[7,8] a=[13,56,17]
Page 241 of 391 a.append([87])
print(lst) a.extend([45,67])
a) [3, 7, 8, 6, 1, 2] print(a)
b) Syntax error a) [13, 56, 17, [87], 45, 67]
c) [3,[7,8],6,1,2] b) [13, 56, 17, 87, 45, 67]
d) [3,4,6,7,8] c) [13, 56, 17, 87,[ 45, 67]]
Answer: a d) [13, 56, 17, [87], [45, 67]]
Explanation: In the piece of code, slice assignment Answer: a
has been implemented. The sliced Explanation: The append function simply adds its
list is replaced by the assigned elements in the list. arguments to the list as it is while
Type in python shell to verify. extend function extends its arguments and later
Page 242 of 391 appends it.
Python Questions and Answers – Lists – 7 Page 243 of 391
1. What will be the output of the following Python 4. What is the output of the following piece of code?
code? a=list((45,)*4)
a=[1,2,3] print((45)*4)
b=a.append(4) print(a)
print(a) a)
print(b) 180
a) [(45),(45),(45),(45)]
[1,2,3,4] b)
[1,2,3,4] (45,45,45,45)
b) [45,45,45,45]
[1, 2, 3, 4] c)
None 180
c) Syntax error [45,45,45,45]
d) d) Syntax error
[1,2,3] Answer: c
[1,2,3,4] Explanation: (45) is an int while (45,) is a tuple of
Answer: b one element. Thus when a tuple is
92

Explanation: Append function on lists doesn’t return multiplied, it created references of itself which is
Page

anything. Thus the value of b is later converted to a list.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


5. What will be the output of the following Python Explanation: unpack(*x) unpacks the list into the
code? separate variables. Now, a=1 and
lst=[[1,2],[3,4]] d=4. Thus 5 gets printed.
print(sum(lst,[])) 8. What will be the output of the following Python
a) [[3],[7]] code?
b) [1,2,3,4] places = ['Bangalore', 'Mumbai', 'Delhi']
c) Error <br class="blank" />places1 = places
d) [10] places2 = places[:]
Answer: b <br class="blank" />places1[1]="Pune"
Explanation: The above piece of code is used for places2[2]="Hyderabad"
flattening lists. print(places)
6. What will be the output of the following Python a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
code? b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
word1="Apple" c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
word2="Apple" d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
list1=[1,2,3] Answer: b
list2=[1,2,3] Explanation: places1 is an alias of the list places.
print(word1 is word2) Hence, any change made to places1 is
print(list1 is list2) reflected in places. places2 is a copy of the list
a) places. Thus, any change made to places2
True isn’t reflected in places.
True 9. What will be the output of the following Python
b) code?
False x=[[1],[2]]
True print(" ".join(list(map(str,x))))
c) a) [1] [2]
False b) [49] [50]
False c) Syntax error
d) d) [[1]] [[2]]
Page 244 of 391 Page 245 of 391
True Answer: a
False Explanation: The elements 1 and 2 are first put into
Answer: d separate lists and then combined
Explanation: In the above case, both the lists are with a space in between using the join attribute.
equivalent but not identical as they 10. What will be the output of the following Python
have different objects. code?
7. What will be the output of the following Python a=165
code? b=sum(list(map(int,str(a))))
def unpack(a,b,c,d): print(b)
print(a+d) a) 561
x = [1,2,3,4] b) 5
unpack(*x) c) 12
a) Error d) Syntax error
b) [1,4] Answer: c
c) [5] Explanation: First, map converts the number to
93

d) 5 string and then places the individual


Page

Answer: d digits in a list. Then, sum finds the sum of the digits

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


in the list. The code basically finds code?
the sum of digits in the number. a = [1, 5, 7, 9, 9, 1]
11. What will be the output of the following Python <br class="blank" />b=a[0]
code? <br class="blank" />x= 0
a= [1, 2, 3, 4, 5] for x in range(1, len(a)):
for i in range(1, 5): if a[x] > b:
a[i-1] = a[i] b = a[x]
for i in range(0, 5): b= x
print(a[i],end = " ") print(b)
a) 5 5 1 2 3 a) 5
b) 5 1 2 3 4 b) 3
c) 2 3 4 5 1 c) 4
d) 2 3 4 5 5 d) 0
Answer: d Answer: c
Explanation: The items having indexes from 1 to 4 Explanation: The above piece of code basically
are shifted forward by one index prints the index of the largest element in
due to the first for-loop and the item of index four the list.
is printed again because of the 14. What will be the output of the following Python
second for-loop. code?
12. What will be the output of the following Python a=["Apple","Ball","Cobra"]
code? <br class="blank" />a.sort(key=len)
def change(var, lst): print(a)
var = 1 a) [‘Apple’, ‘Ball’, ‘Cobra’]
lst[0] = 44 b) [‘Ball’, ‘Apple’, ‘Cobra’]
k=3 c) [‘Cobra’, ‘Apple’, ‘Ball’]
a = [1, 2, 3] d) Invalid syntax for sort()
change(k, a) Answer: b
print(k) Explanation: The syntax isn’t invalid and the list is
print(a) sorted according to the length of the
a) strings in the list since key is given as len.
3 15. What will be the output of the following Python
[44, 2, 3] code?
b) num = ['One', 'Two', 'Three']
Page 246 of 391 for i, x in enumerate(num):
1 Page 247 of 391
[1,2,3] print('{}: {}'.format(i, x),end=" ")
c) a) 1: 2: 3:
3 b) Exception is thrown
[1,2,3] c) One Two Three
d) d) 0: One 1: Two 2: Three
1 Answer: d
[44,2,3] Explanation: enumerate(iterator,start=0) is a built-
Answer: a in function which returns
Explanation: A list is mutable, hence it’s value (0,lst[0]),(1,lst[1]) and so on where lst is a
changes after function call. However, list(iterator).
94

integer isn’t mutable. Thus its value doesn’t change. Page 248 of 391
Page

13. What will be the output of the following Python Python Questions and Answers – Tuples – 1

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


1. Which of the following is a Python tuple? d) (1, 4, 8)
a) [1, 2, 3] Answer: c
b) (1, 2, 3) Explanation: Execute in the shell to verify.
c) {1, 2, 3} 6. What will be the output of the following Python
d) {} code?
Answer: b 1. d = {"john":40, "peter":45}
Explanation: Tuples are represented with round 2. d["john"]
brackets. a) 40
2. Suppose t = (1, 2, 4, 3), which of the following is b) 45
incorrect? c) “john”
a) print(t[3]) d) “peter”
b) t[3] = 45 Answer: a
c) print(max(t)) Explanation: Execute in the shell to verify.
d) print(len(t)) 7. What will be the output of the following Python
Answer: b code?
Explanation: Values cannot be modified in the case 1. >>>t = (1, 2)
of tuple, that is, tuple is immutable. 2. >>>2 * t
3. What will be the output of the following Python a) (1, 2, 1, 2)
code? b) [1, 2, 1, 2]
1. >>>t=(1,2,4,3) c) (1, 1, 2, 2)
2. >>>t[1:3] d) [1, 1, 2, 2]
a) (1, 2) Answer: a
b) (1, 2, 4) Explanation: * operator concatenates tuple.
c) (2, 4) 8. What will be the output of the following Python
d) (2, 4, 3) code?
Answer: c 1. >>>t1 = (1, 2, 4, 3)
Explanation: Slicing in tuples takes place just as it 2. >>>t2 = (1, 2, 3, 4)
does in strings. 3. >>>t1 < t2
4. What will be the output of the following Python a) True
code? b) False
1. >>>t=(1,2,4,3) c) Error
2. >>>t[1:-1] d) None
a) (1, 2) Answer: b
b) (1, 2, 4) Explanation: Elements are compared one by one in
c) (2, 4) this case.
d) (2, 4, 3) 9. What will be the output of the following Python
Answer: c code?
Explanation: Slicing in tuples takes place just as it 1. >>>my_tuple = (1, 2, 3, 4)
does in strings. 2. >>>my_tuple.append( (5, 6, 7) )
5. What will be the output of the following Python 3. >>>print len(my_tuple)
code? a) 1
1. >>>t = (1, 2, 4, 3, 8, 9) b) 2
2. >>>[t[i] for i in range(0, len(t), 2)] c) 5
a) [2, 3, 9] Page 250 of 391
b) [1, 2, 4, 3, 8, 9] d) Error
95

Page 249 of 391 Answer: d


Page

c) [1, 4, 8] Explanation: Tuples are immutable and don’t have

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


an append method. An exception is c) Error, < operator is not valid for tuples
thrown in this case. d) Error, < operator is valid for tuples but not if there
10. What will be the output of the following Python are sub-tuples
code? Answer: a
2. numberGames = {} Explanation: Since the first element in the sub-tuple
3. numberGames[(1,2,4)] = 8 of a is larger that the first element
4. numberGames[(4,2,1)] = 10 in the subtuple of b, False is printed.
5. numberGames[(1,2)] = 12 4. What will be the output of the following Python
6. sum = 0 code?
7. for k in numberGames: >>> a=("Check")*3
8. sum += numberGames[k] >>> a
9. print len(numberGames) + sum a) (‘Check’,’Check’,’Check’)
a) 30 b) * Operator not valid for tuples
b) 24 c) (‘CheckCheckCheck’)
c) 33 d) Syntax error
d) 12 Answer: c
Answer: c Explanation: Here (“Check”) is a string not a tuple
Explanation: Tuples can be used for keys into because there is no comma after the
dictionary. The tuples can have mixed element.
length and the order of the items in the tuple is 5. What will be the output of the following Python
considered when comparing the code?
equality of the keys. >>> a=(1,2,3,4)
Page 251 of 391 Page 252 of 391
Python Questions and Answers – Tuples – 2 >>> del(a[2])
1. What is the data type of (1)? a) Now, a=(1,2,4)
a) Tuple b) Now, a=(1,3,4)
b) Integer c) Now a=(3,4)
c) List d) Error as tuple is immutable
d) Both tuple and integer Answer: d
Answer: b Explanation: ‘tuple’ object doesn’t support item
Explanation: A tuple of one element must be deletion.
created as (1,). 6. What will be the output of the following Python
2. If a=(1,2,3,4), a[1:-1] is _________ code?
a) Error, tuple slicing doesn’t exist >>> a=(2,3,4)
b) [2,3] >>> sum(a,3)
c) (2,3,4) a) Too many arguments for sum() method
d) (2,3) b) The method sum() doesn’t exist for tuples
Answer: d c) 12
Explanation: Tuple slicing exists and a[1:-1] returns d) 9
(2,3). Answer: c
3. What will be the output of the following Python Explanation: In the above case, 3 is the starting
code? value to which the sum of the tuple is
>>> a=(1,2,(4,5)) added to.
>>> b=(1,2,(3,4)) 7. Is the following Python code valid?
>>> a<b >>> a=(1,2,3,4)
96

a) False >>> del a


Page

b) True a) No because tuple is immutable

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) Yes, first element in the tuple is deleted c) Yes, (1,2,3) is printed
c) Yes, the entire tuple is deleted d) 1 is printed
d) No, invalid syntax for del method Answer: c
Answer: c Explanation: A tuple needn’t be enclosed in
Explanation: The command del a deletes the entire parenthesis.
tuple. 2. What will be the output of the following Python
8. What type of data is: a=[(1,1),(2,4),(3,9)]? code?
a) Array of tuples a = ('check',)
b) List of tuples n=2
c) Tuples of lists for i in range(int(n)):
d) Invalid type a = (a,)
Answer: b print(a)
Explanation: The variable a has tuples enclosed in a a) Error, tuples are immutable
list making it a list of tuples. b)
9. What will be the output of the following Python (('check',),)
code? ((('check',),),)
>>> a=(0,1,2,3,4) c) ((‘check’,)’check’,)
>>> b=slice(0,2) d)
>>> a[b] (('check',)’check’,)
a) Invalid syntax for slicing ((('check',)’check’,)’check’,)
b) [0,2] Answer: b
Page 253 of 391 Explanation: The loop runs two times and each time
c) (0,1) the loop runs an extra parenthesis
d) (0,2) along with a comma is added to the tuple (as
Answer: c a=(a’)).
Explanation: The method illustrated in the above 3. Is the following Python code valid?
piece of code is that of naming of >>> a,b=1,2,3
slices. a) Yes, this is an example of tuple unpacking. a=1 and
10. Is the following Python code valid? b=2
>>> a=(1,2,3) b) Yes, this is an example of tuple unpacking. a=(1,2)
>>> b=('A','B','C') and b=3
>>> c=tuple(zip(a,b)) c) No, too many values to unpack
a) Yes, c will be ((1, ‘A’), (2, ‘B’), (3, ‘C’)) d) Yes, this is an example of tuple unpacking. a=1 and
b) Yes, c will be ((1,2,3),(‘A’,’B’,’C’)) b=(2,3)
c) No because tuples are immutable Answer: c
d) No because the syntax for zip function isn’t valid Explanation: For unpacking to happen, the number
Answer: a of values of the right hand side
Explanation: Zip function combines individual must be equal to the number of variables on the left
elements of two iterables into tuples. hand side.
Execute in Python shell to verify. 4. What will be the output of the following Python
Page 254 of 391 code?
Python Questions and Answers – Tuples-3 >>> a=(1,2)
1. Is the following Python code valid? >>> b=(3,4)
>>> a,b,c=1,2,3 >>> c=a+b
>>> a,b,c Page 255 of 391
97

a) Yes, [1,2,3] is printed >>> c


Page

b) No, invalid syntax a) (4,6)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


b) (1,2,3,4) Explanation: A tuple needn’t be enclosed in
c) Error as tuples are immutable parenthesis.
d) None 9. What will be the output of the following Python
Answer: b code?
Explanation: In the above piece of code, the values >>> a=(2,3,1,5)
of the tuples aren’t being changed. >>> a.sort()
Both the tuples are simply concatenated. >>> a
5. What will be the output of the following Python a) (1,2,3,5)
code? b) (2,3,1,5)
>>> a,b=6,7 c) None
>>> a,b=b,a d) Error, tuple has no attribute sort
>>> a,b Answer: d
a) (6,7) Explanation: A tuple is immutable thus it doesn’t
b) Invalid syntax have a sort attribute.
c) (7,6) 10. Is the following Python code valid?
d) Nothing is printed >>> a=(1,2,3)
Answer: c >>> b=a.update(4,)
Explanation: The above piece of code illustrates the a) Yes, a=(1,2,3,4) and b=(1,2,3,4)
unpacking of variables. b) Yes, a=(1,2,3) and b=(1,2,3,4)
6. What will be the output of the following Python c) No because tuples are immutable
code? d) No because wrong syntax for update() method
>>> import collections Answer: c
>>> a=collections.namedtuple('a',['i','j']) Explanation: Tuple doesn’t have any update()
>>> obj=a(i=4,j=7) attribute because it is immutable.
>>> obj 11. What will be the output of the following Python
a) a(i=4, j=7) code?
b) obj(i=4, j=7) >>> a=[(2,4),(1,2),(3,9)]
c) (4,7) >>> a.sort()
d) An exception is thrown >>> a
Answer: a a) [(1, 2), (2, 4), (3, 9)]
Explanation: The above piece of code illustrates the b) [(2,4),(1,2),(3,9)]
concept of named tuples. c) Error because tuples are immutable
7. Tuples can’t be made keys of a dictionary. d) Error, tuple has no sort attribute
a) True Answer: a
b) False Explanation: A list of tuples is a list itself. Hence
Answer: b items of a list can be sorted.
Explanation: Tuples can be made keys of a Page 257 of 391
dictionary because they are hashable. Python Questions and Answers – Dictionary – 1
8. Is the following Python code valid? 1. Which of the following statements create a
>>> a=2,3,4,5 dictionary?
>>> a a) d = {}
a) Yes, 2 is printed b) d = {“john”:40, “peter”:45}
b) Yes, [2,3,4,5] is printed c) d = {40:”john”, 45:”peter”}
Page 256 of 391 d) All of the mentioned
c) No, too many values to unpack Answer: d
98

d) Yes, (2,3,4,5) is printed Explanation: Dictionaries are created by specifying


Page

Answer: d keys and values.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


2. What will be the output of the following Python code snippet?
code snippet? 1. d = {"john":40, "peter":45}
1. d = {"john":40, "peter":45} 2. d["john"]
a) “john”, 40, 45, and “peter” a) 40
b) “john” and “peter” b) 45
c) 40 and 45 c) “john”
d) d = (40:”john”, 45:”peter”) d) “peter”
Answer: b Answer: a
Explanation: Dictionaries appear in the form of keys Explanation: Execute in the shell to verify.
and values. 7. Suppose d = {“john”:40, “peter”:45}, to delete the
3. What will be the output of the following Python entry for “john” what command do we
code snippet? use?
1. d = {"john":40, "peter":45} a) d.delete(“john”:40)
2. "john" in d b) d.delete(“john”)
a) True c) del d[“john”]
b) False d) del d(“john”:40)
c) None Answer: c
d) Error Explanation: Execute in the shell to verify.
Answer: a 8. Suppose d = {“john”:40, “peter”:45}. To obtain the
Explanation: In can be used to check if the key is int number of entries in dictionary which
dictionary. command do we use?
4. What will be the output of the following Python a) d.size()
code snippet? b) len(d)
1. d1 = {"john":40, "peter":45} c) size(d)
2. d2 = {"john":466, "peter":45} d) d.len()
3. d1 == d2 Answer: b
a) True Explanation: Execute in the shell to verify.
b) False 9. What will be the output of the following Python
c) None code snippet?
d) Error 1. d = {"john":40, "peter":45}
Answer: b 2. print(list(d.keys()))
Explanation: If d2 was initialized as d2 = d1 the a) [“john”, “peter”]
answer would be true. b) [“john”:40, “peter”:45]
5. What will be the output of the following Python c) (“john”, “peter”)
code snippet? Page 259 of 391
1. d1 = {"john":40, "peter":45} d) (“john”:40, “peter”:45)
2. d2 = {"john":466, "peter":45} Answer: a
Page 258 of 391 Explanation: The output of the code shown above is
3. d1 > d2 a list containing only keys of the
a) True dictionary d, in the form of a list.
b) False 10. Suppose d = {“john”:40, “peter”:45}, what
c) Error happens when we try to retrieve a value using
d) None the expression d[“susan”]?
Answer: c a) Since “susan” is not a value in the set, Python
Explanation: Arithmetic > operator cannot be used raises a KeyError exception
99

with dictionaries. b) It is executed fine and no exception is raised, and


Page

6. What will be the output of the following Python it returns None

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) Since “susan” is not a key in the set, Python raises d) Invalid syntax for get method
a KeyError exception Answer: b
d) Since “susan” is not a key in the set, Python raises Explanation: The get() method returns the value of
a syntax error the key if the key is present in the
Answer: c dictionary and the default value(second parameter)
Explanation: Execute in the shell to verify. if the key isn’t present in the
Page 260 of 391 dictionary.
Python Questions and Answers – Dictionary – 2 Page 261 of 391
1. Which of these about a dictionary is false? 5. What will be the output of the following Python
a) The values of a dictionary can be accessed using code snippet?
keys a={1:"A",2:"B",3:"C"}
b) The keys of a dictionary can be accessed using print(a.get(5,4))
values a) Error, invalid syntax
c) Dictionaries aren’t ordered b) A
d) Dictionaries are mutable c) 5
Answer: b d) 4
Explanation: The values of a dictionary can be Answer: d
accessed using keys but the keys of a Explanation: The get() method returns the default
dictionary can’t be accessed using values. value(second parameter) if the key
2. Which of the following is not a declaration of the isn’t present in the dictionary.
dictionary? 6. What will be the output of the following Python
a) {1: ‘A’, 2: ‘B’} code snippet?
b) dict([[1,”A”],[2,”B”]]) a={1:"A",2:"B",3:"C"}
c) {1,”A”,2”B”} print(a.setdefault(3))
d) { } a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
Answer: c b) C
Explanation: Option c is a set, not a dictionary. c) {1: 3, 2: 3, 3: 3}
3. What will be the output of the following Python d) No method called setdefault() exists for dictionary
code snippet? Answer: b
a={1:"A",2:"B",3:"C"} Explanation: setdefault() is similar to get() but will
for i,j in a.items(): set dict[key]=default if key is not
print(i,j,end=" ") already in the dictionary.
a) 1 A 2 B 3 C 7. What will be the output of the following Python
b) 1 2 3 code snippet?
c) A B C a={1:"A",2:"B",3:"C"}
d) 1:”A” 2:”B” 3:”C” a.setdefault(4,"D")
Answer: a print(a)
Explanation: In the above code, variables i and j a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
iterate over the keys and values of the b) None
dictionary respectively. c) Error
4. What will be the output of the following Python d) [1,3,6,10]
code snippet? Answer: a
a={1:"A",2:"B",3:"C"} Explanation: setdefault() will set dict[key]=default if
print(a.get(1,4)) key is not already in the
100

a) 1 dictionary.
b) A 8. What will be the output of the following Python
Page

c) 4 code?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a={1:"A",2:"B",3:"C"} Explanation: Keys of a dictionary may be any data
b={4:"D",5:"E"} type that is immutable.
a.update(b) 12. What will be the output of the following Python
print(a) code?
a) {1: ‘A’, 2: ‘B’, 3: ‘C’} a={1:5,2:3,3:4}
b) Method update() doesn’t exist for dictionaries a.pop(3)
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’} print(a)
d) {4: ‘D’, 5: ‘E’} a) {1: 5}
Page 262 of 391 b) {1: 5, 2: 3}
Answer: c c) Error, syntax error for pop() method
Explanation: update() method adds dictionary b’s Page 263 of 391
key-value pairs to dictionary a. d) {1: 5, 3: 4}
Execute in python shell to verify. Answer: b
9. What will be the output of the following Python Explanation: pop() method removes the key-value
code? pair for the key mentioned in the
a={1:"A",2:"B",3:"C"} pop() method.
b=a.copy() 13. What will be the output of the following Python
b[2]="D" code?
print(a) a={1:5,2:3,3:4}
a) Error, copy() method doesn’t exist for dictionaries print(a.pop(4,9))
b) {1: ‘A’, 2: ‘B’, 3: ‘C’} a) 9
c) {1: ‘A’, 2: ‘D’, 3: ‘C’} b) 3
d) “None” is printed c) Too many arguments for pop() method
Answer: b d) 4
Explanation: Changes made in the copy of the Answer: a
dictionary isn’t reflected in the original Explanation: pop() method returns the value when
one. the key is passed as an argument
10. What will be the output of the following Python and otherwise returns the default value(second
code? argument) if the key isn’t present in the
a={1:"A",2:"B",3:"C"} dictionary.
a.clear() 14. What will be the output of the following Python
print(a) code?
a) None a={1:"A",2:"B",3:"C"}
b) { None:None, None:None, None:None} for i in a:
c) {1:None, 2:None, 3:None} print(i,end=" ")
d) { } a) 1 2 3
Answer: d b) ‘A’ ‘B’ ‘C’
Explanation: The clear() method clears all the key- c) 1 ‘A’ 2 ‘B’ 3 ‘C’
value pairs in the dictionary. d) Error, it should be: for i in a.items():
11. Which of the following isn’t true about dictionary Answer: a
keys? Explanation: The variable i iterates over the keys of
a) More than one key isn’t allowed the dictionary and hence the keys
b) Keys must be immutable are printed.
c) Keys must be integers 15. What will be the output of the following Python
101

d) When duplicate keys encountered, the last code?


assignment wins >>> a={1:"A",2:"B",3:"C"}
Page

Answer: c >>> a.items()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) Syntax error total[items] += 1
b) dict_items([(‘A’), (‘B’), (‘C’)]) else:
c) dict_items([(1,2,3)]) total[items] = 1
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)]) insert('Apple')
Answer: d insert('Ball')
Explanation: The method items() returns list of insert('Apple')
tuples with each tuple having a keyvalue pair. print (len(total))
Page 264 of 391 a) 3
Python Questions and Answers – Dictionary – 3 b) 1
1. Which of the statements about dictionary values if c) 2
false? Page 265 of 391
a) More than one key can have the same value d) 0
b) The values of the dictionary can be accessed as Answer: c
dict[key] Explanation: The insert() function counts the
c) Values of a dictionary must be unique number of occurrences of the item being
d) Values of a dictionary can be a mixture of letters inserted into the dictionary. There are only 2 keys
and numbers present since the key ‘Apple’ is
Answer: c repeated. Thus, the length of the dictionary is 2.
Explanation: More than one key can have the same 5. What will be the output of the following Python
value. code snippet?
2. What will be the output of the following Python a = {}
code snippet? a[1] = 1
>>> a={1:"A",2:"B",3:"C"} a['1'] = 2
>>> del a a[1]=a[1]+1
a) method del doesn’t exist for the dictionary count = 0
b) del deletes the values in the dictionary for i in a:
c) del deletes the entire dictionary count += a[i]
d) del deletes the keys in the dictionary print(count)
Answer: c a) 1
Explanation: del deletes the entire dictionary and b) 2
any further attempt to access it will c) 4
throw an error. d) Error, the keys can’t be a mixture of letters and
3. If a is a dictionary with some key-value pairs, what numbers
does a.popitem() do? Answer: c
a) Removes an arbitrary element Explanation: The above piece of code basically finds
b) Removes all the key-value pairs the sum of the values of keys.
c) Removes the key-value pair for the key given as an 6. What will be the output of the following Python
argument code snippet?
d) Invalid method for dictionary numbers = {}
Answer: a letters = {}
Explanation: The method popitem() removes a comb = {}
random key-value pair. numbers[1] = 56
4. What will be the output of the following Python numbers[3] = 7
code snippet? letters[4] = 'B'
102

total={} comb['Numbers'] = numbers


def insert(items): comb['Letters'] = letters
Page

if items in total: print(comb)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) Error, dictionary in a dictionary can’t exist b) 3
b) ‘Numbers’: {1: 56, 3: 7} c) 6
c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}} d) 2
d) {‘Numbers’: {1: 56, 3: 7}, ‘Letters’: {4: ‘B’}} Answer: c
Answer: d Explanation: The value of key 1 is 4 since 1 and 1.0
Explanation: Dictionary in a dictionary can exist. are the same. Then, the function
7. What will be the output of the following Python count() gives the sum of all the values of the keys
code snippet? (2+4).
test = {1:'A', 2:'B', 3:'C'} 10. What will be the output of the following Python
test = {} code snippet?
print(len(test)) a={}
Page 266 of 391 a['a']=1
a) 0 a['b']=[2,3,4]
b) None print(a)
c) 3 Page 267 of 391
d) An exception is thrown a) Exception is thrown
Answer: a b) {‘b’: [2], ‘a’: 1}
Explanation: In the second line of code, the c) {‘b’: [2], ‘a’: [3]}
dictionary becomes an empty dictionary. d) {‘b’: [2, 3, 4], ‘a’: 1}
Thus, length=0. Answer: d
8. What will be the output of the following Python Explanation: Mutable members can be used as the
code snippet? values of the dictionary but they
test = {1:'A', 2:'B', 3:'C'} cannot be used as the keys of the dictionary.
del test[1] 11. What will be the output of the following Python
test[1] = 'D' code snippet?
del test[2] >>>import collections
print(len(test)) >>> a=collections.Counter([1,1,2,3,3,4,4,4])
a) 0 >>> a
b) 2 a) {1,2,3,4}
c) Error as the key-value pair of 1:’A’ is already b) Counter({4, 1, 3, 2})
deleted c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
d) 1 d) {4: 3, 1: 2, 3: 2, 2: 1}
Answer: b Answer: c
Explanation: After the key-value pair of 1:’A’ is Explanation: The statement
deleted, the key-value pair of 1:’D’ is a=collections.OrderedDict() generates a dictionary
added. with
9. What will be the output of the following Python the number as the key and the count of times the
code snippet? number appears as the value.
a = {} 12. What will be the output of the following Python
a[1] = 1 code snippet?
a['1'] = 2 >>>import collections
a[1.0]=4 >>> b=collections.Counter([2,2,3,4,4,4])
count = 0 >>> b.most_common(1)
for i in a: a) Counter({4: 3, 2: 2, 3: 1})
103

count += a[i] b) {3:1}


print(count) c) {4:3}
Page

a) An exception is thrown d) [(4, 3)]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: d class demo(dict):
Explanation: The most_common() method returns def __test__(self,key):
the n number key-value pairs where return []
the value is the most recurring. a = demo()
13. What will be the output of the following Python a['test'] = 7
code snippet? print(a)
>>>import collections a) True
>>> b=collections.Counter([2,2,3,4,4,4]) b) False
>>> b.most_common(1) Answer: b
a) Counter({4: 3, 2: 2, 3: 1}) Explanation: The output of the code is: {‘test’:7}.
b) {3:1} 2. What will be the output of the following Python
c) {4:3} code?
d) [(4, 3)] count={}
Answer: d count[(1,2,4)] = 5
Explanation: The most_common() method returns count[(4,2,1)] = 7
the n number key-value pairs where count[(1,2)] = 6
the value is the most recurring. count[(4,2,1)] = 2
Page 268 of 391 tot = 0
14. What will be the output of the following Python for i in count:
code snippet? tot=tot+count[i]
>>> import collections print(len(count)+tot)
>>> a=collections.Counter([2,2,3,3,3,4]) a) 25
>>> b=collections.Counter([2,2,3,4,4]) b) 17
>>> a|b c) 16
a) Counter({3: 3, 2: 2, 4: 2}) d) Tuples can’t be made keys of a dictionary
b) Counter({2: 2, 3: 1, 4: 1}) Answer: c
c) Counter({3: 2}) Explanation: Tuples can be made keys of a
d) Counter({4: 1}) dictionary. Length of the dictionary is 3 as
Answer: a the value of the key (4,2,1) is modified to 2. The
Explanation: a|b returns the pair of keys and the value of the variable tot is 5+6+2=13.
highest recurring value. 3. What will be the output of the following Python
15. What will be the output of the following Python code?
code snippet? a={}
>>> import collections a[2]=1
>>> a=collections.Counter([3,3,4,5]) a[1]=[2,3,4]
>>> b=collections.Counter([3,4,4,5,5,5]) print(a[1][1])
>>> a&b a) [2,3,4]
a) Counter({3: 12, 4: 1, 5: 1}) b) 3
b) Counter({3: 1, 4: 1, 5: 1}) c) 2
c) Counter({4: 2}) d) An exception is thrown
d) Counter({5: 1}) Answer: b
Answer: b Explanation: Now, a={1:[2,3,4],2:1} . a[1][1] refers
Explanation: a&b returns the pair of keys and the to second element having key 1.
lowest recurring value. Page 270 of 391
104

Page 269 of 391 4. What will be the output of the following Python
Python Questions and Answers – Dictionary – 4 code?
Page

1. The following Python code is invalid. >>> a={'B':5,'A':9,'C':7}

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


>>> sorted(a) b) Returns False if dictionary is empty
a) [‘A’,’B’,’C’] c) Returns True if all keys of the dictionary are true
b) [‘B’,’C’,’A’] d) Method any() doesn’t exist for dictionary
c) [5,7,9] Answer: a
d) [9,5,7] Explanation: Method any() returns True if any key
Answer: a of the dictionary is true and False if
Explanation: Return a new sorted list of keys in the the dictionary is empty.
dictionary. 9. What will be the output of the following Python
5. What will be the output of the following Python code?
code? >>> a={"a":1,"b":2,"c":3}
>>> a={i: i*i for i in range(6)} >>> b=dict(zip(a.values(),a.keys()))
>>> a >>> b
a) Dictionary comprehension doesn’t exist a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36} b) An exception is thrown
c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25} c) {‘a’: ‘b’: ‘c’: }
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} d) {1: ‘a’, 2: ‘b’, 3: ‘c’}
Answer: d Answer: d
Explanation: Dictionary comprehension is Explanation: The above piece of code inverts the
implemented in the above piece of code. key-value pairs in the dictionary.
6. What will be the output of the following Python 10. What will be the output of the following Python
code? code?
>>> a={} >>> a={i: 'A' + str(i) for i in range(5)}
>>> a.fromkeys([1,2,3],"check") >>> a
a) Syntax error a) An exception is thrown
b) {1:”check”,2:”check”,3:”check”} b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}
c) “check” c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}
d) {1:None,2:None,3:None} d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}
Answer: b Answer: b
Explanation: The dictionary takes values of keys Explanation: Dictionary comprehension and string
from the list and initializes it to the concatenation is implemented in the
default value (value given in the second parameter). above piece of code.
Execute in Python shell to verify. 11. What will be the output of the following Python
7. What will be the output of the following Python code?
code? >>> a=dict()
>>> b={} >>> a[1]
>>> all(b) a) An exception is thrown since the dictionary is
a) { } empty
b) False b) ‘ ‘
c) True c) 1
d) An exception is thrown d) 0
Answer: c Answer: a
Explanation: Function all() returns True if all keys of Explanation: The values of a dictionary can be
the dictionary are true or if the accessed through the keys only if the
dictionary is empty. keys exist in the dictionary.
105

Page 271 of 391 12. What will be the output of the following Python
8. If b is a dictionary, what does any(b) do? code?
Page

a) Returns True if any key of the dictionary is true Page 272 of 391

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


>>> import collections code?
>>> a=dict() >>> import collections
>>> a=collections.defaultdict(int) >>> a=collections.OrderedDict((str(x),x) for x in
>>> a[1] range(3))
a) 1 >>> a
b) 0 Page 273 of 391
c) An exception is thrown a) {‘2’:2, ‘0’:0, ‘1’:1}
d) ‘ ‘ b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
Answer: b c) An exception is thrown
Explanation: The statement d) ‘ ‘
a=collections.defaultdict(int) gives the default value Answer: b
of 0 Explanation: The line of code
(since int data type is given within the parenthesis) a=collections.OrderedDict() generates a dictionary
even if the keys don’t exist in the satisfying the conditions given within the
dictionary. parenthesis and in an ascending order of the
13. What will be the output of the following Python keys.
code? Page 274 of 391
>>> import collections Python Questions and Answers – Python Modules
>>> a=dict() 1. Which of these definitions correctly describes a
>>> a=collections.defaultdict(str) module?
>>> a['A'] a) Denoted by triple quotes for providing the
a) An exception is thrown since the dictionary is specification of certain program elements
empty b) Design and implementation of specific
b) ‘ ‘ functionality to be incorporated into a program
c) ‘A’ c) Defines the specification of how it is to be used
d) 0 d) Any program that reuses code
Answer: b Answer: b
Explanation: The statement Explanation: The term “module” refers to the
a=collections.defaultdict(str) gives the default value implementation of specific functionality
of ‘ ‘ to be incorporated into a program.
even if the keys don’t exist in the dictionary. 2. Which of the following is not an advantage of
14. What will be the output of the following Python using modules?
code? a) Provides a means of reuse of program code
>>> import collections b) Provides a means of dividing up tasks
>>> b=dict() c) Provides a means of reducing the size of the
>>> b=collections.defaultdict(lambda: 7) program
>>> b[4] d) Provides a means of testing individual parts of the
a) 4 program
b) 0 Answer: c
c) An exception is thrown Explanation: The total size of the program remains
d) 7 the same regardless of whether
Answer: d modules are used or not. Modules simply divide the
Explanation: The statement program.
a=collections.defaultdict(lambda: x) gives the 3. Program code making use of a given module is
106

default value called a ______ of the module.


of x even if the keys don’t exist in the dictionary. a) Client
Page

15. What will be the output of the following Python b) Docstring

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) Interface 8. What will be the output of the following Python
d) Modularity code?
Answer: a #mod1
Explanation: Program code making use of a given def change(a):
module is called the client of the b=[x*2 for x in a]
module. There may be multiple clients for a print(b)
module. #mod2
4. ______ is a string literal denoted by triple quotes def change(a):
for providing the specifications of b=[x*x for x in a]
certain program elements. print(b)
a) Interface from mod1 import change
b) Modularity from mod2 import change
c) Client #main
d) Docstring s=[1,2,3]
Answer: d change(s)
Explanation: Docstring used for providing the a) [2,4,6]
specifications of program elements. b) [1,4,9]
5. Which of the following is true about top-down c)
design process? [2,4,6]
a) The details of a program design are addressed [1,4,9]
before the overall design d) There is a name clash
b) Only the details of the program are addressed Answer: d
c) The overall design of the program is addressed Explanation: A name clash is when two different
before the details entities with the same identifier
Page 275 of 391 become part of the same scope. Since both the
d) Only the design of the program is addressed modules have the same function name,
Answer: c there is a name clash.
Explanation: Top-down design is an approach for Page 276 of 391
deriving a modular design in which 9. Which of the following isn’t true about main
the overall design. modules?
6. In top-down design every module is broken into a) When a python file is directly executed, it is
same number of submodules. considered main module of a program
a) True b) Main modules may import any number of modules
b) False c) Special name given to main modules is: __main__
Answer: b d) Other main modules can import main modules
Explanation: In top-down design every module can Answer: d
even be broken down into different Explanation: Main modules are not meant to be
number of submodules. imported into other modules.
7. All modular designs are because of a top-down 10. Which of the following is not a valid namespace?
design process. a) Global namespace
a) True b) Public namespace
b) False c) Built-in namespace
Answer: b d) Local namespace
Explanation: The details of the program can be Answer: b
107

addressed before the overall design too. Explanation: During a Python program execution,
Hence, all modular designs are not because of a top- there are as many as three
Page

down design process. namespaces – built-in namespace, global

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


namespace and local namespace. from math import factorial
11. Which of the following is false about “import print(math.factorial(5))
modulename” form of import? a) 120
a) The namespace of imported module becomes part b) Nothing is printed
of importing module c) Error, method factorial doesn’t exist in math
b) This form of import prevents name clash module
c) The namespace of imported module becomes d) Error, the statement should be: print(factorial(5))
available to importing module Answer: d
d) The identifiers in module are accessed as: Explanation: In the “from-import” form of import,
modulename.identifier the imported identifiers (in this
Answer: a case factorial()) aren’t specified along with the
Explanation: In the “import modulename” form of module name.
import, the namespace of imported 15. What is the order of namespaces in which Python
module becomes available to, but not part of, the looks for an identifier?
importing module. a) Python first searches the global namespace, then
12. Which of the following is false about “from- the local namespace and finally the builtin
import” form of import? namespace
a) The syntax is: from modulename import identifier b) Python first searches the local namespace, then
b) This form of import prevents name clash the global namespace and finally the builtin
c) The namespace of imported module becomes part namespace
of importing module c) Python first searches the built-in namespace, then
d) The identifiers in module are accessed directly as: the global namespace and finally the
identifier local namespace
Answer: b d) Python first searches the built-in namespace, then
Explanation: In the “from-import” form of import, the local namespace and finally the
there may be name clashes because global namespace
names of the imported identifiers aren’t specified Answer: b
along with the module name. Explanation: Python first searches for the local, then
13. Which of the statements about modules is false? the global and finally the built-in
a) In the “from-import” form of import, identifiers namespace.
beginning with two underscores are Page 278 of 391
private and aren’t imported Python Questions and Answers – Math module– 1
b) dir() built-in function monitors the items in the 1. What is returned by math.ceil(3.4)?
namespace of the main module a) 3
c) In the “from-import” form of import, all identifiers b) 4
regardless of whether they are private c) 4.0
or public are imported d) 3.0
d) When a module is loaded, a compiled version of Answer: b
the module with file extension .pyc is Explanation: The ceil function returns the smallest
Page 277 of 391 integer that is bigger than or equal
automatically produced to the number itself.
Answer: c 2. What is the value returned by math.floor(3.4)?
Explanation: In the “from-import” form of import, a) 3
identifiers beginning with two b) 4
108

underscores are private and aren’t imported. c) 4.0


14. What will be the output of the following Python d) 3.0
Page

code? Answer: a

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: The floor function returns the biggest c) error
number that is smaller than or d) none of the mentioned
equal to the number itself. Answer: b
3. What will be the output of print(math.copysign(3, Explanation: Factorial of 0 is 1.
-1))? 8. What is math.factorial(4.0)?
a) 1 a) 24
b) 1.0 b) 1
c) -3 c) error
d) -3.0 d) none of the mentioned
Answer: d Answer: a
Explanation: The copysign function returns a float Explanation: The factorial of 4 is returned.
whose absolute value is that of the 9. What will be the output of
first argument and the sign is that of the second print(math.factorial(4.5))?
argument. a) 24
4. What is displayed on executing print(math.fabs(- b) 120
3.4))? c) error
a) -3.4 d) 24.0
b) 3.4 Answer: c
c) 3 Explanation: Factorial is only defined for non-
d) -3 negative integers.
Answer: b 10. What is math.floor(0o10)?
Explanation: A negative floating point number is a) 8
returned as a positive floating point b) 10
number. c) 0
5. Is the output of the function abs() the same as that d) 9
of the function math.fabs()? Page 280 of 391
a) sometimes Answer: a
b) always Explanation: 0o10 is 8 and floor(8) is 8.
c) never Page 281 of 391
d) none of the mentioned Python Questions and Answers – Math module– 2
Page 279 of 391 1. What does the function math.frexp(x) return?
Answer: a a) a tuple containing the mantissa and the exponent
Explanation: math.fabs() always returns a float and of x
does not work with complex b) a list containing the mantissa and the exponent of
numbers whereas the return type of abs() is x
determined by the type of value that is c) a tuple containing the mantissa of x
passed to it. d) a list containing the exponent of x
6. What is the value returned by math.fact(6)? Answer: a
a) 720 Explanation: It returns a tuple with two elements.
b) 6 The first element is the mantissa and
c) [1, 2, 3, 6] the second element is the exponent.
d) error 2. What is the result of math.fsum([.1 for i in
Answer: d range(20)])?
Explanation: NameError, fact() is not defined. a) 2.0
109

7. What is the value of x if x = math.factorial(0)? b) 20


a) 0 c) 2
Page

b) 1 d) 2.0000000000000004

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: a print(math.isinf(float('-inf')))
Explanation: The function fsum returns an accurate a) error, the minus sign shouldn’t have been inside
floating point sum of the elements the brackets
of its argument. b) error, there is no function called isinf
3. What is the result of sum([.1 for i in range(20)])? c) True
a) 2.0 d) False
b) 20 Answer: c
c) 2 Explanation: -float(‘inf’) is the same as float(‘-inf’).
d) 2.0000000000000004 9. What is the value of x if x = math.ldexp(0.5, 1)?
Answer: d a) 1
Explanation: There is some loss of accuracy when b) 2.0
we use sum with floating point c) 0.5
numbers. Hence the function fsum is preferable. d) none of the mentioned
4. What is returned by math.isfinite(float(‘inf’))? Answer: d
a) True Explanation: The value returned by ldexp(x, y) is x *
b) False (2 ** y). In the current case x is
c) None 1.0.
d) error 10. What is returned by math.modf(1.0)?
Answer: b a) (0.0, 1.0)
Explanation: float(‘inf’) is not a finite number. b) (1.0, 0.0)
5. What is returned by math.isfinite(float(‘nan’))? c) (0.5, 1)
a) True Page 283 of 391
b) False d) (0.5, 1.0)
c) None Answer: a
d) error Explanation: The first element is the fractional part
Page 282 of 391 and the second element is the
Answer: b integral part of the argument.
Explanation: float(‘nan’) is not a finite number. Page 284 of 391
6. What is x if x = math.isfinite(float(‘0.0’))? Python Questions and Answers – Math module– 3
a) True 1. What is the result of math.trunc(3.1)?
b) False a) 3.0
c) None b) 3
d) error c) 0.1
Answer: a d) 1
Explanation: float(‘0.0’) is a finite number. Answer: b
7. What will be the output of the following Python Explanation: The integral part of the floating point
code? number is returned.
>>> -float('inf') + float('inf') 2. What is the output of print(math.trunc(‘3.1’))?
a) inf a) 3
b) nan b) 3.0
c) 0 c) error
d) 0.0 d) none of the mentioned
Answer: b Answer: c
Explanation: The result of float(‘inf’)-float(‘inf’) is Explanation: TypeError, a string does not have
110

undefined. __trunc__ method.


8. What will be the output of the following Python 3. Which of the following is the same as
Page

code? math.exp(p)?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) e ** p Explanation: math.pow() returns a floating point
b) math.e ** p number.
c) p ** e 9. What is the value of x if x = math.sqrt(4)?
d) p ** math.e a) 2
Answer: b b) 2.0
Explanation: math.e is the constant defined in the c) (2, -2)
math module. d) (2.0, -2.0)
4. What is returned by math.expm1(p)? Answer: b
a) (math.e ** p) – 1 Explanation: The function returns one floating point
b) math.e ** (p – 1) number.
c) error 10. What does math.sqrt(X, Y) do?
d) none of the mentioned a) calculate the Xth root of Y
Answer: a b) calculate the Yth root of X
Explanation: One is subtracted from the result of c) error
math.exp(p) and returned. d) return a tuple with the square root of X and Y
5. What is the default base used when math.log(x) is Answer: c
found? Explanation: The function takes only one argument.
a) e Page 286 of 391
b) 10 Python Question and Answers – Random module –
c) 2 1
d) none of the mentioned 1. To include the use of functions which are present
Answer: a in the random library, we must use the
Explanation: The natural log of x is returned by option:
default. a) import random
Page 285 of 391 b) random.h
6. Which of the following aren’t defined in the math c) import.random
module? d) random.random
a) log2() Answer: a
b) log10() Explanation: The command import random is used
c) logx() to import the random module,
d) none of the mentioned which enables us to use the functions which are
Answer: c present in the random library.
Explanation: log2() and log10() are defined in the 2. The output of the following Python code is either 1
math module. or 2.
7. What is returned by int(math.pow(3, 2))? import random
a) 6 random.randint(1,2)
b) 9 a) True
c) error, third argument required b) False
d) error, too many arguments Answer: a
Answer: b Explanation: The function random.randint(a,b)
Explanation: math.pow(a, b) returns a ** b. helps us to generate an integer between
8. What is output of print(math.pow(3, 2))? ‘a’ and ‘b’, including ‘a’ and ‘b’. In this case, since
a) 9 there are no integers between 1 and
b) 9.0 2, the output will necessarily be either 1 or 2’.
111

c) None 3. What will be the output of the following Python


d) None of the mentioned code?
Page

Answer: b import random

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


random.choice(2,3,4) Answer: d
a) An integer other than 2, 3 and 4 Explanation: This question depicts the basic
b) Either 2, 3 or 4 difference between the functions
c) Error random.randint(a, b) and random.uniform(a, b).
d) 3 only While random.randint(a,b) generates
Answer: c an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’,
Explanation: The code shown above displays the the function random.uniform(a,b)
incorrect syntax of the function generates a decimal value between ‘a’ and ‘b’.
random.choice(). This functions takes its numeric 7. What will be the output of the following Python
parameter in the form of a list. Hence function if the random module has
the correct syntax world be: random.choice([2,3,4]). already been imported?
4. What will be the output of the following Python random.randint(3.5,7)
code? a) Error
import random b) Any integer between 3.5 and 7, including 7
random.choice([10.4, 56.99, 76]) c) Any integer between 3.5 and 7, excluding 7
a) Error d) The integer closest to the mean of 3.5 and 7
b) Either 10.4, 56.99 or 76 Answer: a
c) Any number other than 10.4, 56.99 and 76 Explanation: The function random.randint() does
d) 56.99 only not accept a decimal value as a
Answer: b parameter. Hence the function shown above will
Explanation: The function random.choice(a,b,c,d) throw an error.
returns a random number which is 8. Which of the following functions helps us to
Page 287 of 391 randomize the items of a list?
selected from a, b, c and d. The output can be either a) seed
a, b, c or d. Hence the output of the b) randomise
snippet of code shown above can be either 10.4, c) shuffle
56.99 or 76. d) uniform
5. What will be the output of the following Python Page 288 of 391
function (random module has already Answer: c
been imported)? Explanation: The function shuffle, which is included
random.choice('sun') in the random module, helps us to
a) sun randomize the items of a list. This function takes
b) u the list as a parameter.
c) either s, u or n 9. What will be the output of the following Python
d) error code?
Answer: c random.seed(3)
Explanation: The above function works with random.randint(1,5)
alphabets just as it does with numbers. 2
The output of this expression will be either s, u or n. random.seed(3)
6. What will be the output of the following Python random.randint(1,5)
function, assuming that the random a) 3
module has already been imported? b) 2
random.uniform(3,4) c) Any integer between 1 and 5, including 1 and 5
a) Error d) Any integer between 1 and 5, excluding 1 and 5
112

b) Either 3 or 4 Answer: b
c) Any integer other than 3 and 4 Explanation: We use the seed function when we
Page

d) Any decimal value between 3 and 4 want to use the same random number

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


once again in our program. Hence the output of the Explanation: The function randrange returns only an
code shown above will be 2, since 2 integer value. Hence this
was generated previously following which we used statement is true.
the seed function. 14. What will be the output of the following Python
10. What is the interval of the value generated by the code?
function random.random(), assuming random.randrange(1,100,10)
that the random module has already been imported? a) 32
a) (0,1) b) 67
b) (0,1] c) 91
c) [0,1] d) 80
d) [0,1) Answer: c
Answer: d Explanation: The output of this function can be any
Explanation: The function random.random() value which is a multiple of 10,
generates a random value in the interval plus 1. Hence a value like 11, 21, 31, 41…91 can be
[0,1), that is, including zero but excluding one. the output. Also, the value should
11. What will be the output of the following Python necessarily be between 1 and 100. The only option
code? which satisfies this criteria is 91.
random.randrange(0,91,5) 15. What will be the output of the following Python
a) 10 function, assuming that the random
b) 18 library has already been included?
c) 79 random.shuffle[1,2,24]
d) 95 a) Randomized list containing the same numbers in
Answer: a any order
Explanation: The function shown above will b) The same list, that is [1,2,24]
generate an output which is a multiple of 5 c) A list containing any random numbers between 1
and is between 0 and 91. The only option which and 24
satisfies these criteria is 10. Hence the d) Error
only possible output of this function is 10. Answer: d
12. Both the functions randint and uniform accept Explanation: The function shown above will result in
____________ parameters. an error because this is the
a) 0 incorrect syntax for the usage of the function
b) 1 shuffle(). The list should be previously
c) 3 declared and then passed to this function to get an
Page 289 of 391 output.
d) 2 An example of the correct syntax:
Answer: d >>> l=['a','b','c','d']
Explanation: Both of these functions, that is, randint >>> random.shuffle(l)
and uniform are included in the >>> print(l)
random module and both of these functions accept Page 290 of 391
2 parameters. For example: Python Questions and Answers – Random Module –
random.uniform(a,b) where ‘a’ and ‘b’ specify the 2
range. 1. What the does random.seed(3) return?
13. The randrange function returns only an integer a) True
value. b) None
113

a) True c) 3
b) False d) 1
Page

Answer: a Answer: b

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: The function random.seed() always 7. Which of the following will never be displayed on
returns a None. executing print(random.choice({0: 1, 2:
2. Which of the following cannot be returned by 3}))?
random.randrange(4)? a) 0
a) 0 b) 1
b) 3 c) KeyError: 1
c) 2.3 d) none of the mentioned
d) none of the mentioned Answer: a
Answer: c Explanation: It will not print 0 but dict[0] i.e. 1 may
Explanation: Only integers can be returned. be printed.
3. Which of the following is equivalent to 8. What does random.shuffle(x) do when x = [1, 2,
random.randrange(3)? 3]?
a) range(3) a) error
b) random.choice(range(0, 3)) b) do nothing, it is a placeholder for a function that is
c) random.shuffle(range(3)) yet to be implemented
d) random.select(range(3)) c) shuffle the elements of the list in-place
Answer: b d) none of the mentioned
Explanation: It returns one number from the given Answer: c
range. Explanation: The elements of the list passed to it
4. The function random.randint(4) can return only are shuffled in-place.
one of the following values. Which? 9. Which type of elements are accepted by
a) 4 random.shuffle()?
b) 3.4 a) strings
c) error b) lists
d) 5 c) tuples
Answer: c d) integers
Explanation: Error, the function takes two Answer: b
arguments. Explanation: Strings and tuples are immutable and
5. Which of the following is equivalent to an integer has no len().
random.randint(3, 6)? 10. What is the range of values that
a) random.choice([3, 6]) random.random() can return?
b) random.randrange(3, 6) a) [0.0, 1.0]
c) 3 + random.randrange(3) b) (0.0, 1.0]
d) 3 + random.randrange(4) c) (0.0, 1.0)
Answer: d d) [0.0, 1.0)
Explanation: random.randint(3, 6) can return any Answer: d
one of 3, 4, 5 and 6. Explanation: Any number that is greater than or
Page 291 of 391 equal to 0.0 and lesser than 1.0 can be
6. Which of the following will not be returned by returned.
random.choice(“1 ,”)? Page 292 of 391
a) 1 CHAPTER-3 WORKING WITH FUNCTIONS
b) (space) 1. Which of the following is the use of function in
c) , python?
d) none of the mentioned a) Functions are reusable pieces of programs
114

Answer: d b) Functions don’t provide better modularity for your


Explanation: Any of the characters present in the application
Page

string may be returned. c) you can’t also create your own functions

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) All of the mentioned code?
Answer: a 1. def printMax(a, b):
Explanation: Functions are reusable pieces of 2. if a > b:
programs. They allow you to give a name to a 3. print(a, 'is maximum')
block of statements, allowing you to run that block 4. elif a == b:
using the specified name anywhere in 5. print(a, 'is equal to', b)
your program and any number of times. 6. else:
2. Which keyword is used for function? 7. print(b, 'is maximum')
a) Fun 8. printMax(3, 4)
b) Define a) 3
c) Def b) 4
d) Function c) 4 is maximum
Answer: c d) None of the mentioned
Explanation: None. Answer: c
3. What will be the output of the following Python Explanation: Here, we define a function called
code? printMax that uses two parameters called a
1. def sayHello(): and b. We find out the greater number using a
2. print('Hello World!') simple if..else statement and then print the
3. sayHello() bigger number.
4. sayHello() 5. What will be the output of the following Python
a) code?
Hello World! 1. x = 50
Hello World! 2. def func(x):
b) 3. print('x is', x)
'Hello World!' 4. x = 2
'Hello World!' 5. print('Changed local x to', x)
c) 6. func(x)
Hello 7. print('x is now', x)
Hello a) x is now 50
d) None of the mentioned b) x is now 2
Answer: a c) x is now 100
Explanation: Functions are defined using the def d) None of the mentioned
keyword. After this keyword comes an Answer: a
identifier name for the function, followed by a pair of Explanation: The first time that we print the value of
parentheses which may enclose some the name x with the first line in the
names of variables, and by the final colon that ends function’s body, Python uses the value of the
the line. Next follows the block of parameter declared in the main block, above
statements that are part of this function. the function definition.
1. def sayHello(): Next, we assign the value 2 to x. The name x is local
2. print('Hello World!') # block belonging to the to our function. So, when we change
function the value of x in the function, the x defined in the
3. # End of function # main block remains unaffected.
Page 293 of 391 With the last print function call, we display the value
4. of x as defined in the main block,
115

5. sayHello() # call the function thereby confirming that it is actually unaffected by


6. sayHello() # call the function again the local assignment within the
Page

4. What will be the output of the following Python previously called function.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


6. What will be the output of the following Python HelloHelloHelloHelloHello
code? Answer: a
Page 294 of 391 Explanation: For some functions, you may want to
1. x = 50 make some parameters optional and use
2. def func(): Page 295 of 391
3. global x default values in case the user does not want to
4. print('x is', x) provide values for them. This is done with
5. x = 2 the help of default argument values. You can specify
6. print('Changed global x to', x) default argument values for parameters
7. func() by appending to the parameter name in the function
8. print('Value of x is', x) definition the assignment operator (=)
a) followed by the default value.
x is 50 The function named say is used to print a string as
Changed global x to 2 many times as specified. If we don’t
Value of x is 50 supply a value, then by default, the string is printed
b) just once. We achieve this by specifying
x is 50 a default argument value of 1 to the parameter
Changed global x to 2 times.
Value of x is 2 In the first usage of say, we supply only the string
c) and it prints the string once. In the second
x is 50 usage of say, we supply both the string and an
Changed global x to 50 argument 5 stating that we want to say the
Value of x is 50 string message 5 times.
d) None of the mentioned 8. What will be the output of the following Python
Answer: b code?
Explanation: The global statement is used to declare 1. def func(a, b=5, c=10):
that x is a global variable – hence, when 2. print('a is', a, 'and b is', b, 'and c is', c)
we assign a value to x inside the function, that 3.
change is reflected when we use the value of x 4. func(3, 7)
in the main block. 5. func(25, c = 24)
7. What will be the output of the following Python 6. func(c = 50, a = 100)
code? a)
1. def say(message, times = 1): a is 7 and b is 3 and c is 10
2. print(message * times) a is 25 and b is 5 and c is 24
3. say('Hello') a is 5 and b is 100 and c is 50
4. say('World', 5) b)
a) a is 3 and b is 7 and c is 10
Hello a is 5 and b is 25 and c is 24
WorldWorldWorldWorldWorld a is 50 and b is 100 and c is 5
b) c)
Hello a is 3 and b is 7 and c is 10
World 5 a is 25 and b is 5 and c is 24
c) a is 100 and b is 5 and c is 50
Hello d) None of the mentioned
116

World,World,World,World,World Answer: c
d) Explanation: If you have some functions with many
Page

Hello parameters and you want to specify only

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


some of them, then you can give values for such classes, and methods
parameters by naming them – this is called b) All functions should have a docstring
keyword arguments – we use the name (keyword) c) Docstrings can be accessed by the __doc__
instead of the position (which we have attribute on objects
been using all along) to specify the arguments to the d) All of the mentioned
function. Answer: d
The function named func has one parameter without Explanation: Python has a nifty feature called
a default argument value, followed by documentation strings, usually referred to by
two parameters with default argument values. its shorter name docstrings. DocStrings are an
In the first usage, func(3, 7), the parameter a gets the important tool that you should make use of
value 3, the parameter b gets the value since it helps to document the program better and
7 and c gets the default value of 10. makes it easier to understand.
In the second usage func(25, c=24), the variable a 11. Which are the advantages of functions in python?
gets the value of 25 due to the position of a) Reducing duplication of code
the argument. Then, the parameter c gets the value b) Decomposing complex problems into simpler
of 24 due to naming i.e. keyword pieces
arguments. The variable b gets the default value of 5. c) Improving clarity of the code
In the third usage func(c=50, a=100), we use keyword d) All of the mentioned
arguments for all specified values. Answer: d
Notice that we are specifying the value for Explanation: None.
parameter c before that for a even though a is 12. What are the two main types of functions?
defined before c in the function definition. a) Custom function
Page 296 of 391 b) Built-in function & User defined function
9. What will be the output of the following Python c) User function
code? Page 297 of 391
1. def maximum(x, y): d) System function
2. if x > y: Answer: b
3. return x Explanation: Built-in functions and user defined ones.
4. elif x == y: The built-in functions are part of the
5. return 'The numbers are equal' Python language. Examples are: dir(), len() or abs().
6. else: The user defined functions are functions
7. return y created with the def keyword.
8. 13. Where is function defined?
9. print(maximum(2, 3)) a) Module
a) 2 b) Class
b) 3 c) Another function
c) The numbers are equal d) All of the mentioned
d) None of the mentioned Answer: d
Answer: b Explanation: Functions can be defined inside a
Explanation: The maximum function returns the module, a class or another function.
maximum of the parameters, in this case the 14. What is called when a function is defined inside a
numbers supplied to the function. It uses a simple class?
if..else statement to find the greater value a) Module
and then returns that value. b) Class
117

10. Which of the following is a feature of DocString? c) Another function


a) Provide a convenient way of associating d) Method
Page

documentation with Python modules, functions, Answer: d

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Explanation: None. 4. print C2F(0)
15. Which of the following is the use of id() function a)
in python? 212
a) Id returns the identity of the object 32
b) Every object doesn’t have a unique id b)
c) All of the mentioned 314
d) None of the mentioned 24
Answer: a c)
Explanation: Each object in Python has a unique id. 567
The id() function returns the object’s id. 98
16. Which of the following refers to mathematical d) None of the mentioned
function? Answer: a
a) sqrt Explanation: The code shown above is used to
b) rhombus convert a temperature in degree celsius to
c) add fahrenheit.
d) rhombus 19. What will be the output of the following Python
Answer: a code?
Explanation: Functions that are always available for 1. def power(x, y=2):
usage, functions that are contained 2. r = 1
within external modules, which must be imported 3. for i in range(y):
and functions defined by a programmer 4. r = r * x
with the def keyword. 5. return r
Eg: math import sqrt 6. print power(3)
A sqrt() function is imported from the math module. 7. print power(3, 3)
Page 298 of 391 a)
17. What will be the output of the following Python 212
code? 32
1. def cube(x): b)
2. return x * x * x Page 299 of 391
3. x = cube(3) 9
4. print x 27
a) 9 c)
b) 3 567
c) 27 98
d) 30 d) None of the mentioned
Answer: c Answer: b
Explanation: A function is created to do a specific Explanation: The arguments in Python functions may
task. Often there is a result from such a have implicit values. An implicit value
task. The return keyword is used to return values is used, if no value is provided. Here we created a
from a function. A function may or may not power function. The function has one
return a value. If a function does not have a return argument with an implicit value. We can call the
keyword, it will send a none value. function with one or two arguments.
18. What will be the output of the following Python 20. What will be the output of the following Python
code? code?
118

1. def C2F(c): 1. def sum(*args):


2. return c * 9/5 + 32 2. '''Function returns the sum
Page

3. print C2F(100) 3. of all values'''

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


4. r = 0 c) 64
5. for i in args: d) None of the mentioned
6. r += i Answer: a
7. return r Explanation: The lambda keyword creates an
8. print sum.__doc__ anonymous function. The x is a parameter, that
9. print sum(1, 2, 3) is passed to the lambda function. The parameter is
10.print sum(1, 2, 3, 4, 5) followed by a colon character. The code
a) next to the colon is the expression that is executed,
6 when the lambda function is called. The
15 lambda function is assigned to the z variable.
b) The lambda function is executed. The number 8 is
6 passed to the anonymous function and it
100 returns 48 as the result. Note that z is not a name for
c) this function. It is only a variable to
123 which the anonymous function was assigned.
12345 23. What will be the output of the following Python
d) None of the mentioned code?
Answer: a 1. lamb = lambda x: x ** 3
Explanation: We use the * operator to indicate, that 2. print(lamb(5))
the function will accept arbitrary number a) 15
of arguments. The sum() function will return the sum b) 555
of all arguments. The first string in the c) 125
function body is called the function documentation d) None of the mentioned
string. It is used to document the Answer: c
function. The string must be in triple quotes. Explanation: None.
21. Python supports the creation of anonymous 24. Does Lambda contains return statements?
functions at runtime, using a construct called a) True
__________ b) False
a) lambda Answer: b
b) pi Explanation: lambda definition does not include a
c) anonymous return statement. it always contains an
d) none of the mentioned expression which is returned. Also note that we can
Page 300 of 391 put a lambda definition anywhere a
Answer: a function is expected. We don’t have to assign it to a
Explanation: Python supports the creation of variable at all.
anonymous functions (i.e. functions that are not 25. Lambda is a statement.
bound to a name) at runtime, using a construct a) True
called lambda. Lambda functions are b) False
restricted to a single expression. They can be used Page 301 of 391
wherever normal functions can be used. Answer: b
22. What will be the output of the following Python Explanation: lambda is an anonymous function in
code? Python. Hence this statement is false.
1. y = 6 26. Lambda contains block of statements.
2. z = lambda x: x * y a) True
119

3. print z(8) b) False


a) 48 Answer: b
Page

b) 14 Explanation: None.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


27. What will be the output of the following Python Explanation: None.
code? 30. What will be the output of the following Python
1. def f(x, y, z): return x + y + z code?
2. f(2, 30, 400) 1. min = (lambda x, y: x if x < y else y)
a) 432 2. min(101*99, 102*98)
b) 24000 a) 9997
c) 430 b) 9999
d) No output c) 9996
Answer: a d) None of the mentioned
Explanation: None. Answer: c
28. What will be the output of the following Python Explanation: None.
code? 31. What is a variable defined outside a function
1. def writer(): referred to as?
2. title = 'Sir' a) A static variable
3. name = (lambda x:title + ' ' + x) b) A global variable
4. return name c) A local variable
5. d) An automatic variable
6. who = writer() Answer: b
7. who('Arthur') Explanation: The value of a variable defined outside
a) Arthur Sir all function definitions is referred to as
b) Sir Arthur a global variable and can be used by multiple
c) Arthur functions of the program.
d) None of the mentioned 32. What is a variable defined inside a function
Answer: b referred to as?
Explanation: None. a) A global variable
29. What will be the output of the following Python b) A volatile variable
code? c) A local variable
1. L = [lambda x: x ** 2, d) An automatic variable
2. lambda x: x ** 3, Answer: c
3. lambda x: x ** 4] Explanation: The variable inside a function is called
4. as local variable and the variable
5. for f in L: definition is confined only to that function.
6. print(f(3)) 33. What will be the output of the following Python
a) code?
27 Page 303 of 391
81 i=0
Page 302 of 391 def change(i):
343 i=i+1
b) return i
69 change(1)
12 print(i)
c) a) 1
9 b) Nothing is displayed
27 c) 0
120

81 d) An exception is thrown
d) None of the mentioned Answer: c
Page

Answer: c Explanation: Any change made in to an immutable

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


data type in a function isn’t reflected def change(i = 1, j = 2):
outside the function. i=i+j
34. What will be the output of the following Python j=j+1
code? print(i, j)
def a(b): change(j = 1, i = 2)
b = b + [5] a) An exception is thrown because of conflicting
c = [1, 2, 3, 4] values
a(c) b) 1 2
print(len(c)) c) 3 3
a) 4 d) 3 2
b) 5 Answer: d
c) 1 Explanation: The values given during function call is
d) An exception is thrown taken into consideration, that is, i=2
Answer: b and j=1.
Explanation: Since a list is mutable, any change made 37. What will be the output of the following Python
in the list in the function is reflected code?
outside the function. def change(one, *two):
35. What will be the output of the following Python print(type(two))
code? change(1,2,3,4)
a=10 a) Integer
b=20 b) Tuple
def change(): c) Dictionary
global b d) An exception is thrown
a=45 Answer: b
b=56 Explanation: The parameter two is a variable
change() parameter and consists of (2,3,4). Hence the
print(a) data type is tuple.
print(b) 38. If a function doesn’t have a return statement,
a) which of the following does the function
10 return?
56 a) int
b) b) null
45 c) None
56 d) An exception is thrown without the return
Page 304 of 391 statement
c) Page 305 of 391
10 Answer: c
20 Explanation: A function can exist without a return
d) Syntax Error statement and returns None if the function
Answer: a doesn’t have a return statement.
Explanation: The statement “global b” allows the 39. What will be the output of the following Python
global value of b to be accessed and code?
changed. Whereas the variable a is local and hence def display(b, n):
the change isn’t reflected outside the while n > 0:
121

function. print(b,end="")
36. What will be the output of the following Python n=n-1
Page

code? display('z',3)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) zzz 43. The function pow(x,y,z) is evaluated as:
b) zz a) (x**y)**z
c) An exception is executed b) (x**y) / z
d) Infinite loop c) (x**y) % z
Answer: a d) (x**y)*z
Explanation: The loop runs three times and ‘z’ is Answer: c
printed each time. Explanation: The built-in function pow() can accept
40. What will be the output of the following Python two or three arguments. When it takes in
code? two arguments, they are evaluated as x**y. When it
def find(a, **b): takes in three arguments, they are
print(type(b)) evaluated as (x**y)%z.
find('letters',A='1',B='2') 44. What will be the output of the following Python
a) String function?
b) Tuple all([2,4,0,6])
c) Dictionary a) Error
d) An exception is thrown b) True
Answer: c c) False
Explanation: b combines the remaining parameters d) 0
into a dictionary. Answer: c
41. Which of the following functions is a built-in Explanation: The function all returns false if any one
function in python? of the elements of the iterable is zero
a) seed() and true if all the elements of the iterable are non
b) sqrt() zero. Hence the output of this function will
c) factorial() be false.
d) print() 45. What will be the output of the following Python
Answer: d expression?
Explanation: The function seed is a function which is round(4.5676,2)?
present in the random module. The a) 4.5
functions sqrt and factorial are a part of the math b) 4.6
module. The print function is a built-in c) 4.57
function which prints a value directly to the system d) 4.56
output. Answer: c
42. What will be the output of the following Python Explanation: The function round is used to round off
expression? the given decimal number to the
round(4.576) specified decimal places. In this case, the number
a) 4.5 should be rounded off to two decimal
b) 5 places. Hence the output will be 4.57.
c) 4 46. What will be the output of the following Python
d) 4.6 function?
Page 306 of 391 any([2>8, 4>2, 1>2])
Answer: b a) Error
Explanation: This is a built-in function which rounds a b) True
number to give precision in decimal c) False
digits. In the above case, since the number of d) 4>2
122

decimal places has not been specified, the Page 307 of 391
decimal number is rounded off to a whole number. Answer: b
Page

Hence the output will be 5. Explanation: The built-in function any() returns true if

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


any or more of the elements of the d) -4
iterable is true (non zero), If all the elements are Page 308 of 391
zero, it returns false. Answer: b
47. What will be the output of the following Python Explanation: The function max() is being used to find
function? the maximum value from among -3, -4
import math and false. Since false amounts to the value zero,
abs(math.sqrt(25)) hence we are left with min(0, 2, 7) Hence
a) Error the output is 0 (false).
b) -5 51. What will be the output of the following Python
c) 5 functions?
d) 5.0 chr(‘97’)
Answer: d chr(97)
Explanation: The abs() function prints the absolute a)
value of the argument passed. For a
example: abs(-5)=5. Hence, in this case we get Error
abs(5.0)=5.0. b)
48. What will be the output of the following Python ‘a’
function? a
sum(2,4,6) c)
sum([1,2,3]) Error
a) Error, 6 a
b) 12, Error d)
c) 12, 6 Error
d) Error, Error Error
Answer: a Answer: c
Explanation: The first function will result in an error Explanation: The built-in function chr() returns the
because the function sum() is used to alphabet corresponding to the value given
find the sum of iterable numbers. Hence the as an argument. This function accepts only integer
outcomes will be Error and 6 respectively. type values. In the first function, we have
49. What will be the output of the following Python passed a string. Hence the first function throws an
function? error.
all(3,0,4.2) 52. What will be the output of the following Python
a) True function?
b) False complex(1+2j)
c) Error a) Error
d) 0 b) 1
Answer: c c) 2j
Explanation: The function all() returns ‘True’ if any d) 1+2j
one or more of the elements of the Answer: d
iterable are non zero. In the above case, the values Explanation: The built-in function complex() returns
are not iterable, hence an error is thrown. the argument in a complex form. Hence
50. What will be the output of the following Python the output of the function shown above will be 1+2j.
function? 53. What is the output of the function complex()?
min(max(False,-3,-4), 2,7) a) 0j
123

a) 2 b) 0+0j
b) False c) 0
Page

c) -3 d) Error

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: a a) Error
Explanation: The complex function returns 0j if both b) [(1, 2), (2, 3)]
of the arguments are omitted, that is, if c) [(0, 2), (1, 3)]
the function is in the form of complex() or d) [(2, 3)]
complex(0), then the output will be 0j. Answer: c
Page 309 of 391 Explanation: The built-in function enumerate()
54. The function divmod(a,b), where both ‘a’ and ‘b’ accepts an iterable as an argument. The
are integers is evaluated as: Page 310 of 391
a) (a%b, a//b) function shown in the above case returns containing
b) (a//b, a%b) pairs of the numbers given, starting
c) (a//b, a*b) from 0. Hence the output will be: [(0, 2), (1,3)].
d) (a/b, a%b) 58. What will be the output of the following Python
Answer: b functions?
Explanation: The function divmod(a,b) is evaluated as x=3
a//b, a%b, if both ‘a’ and ‘b’ are eval('x^2')
integers. a) Error
55. What will be the output of the following Python b) 1
function? c) 9
divmod(10.5,5) d) 6
divmod(2.4,1.2) Answer: b
a) Explanation: The function eval is use to evaluate the
(2.00, 0.50) expression that it takes as an argument.
(2.00, 0.00) In the above case, the eval() function is used to
b) perform XOR operation between 3 and 2.
(2, 0.5) Hence the output is 1.
(2, 0) 59. What will be the output of the following Python
c) functions?
(2.0, 0.5) float('1e-003')
(2.0, 0.0) float('2e+003')
d) a)
(2, 0.5) 3.00
(2) 300
Answer: c b)
Explanation: See python documentation for the 0.001
function divmod. 2000.0
56. The function complex(‘2-3j’) is valid but the c)
function complex(‘2 – 3j’) is invalid. 0.001
a) True 200
b) False d)
Answer: a Error
Explanation: When converting from a string, the 2003
string must not contain any blank spaces Answer: b
around the + or – operator. Hence the function Explanation: The output of the first function will be
complex(‘2 – 3j’) will result in an error. 0.001 and that of the second function
124

57. What will be the output of the following Python will be 2000.0. The first function created a floating
function? point number up to 3 decimal places and
Page

list(enumerate([2, 3])) the second function adds 3 zeros after the given

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


number. -12345.0 (5 blank spaces before the number) a
60. Which of the following functions does not b) -12345.0 )
necessarily accept only iterables as c) Error
arguments? d) -12345.000000000…. (infinite decimal places)
a) enumerate() Answer: b
b) all() Explanation: The function float() will remove all the
c) chr() blank spaces and convert the integer to
d) max() a floating point number. Hence the output will be: -
Answer: c 12345.0.
Explanation: The functions enumerate(), all() and 64. What will be the output of the following Python
max() accept iterables as arguments function?
Page 311 of 391 ord(65)
whereas the function chr() throws an error on ord(‘A’)
receiving an iterable as an argument. Also note a)
that the function chr() accepts only integer values. A
61. Which of the following functions accepts only 65
integers as arguments? b)
a) ord() Error
b) min() 65
c) chr() Page 312 of 391
d) any() c)
Answer: c A
Explanation: The function chr() accepts only integers Error
as arguments. The function ord() d)
accepts only strings. The functions min() and max() Error
can accept floating point as well as Error
integer arguments. Answer: b
62. Suppose there is a list such that: l=[2,3,4]. If we Explanation: The built-in function ord() is used to
want to print this list in reverse order, return the ASCII value of the alphabet
which of the following methods should be used? passed to it as an argument. Hence the first function
a) reverse(l) results in an error and the output of the
b) list(reverse[(l)]) second function is 65.
c) reversed(l) 65. What will be the output of the following Python
d) list(reversed(l)) function?
Answer: d float(‘-infinity’)
Explanation: The built-in function reversed() can be float(‘inf’)
used to reverse the elements of a list. a)
This function accepts only an iterable as an –inf
argument. To print the output in the form of a inf
list, we use: list(reversed(l)). The output will be: b)
[4,3,2]. –infinity
63. What will be the output of the following Python inf
function? c)
float(' -12345\n') Error
125

(Note that the number of blank spaces before the Error


number is 5) d)
Page

Error

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Junk value 69. What will be the output of the following Python
Answer: a function?
Explanation: The output of the first function will be – len(["hello",2, 4, 6])
inf and that of the second function will a) 4
be inf. b) 3
66. Which of the following functions will not result in c) Error
an error when no arguments are d) 6
passed to it? Answer: a
a) min() Explanation: The function len() returns the length of
b) divmod() the number of elements in the iterable.
c) all() Therefore the output of the function shown above is
d) float() 4.
Answer: d 70. What will be the output of the following Python
Explanation: The built-in functions min(), max(), function?
divmod(), ord(), any(), all() etc throw an oct(7)
error when no arguments are passed to them. oct(‘7’)
However there are some built-in functions like a)
float(), complex() etc which do not throw an error Error
when no arguments are passed to them. 07
The output of float() is 0.0. b)
67. What will be the output of the following Python 0o7
function? Error
hex(15) c)
Page 313 of 391 0o7
a) f Error
b) 0xF d)
c) 0Xf 07
d) 0xf 0o7
Answer: d Page 314 of 391
Explanation: The function hex() is used to convert the Answer: c
given argument into its hexadecimal Explanation: The function oct() is used to convert its
representation, in lower case. Hence the output of argument into octal form. This function
the function hex(15) is 0xf. does not accept strings. Hence the second function
68. Which of the following functions does not throw results in an error while the output of the
an error? first function is 0o7.
a) ord() 71. What is the type of each element in sys.argv?
b) ord(‘ ‘) a) set
c) ord(”) b) list
d) ord(“”) c) tuple
Answer: b d) string
Explanation: The function ord() accepts a character. Answer: d
Hence ord(), ord(”) and ord(“”) throw Explanation: It is a list of strings.
errors. However the function ord(‘ ‘) does not throw 72. What is the length of sys.argv?
an error because in this case, we are a) number of arguments
126

actually passing a blank space as an argument. The b) number of arguments + 1


output of ord(‘ ‘) is 32 (ASCII value c) number of arguments – 1
Page

corresponding to blank space). d) none of the mentioned

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: b Explanation: It is possible to pass function names as
Explanation: The first argument is the name of the arguments to other functions.
program itself. Therefore the length of 77. What will be the output of the following Python
sys.argv is one more than the number arguments. code?
73. What will be the output of the following Python def foo():
code? return total + 1
def foo(k): total = 0
k[0] = 1 print(foo())
q = [0] a) 0
foo(q) b) 1
print(q) c) error
a) [0] d) none of the mentioned
b) [1] Answer: b
c) [1, 0] Explanation: It is possible to read the value of a
d) [0, 1] global variable directly.
Answer: b 78. What will be the output of the following Python
Explanation: Lists are passed by reference. code?
74. How are keyword arguments specified in the def foo():
function heading? total += 1
a) one-star followed by a valid identifier return total
b) one underscore followed by a valid identifier total = 0
c) two stars followed by a valid identifier print(foo())
d) two underscores followed by a valid identifier a) 0
Answer: c b) 1
Explanation: Refer documentation. c) error
Page 315 of 391 d) none of the mentioned
75. How many keyword arguments can be passed to Page 316 of 391
a function in a single function call? Answer: c
a) zero Explanation: It is not possible to change the value of
b) one a global variable without explicitly
c) zero or more specifying it.
d) one or more 79. What will be the output of the following Python
Answer: c code?
Explanation: Zero keyword arguments may be passed def foo(x):
if all the arguments have default x = ['def', 'abc']
values. return id(x)
76. What will be the output of the following Python q = ['abc', 'def']
code? print(id(q) == foo(q))
def foo(fname, val): a) True
print(fname(val)) b) False
foo(max, [1, 2, 3]) c) None
foo(min, [1, 2, 3]) d) Error
a) 3 1 Answer: b
b) 1 3 Explanation: A new object is created in the function.
127

c) error 80. What will be the output of the following Python


d) none of the mentioned code?
Page

Answer: a def foo(i, x=[]):

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


x.append(i) a) set
return x b) list
for i in range(3): c) tuple
print(foo(i)) d) string
a) [0] [1] [2] Answer: b
b) [0] [0, 1] [0, 1, 2] Explanation: It is a list of elements.
c) [1] [2] [3] 85. What is the value stored in sys.argv[0]?
d) [1] [1, 2] [1, 2, 3] a) null
Answer: b b) you cannot access it
Explanation: When a list is a default value, the same c) the program’s name
list will be reused. d) the first argument
81. What will be the output of the following Python Answer: c
code? Explanation: Refer documentation.
def foo(k): 86. How are default arguments specified in the
k = [1] function heading?
q = [0] a) identifier followed by an equal to sign and the
foo(q) default value
print(q) b) identifier followed by the default value within
a) [0] backticks (“)
b) [1] c) identifier followed by the default value within
c) [1, 0] square brackets ([])
d) [0, 1] d) identifier
Answer: a Answer: a
Explanation: A new list object is created in the Explanation: Refer documentation.
function and the reference is lost. This can be 87. How are required arguments specified in the
checked by comparing the id of k before and after k = function heading?
[1]. a) identifier followed by an equal to sign and the
Page 317 of 391 default value
82. How are variable length arguments specified in Page 318 of 391
the function heading? b) identifier followed by the default value within
a) one star followed by a valid identifier backticks (“)
b) one underscore followed by a valid identifier c) identifier followed by the default value within
c) two stars followed by a valid identifier square brackets ([])
d) two underscores followed by a valid identifier d) identifier
Answer: a Answer: d
Explanation: Refer documentation. Explanation: Refer documentation.
83. Which module in the python standard library 88. What will be the output of the following Python
parses options received from the command code?
line? def foo(x):
a) getopt x[0] = ['def']
b) os x[1] = ['abc']
c) getarg return id(x)
d) main q = ['abc', 'def']
Answer: a print(id(q) == foo(q))
128

Explanation: getopt parses options received from the a) True


command line. b) False
Page

84. What is the type of sys.argv? c) None

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d) Error x=100
Answer: a print(x)
Explanation: The same object is modified in the x=+1
function. f1()
89. Where are the arguments received from the a) Error
command line stored? b) 100
a) sys.argv c) 101
b) os.argv d) 99
c) argv Answer: b
d) none of the mentioned Explanation: The variable x is a local variable. It is
Answer: a first printed and then modified. Hence
Explanation: Refer documentation. the output of this code is 100.
90. What will be the output of the following Python 93. What will be the output of the following Python
code? code?
def foo(i, x=[]): def san(x):
x.append(x.append(i)) print(x+1)
return x x=-2
for i in range(3): x=4
y = foo(i) san(12)
print(y) a) 13
a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]] b) 10
b) [[0], [[0], 1], [[0], [[0], 1], 2]] c) 2
c) [0, None, 1, None, 2, None] d) 5
d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]] Answer: a
Answer: c Explanation: The value passed to the function san() is
Explanation: append() returns None. 12. This value is incremented by one
Page 319 of 391 and printed. Hence the output of the code shown
91. What will be the output of the following Python above is 13.
code? 94. What will be the output of the following Python
def f1(): code?
x=15 Page 320 of 391
print(x) def f1():
x=12 global x
f1() x+=1
a) Error print(x)
b) 12 x=12
c) 15 print("x")
d) 1512 a) Error
Answer: c b) 13
Explanation: In the code shown above, x=15 is a local c)
variable whereas x=12 is a global 13
variable. Preference is given to local variable over x
global variable. Hence the output of the d) x
code shown above is 15. Answer: d
129

92. What will be the output of the following Python Explanation: In the code shown above, the variable
code? ‘x’ is declared as global within the
Page

def f1(): function. Hence the output is ‘x’. Had the variable ‘x’

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


been a local variable, the output would a = "world"
have been: f()
13 print(a)
x a)
95. What will be the output of the following Python hello
code? hello
def f1(x): world
global x b)
x+=1 world
print(x) hello
f1(15) hello
print("hello") c)
a) error hello
b) hello world
c) 16 world
d) d)
16 world
hello hello
Answer: a world
Explanation: The code shown above will result in an Answer: b
error because ‘x’ is a global variable. Explanation: Since the variable ‘a’ has been explicitly
Had it been a local variable, the output would be: 16 specified as a global variable, the
hello value of a passed to the function is ‘world’. Hence
96. What will be the output of the following Python the output of this code is:
code? world
x=12 hello
def f1(a,b=x): hello
print(a,b) 98. What will be the output of the following Python
x=15 code?
f1(4) def f1(a,b=[]):
Page 321 of 391 b.append(a)
a) Error return b
b) 12 4 print(f1(2,[3,4]))
c) 4 12 Page 322 of 391
d) 4 15 a) [3,2,4]
Answer: c b) [2,3,4]
Explanation: At the time of leader processing, the c) Error
value of ‘x’ is 12. It is not modified later. d) [3,4,2]
The value passed to the function f1 is 4. Hence the Answer: d
output of the code shown above is 4 12. Explanation: In the code shown above, the integer 2
97. What will be the output of the following Python is appended to the list [3,4]. Hence the
code? output of the code is [3,4,2]. Both the variables a and
def f(): b are local variables.
global a 99. What will be the output of the following Python
130

print(a) code?
a = "hello" def f(p, q, r):
Page

print(a) global s

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


p = 10 def f2(a,b):
q = 20 global x
r = 30 return a+b+x
s = 40 f1()
print(p,q,r,s) total = f2(1,2)
p,q,r,s = 1,2,3,4 print(total)
f(5,10,15) a) Error
a) 1 2 3 4 b) 7
b) 5 10 15 4 c) 8
c) 10 20 30 40 d) 15
d) 5 10 15 40 Answer: b
Answer: c Explanation: In the code shown above, the variable
Explanation: The above code shows a combination of ‘x’ has been declared as a global variable
local and global variables. The output under both the functions f1 and f2. The value
of this code is: 10 20 30 40 returned is a+b+x = 1+2+4 = 7.
100. What will be the output of the following Python 102. What will be the output of the following Python
code? code?
def f(x): x=100
print("outer") def f1():
def f1(a): global x
print("inner") x=90
print(a,x) def f2():
f(3) global x
f1(1) x=80
a) print(x)
outer a) 100
error b) 90
b) c) 80
inner d) Error
error Answer: a
c) Explanation: The output of the code shown above is
outer 100. This is because the variable ‘x’ has
inner been declared as global within the functions f1 and
d) error f2.
Page 323 of 391 103. Read the following Python code carefully and
Answer: a point out the global variables?
Explanation: The error will be caused due to the y, z = 1, 2
statement f1(1) because the function is def f():
nested. If f1(1) had been called inside the function, global x
the output would have been different and Page 324 of 391
there would be no error. x = y+z
101. What will be the output of the following Python a) x
code? b) y and z
x=5 c) x, y and z
131

def f1(): d) Neither x, nor y, nor z


global x Answer: c
Page

x=4 Explanation: In the code shown above, x, y and z are

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


global variables inside the function f. y a) error
and z are global because they are not assigned in the b)
function. x is a global variable because butter
it is explicitly specified so in the code. Hence, x, y and error
z are global variables. c)
104. Which of the following data structures is bitter
returned by the functions globals() and error
locals()? d) bitterbutter
a) list Answer: c
b) set Explanation: The output of the code shown above
c) dictionary will be ‘bitter’, followed by an error. The
d) tuple error is because the operand ‘+’ is unsupported on
Answer: c the types used above.
Explanation: Both the functions, that is, globals() and 108. What happens if a local variable exists with the
locals() return value of the data same name as the global variable you
structure dictionary. want to access?
105. What will be the output of the following Python a) Error
code? b) The local variable is shadowed
x=1 c) Undefined behavior
def cg(): d) The global variable is shadowed
global x Answer: d
x=x+1 Explanation: If a local variable exists with the same
cg() name as the local variable that you want
x to access, then the global variable is shadowed. That
a) 2 is, preference is given to the local
b) 1 variable.
c) 0 109. What will be the output of the following Python
d) Error code?
Answer: a a=10
Explanation: Since ‘x’ has been declared a global globals()['a']=25
variable, it can be modified very easily print(a)
within the function. Hence the output is 2. a) 10
106. On assigning a value to a variable inside a b) 25
function, it automatically becomes a global c) Junk value
variable. d) Error
a) True Answer: b
b) False Explanation: In the code shown above, the value of
Answer: b ‘a’ can be changed by using globals()
Explanation: On assigning a value to a variable inside function. The dictionary returned is accessed using
a function, t automatically becomes a key of the variable ‘a’ and modified to
local variable. Hence the above statement is false. 25.
Page 325 of 391 110. ______________ returns a dictionary of the
107. What will be the output of the following Python module namespace.
code? ________________ returns a dictionary of the
132

e="butter" current namespace.


def f(a): print(a)+e a)
Page

f("bitter") locals()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Page 326 of 391 b) When you open a file for writing, if the file does
globals() not exist, a new file is created
b) c) When you open a file for writing, if the file exists,
locals() the existing file is overwritten with the
locals() new file
c) d) All of the mentioned
globals() Answer: d
locals() Explanation: The program will throw an error.
d) 5. To read two characters from a file object infile, we
globals() use ____________
globals() a) infile.read(2)
Answer: c b) infile.read()
Explanation: The function globals() returns a c) infile.readline()
dictionary of the module namespace, whereas d) infile.readlines()
the function locals() returns a dictionary of the Answer: a
current namespace. Explanation: Execute in the shell to verify.
Page 327 of 391 Page 328 of 391
CHAPTER-4 – FILE HANDLING 6. To read the entire remaining contents of the file as
1. To open a file c:\scores.txt for reading, we use a string from a file object infile, we use
_____________ ____________
a) infile = open(“c:\scores.txt”, “r”) a) infile.read(2)
b) infile = open(“c:\\scores.txt”, “r”) b) infile.read()
c) infile = open(file = “c:\scores.txt”, “r”) c) infile.readline()
d) infile = open(file = “c:\\scores.txt”, “r”) d) infile.readlines()
Answer: b Answer: b
Explanation: Execute help(open) to get more details. Explanation: read function is used to read all the
2. To open a file c:\scores.txt for writing, we use lines in a file.
____________ 7. What will be the output of the following Python
a) outfile = open(“c:\scores.txt”, “w”) code?
b) outfile = open(“c:\\scores.txt”, “w”) 1. f = None
c) outfile = open(file = “c:\scores.txt”, “w”) 2. for i in range (5):
d) outfile = open(file = “c:\\scores.txt”, “w”) 3. with open("data.txt", "w") as f:
Answer: b 4. if i > 2:
Explanation: w is used to indicate that file is to be 5. break
written to. 6. print(f.closed)
3. To open a file c:\scores.txt for appending data, we a) True
use ____________ b) False
a) outfile = open(“c:\\scores.txt”, “a”) c) None
b) outfile = open(“c:\\scores.txt”, “rw”) d) Error
c) outfile = open(file = “c:\scores.txt”, “w”) Answer: a
d) outfile = open(file = “c:\\scores.txt”, “w”) Explanation: The WITH statement when used with
Answer: a open file guarantees that the file object is
Explanation: a is used to indicate that data is to be closed when the with block exits.
appended. 8. To read the next line of the file from a file object
133

4. Which of the following statements are true? infile, we use ____________


a) When you open a file for reading, if the file does a) infile.read(2)
Page

not exist, an error occurs b) infile.read()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) infile.readline() d) None of the mentioned
d) infile.readlines() Answer: a
Answer: c Explanation: The raw_input([prompt]) function reads
Explanation: Execute in the shell to verify. one line from standard input and
9. To read the remaining lines of the file from a file returns it as a string. This would prompt you to enter
object infile, we use ____________ any string and it would display same
a) infile.read(2) string on the screen. When I typed “Hello Python!”
b) infile.read() 13. What will be the output of the following Python
c) infile.readline() code?
d) infile.readlines() 1. str = input("Enter your input: ");
Answer: d 2. print "Received input is : ", str
Explanation: Execute in the shell to verify. a)
10. The readlines() method returns ____________ Enter your input: [x*5 for x in range(2,10,2)]
a) str Received input is : [x*5 for x in range(2,10,2)]
Page 329 of 391 b)
b) a list of lines Enter your input: [x*5 for x in range(2,10,2)]
c) a list of single characters Received input is : [10, 30, 20, 40]
d) a list of integers Page 330 of 391
Answer: b c)
Explanation: Every line is stored in a list and Enter your input: [x*5 for x in range(2,10,2)]
returned. Received input is : [10, 10, 30, 40]
11. Which are the two built-in functions to read a line d) None of the mentioned
of text from standard input, which by Answer: a
default comes from the keyboard? Explanation: None.
a) Raw_input & Input 14. Which one of the following is not attributes of
b) Input & Scan file?
c) Scan & Scanner a) closed
d) Scanner b) softspace
Answer: a c) rename
Explanation: Python provides two built-in functions d) mode
to read a line of text from standard Answer: c
input, which by default comes from the keyboard. Explanation: rename is not the attribute of file rest
These functions are: all are files attributes.
raw_input and input Attribute Description
12. What will be the output of the following Python file.closed Returns true if file is closed, false otherwise
code? file.mode Returns access mode with which file was op
1. str = raw_input("Enter your input: "); file.name Returns name of the file.
2. print "Received input is : ", str file.softspace Returns false if space explicitly required wit
a) 15. What is the use of tell() method in python?
Enter your input: Hello Python a) tells you the current position within the file
Received input is : Hello Python b) tells you the end position within the file
b) c) tells you the file is opened or not
Enter your input: Hello Python d) none of the mentioned
Received input is : Hello Answer: a
134

c) Explanation: The tell() method tells you the current


Enter your input: Hello Python position within the file; in other words,
Page

Received input is : Python the next read or write will occur at that many bytes

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


from the beginning of the file. Output:
16. What is the current syntax of rename() a file? Name of the file: foo.txt
a) rename(current_file_name, new_file_name) Line No 0 - This is 1st line
b) rename(new_file_name, current_file_name,) Line No 1 - This is 2nd line
c) rename(()(current_file_name, new_file_name)) Line No 2 - This is 3rd line
d) none of the mentioned Line No 3 - This is 4th line
Answer: a Line No 4 - This is 5th line
Explanation: This is the correct syntax which has 19. What is the use of seek() method in files?
shown below. a) sets the file’s current position at the offset
rename(current_file_name, new_file_name) b) sets the file’s previous position at the offset
17. What is the current syntax of remove() a file? c) sets the file’s current position within the file
a) remove(file_name) Page 332 of 391
b) remove(new_file_name, current_file_name,) d) none of the mentioned
c) remove(() , file_name)) Answer: a
Page 331 of 391 Explanation: Sets the file’s current position at the
d) none of the mentioned offset. The method seek() sets the file’s
Answer: a current position at the offset.
Explanation: remove(file_name) Following is the syntax for seek() method:
18. What will be the output of the following Python fileObject.seek(offset[, whence])
code? Parameters
1. fo = open("foo.txt", "rw+") offset — This is the position of the read/write pointer
2. print "Name of the file: ", fo.name within the file.
3. whence — This is optional and defaults to 0 which
4. # Assuming file has following 5 lines means absolute file positioning, other
5. # This is 1st line values are 1 which means seek relative to the current
6. # This is 2nd line position and 2 means seek relative to
7. # This is 3rd line the file’s end.
8. # This is 4th line 20. What is the use of truncate() method in file?
9. # This is 5th line a) truncates the file size
10. b) deletes the content of the file
11.for index in range(5): c) deletes the file size
12. line = fo.next() d) none of the mentioned
13. print "Line No %d - %s" % (index, line) Answer: a
14. Explanation: The method truncate() truncates the file
15.# Close opened file size. Following is the syntax for
16.fo.close() truncate() method:
a) Compilation Error fileObject.truncate( [ size ])
b) Syntax Error Parameters
c) Displays Output size — If this optional argument is present, the file is
d) None of the mentioned truncated to (at most) that size.
Answer: c 21. Which is/are the basic I/O connections in file?
Explanation: It displays the output as shown below. a) Standard Input
The method next() is used when a file is b) Standard Output
used as an iterator, typically in a loop, the next() c) Standard Errors
135

method is called repeatedly. This method d) All of the mentioned


returns the next input line, or raises StopIteration Answer: d
Page

when EOF is hit. Explanation: Standard input, standard output and

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


standard error. Standard input is the data Answer: d
that goes to the program. The standard input comes Explanation: None
from a keyboard. Standard output is Output:
where we print our data with the print keyword. Hello
Unless redirected, it is the terminal console. Python
The standard error is a stream where programs write 24. Which of the following mode will refer to binary
their error messages. It is usually the data?
text terminal. a) r
22. What will be the output of the following Python b) w
code? (If entered name is sanfoundry) c) +
1. import sys d) b
2. print 'Enter your name: ', Answer:d
3. name = '' Explanation: Mode Meaning is as explained below:
4. while True: r Reading
5. c = sys.stdin.read(1) w Writing
6. if c == '\n': a Appending
7. break b Binary data
Page 333 of 391 + Updating.
8. name = name + c Page 334 of 391
9. 25. What is the pickling?
10.print 'Your name is:', name a) It is used for object serialization
a) sanfoundry b) It is used for object deserialization
b) sanfoundry, sanfoundry c) None of the mentioned
c) San d) All of the mentioned
d) None of the mentioned Answer: a
Answer: a Explanation: Pickle is the standard mechanism for
Explanation: In order to work with standard I/O object serialization. Pickle uses a simple
streams, we must import the sys module. stack-based virtual machine that records the
The read() method reads one character from the instructions used to reconstruct the object. This
standard input. In our example we get a makes pickle vulnerable to security risks by
prompt saying “Enter your name”. We enter our malformed or maliciously constructed data, that
name and press enter. The enter key may cause the deserializer to import arbitrary
generates the new line character: \n. modules and instantiate any object.
Output: 26. What is unpickling?
Enter your name: sanfoundry a) It is used for object serialization
Your name is: sanfoundry b) It is used for object deserialization
23. What will be the output of the following Python c) None of the mentioned
code? d) All of the mentioned
1. import sys Answer: b
2. sys.stdout.write(' Hello\n') Explanation: We have been working with simple
3. sys.stdout.write('Python\n') textual data. What if we are working with
a) Compilation Error objects rather than simple text? For such situations,
b) Runtime Error we can use the pickle module. This
c) Hello Python module serializes Python objects. The Python objects
136

d) are converted into byte streams and


Hello written to text files. This process is called pickling.
Page

Python The inverse operation, reading from a file

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


and reconstructing objects is called deserializing or 29. Correct syntax of file.writelines() is?
unpickling. a) file.writelines(sequence)
27. What is the correct syntax of open() function? b) fileObject.writelines()
a) file = open(file_name [, access_mode][, buffering]) c) fileObject.writelines(sequence)
b) file object = open(file_name [, access_mode][, d) none of the mentioned
buffering]) Answer: c
c) file object = open(file_name) Explanation: The method writelines() writes a
d) none of the mentioned sequence of strings to the file. The sequence
Answer: b can be any iterable object producing strings, typically
Explanation: Open() function correct syntax with the a list of strings. There is no return
parameter details as shown below: value.
file object = open(file_name [, access_mode][, Syntax
buffering]) Following is the syntax for writelines() method:
Here is parameters’ detail: fileObject.writelines( sequence ).
file_name: The file_name argument is a string value 30. Correct syntax of file.readlines() is?
that contains the name of the file that a) fileObject.readlines( sizehint );
you want to access. b) fileObject.readlines();
access_mode: The access_mode determines the c) fileObject.readlines(sequence)
mode in which the file has to be opened, i.e., d) none of the mentioned
read, write, append, etc. A complete list of possible Answer: a
values is given below in the table. This is Explanation: The method readlines() reads until EOF
optional parameter and the default file access mode using readline() and returns a list
is read (r). containing the lines. If the optional sizehint argument
buffering: If the buffering value is set to 0, no is present, instead of reading up to
buffering will take place. If the buffering EOF, whole lines totalling approximately sizehint
value is 1, line buffering will be performed while bytes (possibly after rounding up to an
accessing a file. If you specify the internal buffer size) are read.
buffering value as an integer greater than 1, then Syntax
buffering action will be performed with the Following is the syntax for readlines() method:
indicated buffer size. If negative, the buffer size is the fileObject.readlines( sizehint );
system default(default behavior). Parameters
28. What will be the output of the following Python sizehint — This is the number of bytes to be read
code? from the file.
Page 335 of 391 31. In file handling, what does this terms means “r,
1. fo = open("foo.txt", "wb") a”?
2. print "Name of the file: ", fo.name a) read, append
3. fo.flush() b) append, read
4. fo.close() Page 336 of 391
a) Compilation Error c) write, append
b) Runtime Error d) none of the mentioned
c) No Output Answer: a
d) Flushes the file when closing them Explanation: r- reading, a-appending.
Answer: d 32. What is the use of “w” in file handling?
Explanation: The method flush() flushes the internal a) Read
137

buffer. Python automatically flushes the b) Write


files when closing them. But you may want to flush c) Append
Page

the data before closing any file. d) None of the mentioned

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Answer: b write(“Hello World”).
Explanation: This opens the file for writing. It will 37. Which function is used to write a list of string in a
create the file if it doesn’t exist, and if it file?
does, it will overwrite it. a) writeline()
fh = open(“filename_here”, “w”). b) writelines()
33. What is the use of “a” in file handling? c) writestatement()
a) Read d) writefullline()
b) Write Answer: a
c) Append Explanation: With the writeline function you can
d) None of the mentioned write a list of strings to a file
Answer: c fh = open(“hello.txt”, “w”)
Explanation: This opens the fhe file in appending lines_of_text = [“a line of text”, “another line of
mode. That means, it will be open for text”, “a third line”]
writing and everything will be written to the end of fh.writelines(lines_of_text).
the file. 38. Which function is used to close a file in python?
fh =open(“filename_here”, “a”). a) Close()
34. Which function is used to read all the characters? b) Stop()
a) Read() c) End()
b) Readcharacters() d) Closefile()
c) Readall() Answer: a
d) Readchar() Explanation: f.close()to close it and free up any
Answer: a system resources taken up by the open file.
Explanation: The read function reads all characters fh 39. Is it possible to create a text file in python?
= open(“filename”, “r”) a) Yes
content = fh.read(). b) No
35. Which function is used to read single line from c) Machine dependent
file? d) All of the mentioned
a) Readline() Answer: a
b) Readlines() Explanation: Yes we can create a file in python.
c) Readstatement() Creation of file is as shown below.
d) Readfullline() file = open(“newfile.txt”, “w”)
Answer: b file.write(“hello world in the new file\n”)
Explanation: The readline function reads a single line file.write(“and another line\n”)
from the file fh = open(“filename”, file.close().
Page 337 of 391 Page 338 of 391
“r”) 40. Which of the following are the modes of both
content = fh.readline(). writing and reading in binary format in
36. Which function is used to write all the file?
characters? a) wb+
a) write() b) w
b) writecharacters() c) wb
c) writeall() d) w+
d) writechar() Answer: a
Answer: a Explanation: Here is the description below
138

Explanation: To write a fixed sequence of characters “w” Opens a file for writing only. Overwrites the file
to a file if the file exists. If the file does not
Page

fh = open(“hello.txt”,”w”) exist, creates a new file for writing.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


“wb” Opens a file for writing only in binary format. d) fp.size
Overwrites the file if the file exists. If Answer: d
the file does not exist, creates a new file for writing. Explanation: fp.size has not been implemented.
“w+” Opens a file for both writing and reading. 45. How do you close a file object (fp)?
Overwrites the existing file if the file exists. a) close(fp)
If the file does not exist, creates a new file for b) fclose(fp)
reading and writing. c) fp.close()
“wb+” Opens a file for both writing and reading in d) fp.__close__()
binary format. Overwrites the existing Answer: c
file if the file exists. If the file does not exist, creates Explanation: close() is a method of the file object.
a new file for reading and writing 46. How do you get the current position within the
41. Which of the following is not a valid mode to file?
open a file? a) fp.seek()
a) ab b) fp.tell()
b) rw c) fp.loc
c) r+ d) fp.pos
d) w+ Answer: b
Answer: b Explanation: It gives the current position as an offset
Explanation: Use r+, w+ or a+ to perform both read from the start of file.
and write operations using a single file 47. How do you rename a file?
object. a) fp.name = ‘new_name.txt’
42. What is the difference between r+ and w+ b) os.rename(existing_name, new_name)
modes? c) os.rename(fp, new_name)
a) no difference d) os.set_name(existing_name, new_name)
b) in r+ the pointer is initially placed at the beginning Answer: b
of the file and the pointer is at the end Explanation: os.rename() is used to rename files.
for w+ 48. How do you delete a file?
c) in w+ the pointer is initially placed at the beginning a) del(fp)
of the file and the pointer is at the end b) fp.delete()
for r+ c) os.remove(‘file’)
d) depends on the operating system d) os.delete(‘file’)
Answer: b Answer: c
Explanation: none. Explanation: os.remove() is used to delete files.
43. How do you get the name of a file from a file 49. How do you change the file position to an offset
object (fp)? value from the start?
a) fp.name a) fp.seek(offset, 0)
b) fp.file(name) Page 340 of 391
c) self.__name__(fp) b) fp.seek(offset, 1)
d) fp.__name__() c) fp.seek(offset, 2)
Answer: a d) none of the mentioned
Explanation: name is an attribute of the file object. Answer: a
Page 339 of 391 Explanation: 0 indicates that the offset is with
44. Which of the following is not a valid attribute of a respect to the start.
file object (fp)? 50. What happens if no arguments are passed to the
139

a) fp.name seek function?


b) fp.closed a) file position is set to the start of file
Page

c) fp.mode b) file position is set to the end of file

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) file position remains unchanged d) f.readlines()
d) error Correct answer
Answer: d f.read(2)
Explanation: seek() takes at least one argument. 8. What is the correct syntax of rename() a file?
MULTIPLE CHOICE QUESTIONS: a) rename(current_file_name, new_file_name)
1. What is the use of “a” in file handling? b) rename(new_file_name, current_file_name,)
a) Read c) rename(()(current_file_name, new_file_name))
b) Write d) none of the mentioned
c) Append 9. Which of the following statements are true?
d) None of the mentioned a) When you open a file for reading an error occurs,
2. How do you rename a file? if the file does not exist
a) f.name = ‘new_name.txt’ b) When you open a file for writing a new file is
b) os.rename(old_file, new_name) created, if the file does not exist
c) os.set_name(old_file, new_name) c) When you open a file for writing, the existing file is
3. What is the use of seek() method in files? overwritten with the new
a) sets the file’s current position at the offset file, if the file exists,
b) sets the file’s previous position at the offset d) All of the mentioned
c) sets the file’s current position within the file 10.Which are the two built-in functions to read a line
d) none of the mentioned of text from standard input, which
Correct answer by default comes from the keyboard?
sets the file’s current position at the offset a) raw_input & Input
4. How do you get the name of a file from a file b) Input & Scan
object (f)? Page 342 of 391
a) f.name c) Scan & Scanner
b) f.file(name) d) Scanner
c) self.__name__(f) Correct answer
d) f.__name__() raw_input & Input
Correct answer 11.What will be the output of the following Python
Page 341 of 391 code?
f.name a) Compilation Error
5. What is the use of “w” in file handling? b) Runtime Error
a) Read c) No Output
b) Write d) Flushes the file when closing them
c) Append Correct answer
d) None of the mentioned Flushes the file when closing them
6. What is the correct syntax to remove() a file? 12.What happens if no arguments are passed to the
a) remove(file_name) seek function?
b) remove(new_file_name, current_file_name,) a) file position is set to the start of file
c) remove(() , file_name)) b) file position is set to the end of file
d) none of the mentioned c) file position remains unchanged
Correct answer d) error
remove(file_name) Correct answer
7. To read two characters from a file object f, we use error
____________ 13.To read the next line of the file from a file object f,
140

a) f.read(2) we use ___________


b) f.read() a) f.read(2)
Page

c) f.readline() b) f.read()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


c) f.readline() d) outfile = open(file = “c:\\test.txt”, “w”)
d) f.readlines() Correct answer
Correct answer outfile = open(“c:\\test.txt”, “a”)
f.readline() 19.What will be the output of the following Python
14.What is the use of truncate() method in file? code?
a) truncates the file size a) Compilation Error
b) deletes the content of the file b) Runtime Error
c) deletes the file size Page 344 of 391
d) none of the mentioned c)
Correct answer output
truncates the file size d)
15.Is it possible to create a text file in Python? Output
Page 343 of 391 20.Correct syntax of file.readlines() is?
a) Yes a) fileObject.readlines( sizehint );
b) No b) fileObject.readlines();
c) Machine dependent c) fileObject.readlines(sequence)
d) All of the mentioned d) none of the mentioned
Correct answer 21.Command to delete a file.
Yes a) del(fp)
16.Which of the following are the modes of both b) fp.delete()
writing and reading in binary format in c) os.remove(‘file’)
file? d) os.delete(‘file’)
a) wb+ 22.Which function is used to write all the characters?
b) w a) write()
c) wb b) writecharacters()
d) w+ c) writeall()
Correct answer d) writechar()
wb+ Correct answer
17.What is the difference between r+ and w+ write()
modes? 23.What is the correct syntax of open() function?
a) No difference a) file = open(file_name [, access_mode][, buffering])
b) In case of r+ the pointer is initially placed at the b) file object = open(file_name [, access_mode][,
beginning of the file and the buffering])
pointer is at the end for w+ c) file object = open(file_name)
c) In case of w+ the pointer is initially placed at the d) none of the mentioned
beginning of the file and the Correct answer
pointer is at the end for r+ file object = open(file_name [, access_mode][,
d) Depends on the operating system buffering])
Correct answer 24.Which of the following is not a valid attribute of a
In case of r+ the pointer is initially placed at the file object (f)?
beginning of the file and the Page 345 of 391
pointer is at the end for w+ a) f.name
18.To open a file c:\text.txt for appending data, we b) f.closed
use ___________ c) f.mode
141

a) outfile = open(“c:\\test.txt”, “a”) d) f.size


b) outfile = open(“c:\\test.txt”, “rw”) Correct answer
Page

c) outfile = open(file = “c:\test.txt”, “w”) f.size

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


25.Which one of the following is not attributes of Correct answer
file? fp.close()
a) closed 32.Correct syntax of file.writelines() is?
b) softspace a) file.writelines(sequence)
c) rename b) fileObject.writelines()
d) mode c) fileObject.writelines(sequence)
26.Which function is used to read single line from d) none of the mentioned
file? 33.What will be the output of the following Python
a) readline() code?
b) readlines() a) w3resource
c) readstatement() b) w3resource , w3resource
d) readfullline() c) w3r
27.Which of the following mode will refer to binary d) None of the mentioned
data? 34.What will be the output of the following Python
a) r code?
b) w Page 347 of 391
c) + a) True
d) b b) False
28.To open a file c:\text.txt for reading, we use c) None
_____________ d) Error
a) f = open(“c:\test.txt”, “r”) Correct answer
b) f = open(“c:\\test.txt”, “r”) True
c) f = open(file = “c:\test.txt”, “r”) 35.In file handling, what does this terms means “r,
d) f = open(file = “c:\\test.txt”, “r”) a”?
Correct answer a) read, append
f = open(“c:\\test.txt”, “r”) b) append, read
29.Change the file position to an offset value from c) write, append
the starting position. d) none of the mentioned
a) fp.seek(offset, 0) Correct answer
b) fp.seek(offset, 1) read, append
c) fp.seek(offset, 2) 36.To open a file c:\text.txt for writing, we use
d) none of the mentioned ____________
Correct answer a) outfile = open(“c:\test.txt”, “w”)
fp.seek(offset, 0) b) outfile = open(“c:\\test.txt”, “w”)
Page 346 of 391 c) outfile = open(file = “c:\test.txt”, “w”)
30.What is the use of tell() method in python? d) outfile = open(file = “c:\\test.txt”, “w”)
a) Inform you the current position within the file Correct answer
b) Inform you the end position within the file outfile = open(“c:\\test.txt”, “w”)
c) Inform you the file is opened or not 37.Which function is used to write a list of string in a
d) None of the mentioned file?
Correct answer a) writeline()
Inform you the current position within the file b) writelines()
31.How do you close a file object (fp)? c) writestatement()
a) close(fp) d) writefullline()
142

b) fclose(fp) Correct answer


c) fp.close() writeline()
Page

d) fp.__close__() 38.Which function is used to read all the characters?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a) read() a) f.read(2)
b) readcharacters() b) f.read()
c) readall() c) f.readline()
d) readchar() d) f.readlines()
Correct answer Correct answer
Page 348 of 391 f.read()
read() Page 350 of 391
39.Which of the following is not a valid mode to MCQs – FILE HANDLING:
open a file? [1] Which of the following is not a correct statement
a) ab for binary files?
b) rw a) Easy for carrying data into buffer
c) r+ b) Much faster than other file systems
d) w+ c) Characters translation is not required
Correct answer d) Every line ends with new line character ‘\n’
rw [2] Which of the following file mode open a file for
40.The readlines() method returns ____________ reading and writing both in the binary
a) str file?
b) a list of lines a) r
c) a list of single characters b) rb
d) a list of integers c) rb+
41.Which function is used to close a file in Python? d) rwb
a) close() [3] Which of the following file mode opens a file for
b) stop() reading and writing both as well as
c) end() overwrite the existing file if the file exists otherwise
d) closefile() creates a new file?
Correct answer a) w
close() b) wb+
42.How do you get the current position within the c) wb
file? d) rwb
a) f.seek() [4] Which of the following file mode opens a file for
b) f.tell() append or read a binary file and moves
c) f.loc the files pointer at the end of the file if the file
d) f.pos already exist otherwise create a new file?
Correct answer a) a
f.tell() b) ab
43.To read the remaining lines of the file from a file c) ab+
object f, we use __________ d) a+
a) f.read(2) [5] Ms. Suman is working on a binary file and wants
b) f.read() to write data from a list to a binary file.
c) f.readline() Consider list object as l1, binary file suman_list.dat,
d) f.readlines() and file object as f. Which of the
Correct answer following can be the correct statement for her?
f.readlines() a) f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
44.To read the entire remaining contents of the file b) f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
143

as a string from a file object f, we c) f = open(‘sum_list’,’wb’); pickle.load(l1,f)


Page 349 of 391 d) f = open(‘sum_list’,’rb’); l1=pickle.load(f)
Page

use ___________ [6] Which option will be correct for reading file for

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


suman from q-5? d. None of these
–> Option ) f = open(‘sum_list’,’rb’); l1=pickle.load(f) 7. Which of the following is nor a proper file access
[7] In which of the file mode existing data will be mode?
intact in binary file? a. close
a) ab b. read
b) a c. write
c) w Page 352 of 391
d) wb d. append
[8]Which one of the following is correct statement? 8. To read 4th line from text file, which of the
Page 351 of 391 following statement is true?
a) import – pickle a. dt = f.readlines();print(dt[3])
b) pickle import b. dt=f.read(4) ;print(dt[3])
c) import pickle c. dt=f.readline(4);print(dt[3])
d) All of the above d. All of these
Data file handling in python – MCQs 9 Which of the following function flushes the files
1 Every file has its own identity associated with it. implicitly?
Which is known as – a. flush()
a. icon b. close()
b. extension c. open()
c. format d. fflush()
d. file type 10. Which of the following functions flushes the data
2 Which of the following is not a known file type? before closing the file?
a. .pdf a. flush()
b. jpg b. close()
c. mp3 c. open()
d. txp d. fflush()
3. In f=open(“data.txt”, “r”), r refers to __________. Page 353 of 391
a. File handle Q1. Which statement will read 5 characters from a
b. File object file(file object ‘f’)?
c. File Mode a. f.read()
d Buffer b. f.read(5)
4. EOL stands for c. f.reads(5)
a. End Of Line d. None of the above
b. End Of List Ans. b. f.read(5)
c. End of Lines Q2. Which function open file in python?
d. End Of Location a. open( )
5. Which of the following file types allows to store b. new( )
large data files in the computer memory? c. Open( )
a. Text Files d. None of the above
b. Binary Files Ans. a. open( )
c. CSV Files Q3. Processing of Text file is faster than binary
d. None of these files.(T/F)
6. Which of the following file types can be opened a. True
with notepad as well as ms excel? b. False
144

a. Text Files Ans. b. False


b. Binary Files Q4. Which mode create new file if the file does not
Page

c. CSV Files exist?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a. write mode a. f = open(‘data.txt’); f.read()
b. append mode b. f = open(‘data.txt’,’r’); f.read(n)
c. Both of the above c. myfile = open(‘data.txt’); f.readline()
d. None of the above d. f = open(‘data.txt’); f.readlines()
Ans. c. Both of the above Ans. c. myfile = open(‘data.txt’); f.readline()
Q5. Which statement will return one line from a file Q12. File in python is treated as sequence of
(file object is ‘f’)? ________________
a. f.readline( ) a. Bytes
b. f.readlines( ) b. Bites
c. f.read( ) c. bits
d. f.line( ) d. None of the above
Ans. a. f.readline( ) Ans. a. Bytes
Q6. readlines() method return _________ Page 355 of 391
a. String Q13. Which function is used to write data in binary
b. List mode?
c. Dictionary a. write
d. Tuple b. writelines
Ans. b. List c. pickle
Q7. EOF stands for _________________ d. dump
a. End of File Ans. d. dump
Page 354 of 391 Q14. Which function is used to force transfer of data
b. End off File from buffer to file?
c. End on File a. flush( )
d. End or File b. save( )
Ans. a. End of File c. move( )
Q8. Which function is used to read data from Text d. None of the above
File? Ans. a. flush( )
a. read( ) Q15. Let the file pointer is at the end of 3rd line in a
b. writelines( ) text file named “data.txt”. Which of the
c. pickle( ) following option can be used to read all the
d. dump( ) remaining lines?
Ans. a. read( ) a. f.read( )
Q9. Which of the following will read entire content of b. f.read(all)
file(file object ‘f’)? c. f.readline( )
a. f.reads( ) d. f.readlines( )
b. f.read( ) Ans. d. f.readlines( )
c. f.read(all) Q16. ____________________ module is used for
d. f.read( * ) serializing and de-serializing any Python
Ans. b. f.read( ) object structure.
Q10. Which symbol is used for append mode? a. pickle
a. ap b. unpickle
b. a c. pandas
c. w d. math
d. app Ans. a. pickle
145

Ans. b. a Q17. Which of the following error is returned when


Q11. Which of the following options can be used to we try to open a file in write mode
Page

read the first line of a text file data.txt? which does not exist?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a. FileNotFoundError d. File Handling
b. FileFoundError Ans. b. File Handle
c. FileNotExistError Q24. What is full form of CSV
d. None of the above a. Comma Separation Value
Ans. d. None of the above r b. Comma Separated Value
Q18. ______________ function returns the strings. Page 357 of 391
a. read( ) c. Common Syntax Value
b. readline( ) d. Comma Separated Variable
c. Both of the above Ans. b. Comma Separated Value
Page 356 of 391 Q25. Which statement will open file “data.txt” in
d. None of the above append mode?
Ans. c. Both of the above a. f = open(“data.txt” , “a”)
Q19. The syntax of seek() is: file_object.seek(offset [, b. f = Open(“data.txt” , “ab”)
reference_point]) c. f = new(“data.txt” , “a”)
What is reference_point indicate? d. open(“data.txt” , “a”)
a. reference_point indicates the starting position of Ans. a. f = open(“data.txt” , “a”)
the file object Q26. Fill in the blank
b. reference_point indicates the ending position of import pickle
the file object f=open("data.dat",'rb')
c. reference_point indicates the current position of d=_____________________.load(f)
the file object f.close()
d. None of the above. a. unpickle
Ans. a. reference_point indicates the starting b. pickling
position of the file object c. pickle
Q20. Identify the invalid mode from the following. d. pick
a. a Ans. c. pickle
b. r+ Q27. Which module to be imported to make the
c. ar+ following line functional?
d. w sys.stdout.write("ABC")
Ans. c. ar+ a. system
Q21. Which of the following is an invalid mode of file b. sys
opening? c. stdout
a. read only mode d. stdin
b. write only mode Ans. b. sys
c. read and write mode Q28. What error is returned by the following
d. write and append mode statement if the file does not exist?
Ans. d. write and append mode f=open("A.txt")
Q22. readlines( ) function returns all the words of the a. FileNotFoundError
file in the form of List. (T/F) b. NotFoundError
a. True c. FileNotFound
b. False d. FoundError
Ans. b. False Ans. a. FileNotFoundError
Q23. What is ‘f’ in the following statement? Page 358 of 391
f=open("Data.txt" , "r") Q29. Which statement will return error?
146

a. File Name import pickle


b. File Handle f=open("data.dat",'rb')
Page

c. Mode of file d=pickle.load(f)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


f.end() a. True
a. Statement 1 b. False
b. Statement 2 Ans. a. True
c. Statement 3 Q37. Fill in the blanks in the following code of writing
d. Statement 4 data in binary files. Choose the
Ans. d. Statement 4 answer for statement 1
Q30. Which of the following function takes two import ___________ # Statement 1
arguments? rec = [ ]
a. load( ) while True:
b. dump( ) rn = int(input("Enter"))
c. both of the above nm = input("Enter")
d. none of the above temp = [rn, nm]
Ans. b. dump( ) rec.append(temp)
Q31. Almost all the files in our computer stored as ch = input("Enter choice (Y/N)")
_______ File. if ch.upper == "N":
a. Text break
b. Binary f = open("stud.dat", "____________") #statement 2
c. CSV __________ .dump(rec, f) #statement 3
d. None of the above _______.close( ) # statement 4
Ans. b. Binary a. csv
Q32. Binary files are not in human readable b. unpickle
format.(T/F) c. pickle
a. True d. load
b. False Ans. c. pickle
Ans. a. True Q38. Refer to the above code and choose the option
Q33. .pdf and .doc are examples of __________ files. for statement2.
a. Text a. w
b. Binary b. w+
c. CSV c. wb
d. None of the above d. write
Ans. b. Binary Ans. c. wb
Q34. The syntax of seek() is:file_object.seek(offset [, Page 360 of 391
reference_point]) What all values can Q39. Refer to the above code (Q 38)and choose the
be given as a reference point? option for statement 3
a. 1 a. unpickle
b. 2 b. write
Page 359 of 391 c. pickle
c. 0 d. None of the above
d. All of the above Ans. c. pickle
Ans. d. All of the above Q40. Refer to the above code (Q 38)and choose the
Q35. There is no delimiter to end a line in binary option for statement 4.
files.(T/F) a. f
a. True b. rec
b. False c. file
147

Ans. a. True d. stud


Q36. seek( ) method is used for random access to the Ans. a. f
Page

file.(T/F) Q41. The syntax of seek() is:file_object.seek(offset [,

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


reference_point] What is the default d=f.read(5)
value of reference_point print(d) # First Print Statement
a. 0 f.seek(10)
b. 1 d=f.read(3)
c. 2 print(d) # Second Print Statement
d. 3 f.seek(13)
Ans. a. 0 d=f.read(5)
Q42. _______ function returns the current position print(d) # Third Print Statement
of file pointer. d=f.tell()
a. get( ) print(d) # Fourth Print Statement
b. tell( ) a. Hello
c. cur( ) b. Hell
d. seek( ) c. ello
Ans. b. tell( ) d. None of the above
Q43. f.seek(10,0) will move 10 bytes forward from Ans. a. Hello
beginning of file.(T/F) Q48. Refer to the above code (Q 47) : Write the
a. True output of Second Print Statement
b. False a. om
Ans. a. True b. me
Q44. Which statement will move file pointer 10 bytes c. co
backward from current position. d. None of the above
a. f.seek(-10, 0) Ans. b. me
b. f.seek(10, 0) Page 362 of 391
c. f.seek(-10, 1) Q49. Refer to the above code (Q 47) : Write the
d. None of the above output of Third Print Statement
Ans. c. f.seek(-10, 1) a. e to m
Page 361 of 391 b. e to my
Q45. When we open file in append mode the file c. to my
pointer is at the _________ of the file. d. None of the above
a. end Ans. c. to my
b. beginning Q50. Refer to the above code (Q 47) : Write the
c. anywhere in between the file output of Fourth Print Statement
d. second line of the file a. 17
Ans. a. end b. 16
Q46. When we open file in write mode the file c. 19
pointer is at the _______ of the file. d. 18
a. end Ans. d. 18
b. beginning Q51. A _____________ is a named location on a
c. anywhere in between the file secondary storage media where data are
d. second line of the file permanently stored for later access.
Ans. b. beginning a. file
Q47. Write the output of the First Print statements : b. variable
f=open("data.txt",'w') c. comment
f.write("Hello") d. token
148

f.write("Welcome to my Blog") Ans. a. file


f.close() Q52. A _____ file consists of human readable
Page

f=open("data.txt",'r') characters.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a. Binary Q59. open( ) function takes ____ as parameter.
b. Text a. File name
c. Both of the above b. Access mode
d. None of the above c. Both of the above
Ans. b. Text d. None of the above
Q53. Which of the following file require specific Ans. c. Both of the above
programs to access its contents? Q60. Identify the correct statement to open a file:
a. Binary a. f = open(“D:\\myfolder\\naman.txt”)
b. Text b. f = open(“D:\myfolder\naman.txt”)
c. CSV c. f = open(“D:myfolder#naman.txt”)
d. None of the above d. f = Open(“D:\myfolder\naman.txt”)
Ans. a. Binary Page 364 of 391
Q54. Which of the following file can be opened in Ans. a. f = open(“D:\\myfolder\\naman.txt”)
any text editor? Q61. Which of the following are the attributes of file
a. Binary handle?
b. Text a. closed
c. Both of the above b. name
d. None of the above c. mode
Page 363 of 391 d. All of the above
Ans. b. Text Ans. d. All of the above
Q55. Each line of a text file is terminated by a special Q62. Write the output of the following:
character, called the ________ >>> f = open("test.txt","w")
a. End of File >>> f.closed
b. End of Line a. True
c. End of Statement b. False
d. End of program c. Yes
Ans. b. End of Line d. No
Q56. Default EOL character in text file is ________ Ans. b. False
a. \n Q63. Write the output of the following:
b. \N >>> f = open("test.txt","w")
c. \t >>> f.mode
d. \l a. ‘w’
Ans. a. \n b. ‘r’
Q57. Which of the following file can be created in c. ‘a’
python? d. ‘w+’
a. Text File Ans. a. ‘w’
b. Binary File Q64. Write the output of the following:
c. CSV File >>> f = open("test.txt","w")
d. All of the above >>> f.name
Ans. d. All of the above a. ‘test’
Q58. In which of the following data store b. ‘test.txt’
permanently? c. ‘test.dat’
a. File d. file does not exist
b. Variable Ans. b. ‘test.txt’
149

c. Both of the above Q65. Write the output of the following:


d. None of the above >>> f = open("test.txt","w")
Page

Ans. a. File >>> f.close()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


>>> f.closed b. ‘+wb’
a. True c. Both of the above
b. False d. None of the above
Page 365 of 391 Ans. c. Both of the above
c. Yes Q72. In the given statement, the file myfile.txt will
d. No open in _______________ mode.
Ans. a. True myObject=open(“myfile.txt”, “a+”)
Q66. Which of the following attribute of file handle a. append and read
returns Boolean value? b. append and write
a. name c. append and read and binary
b. closed d. All of the above
c. mode Ans. a. append and read
d. None of the above Q73. Ravi opened the file myfile.txt in append mode.
Ans. b. closed In this file the file object/file handle
Q67. Ravi opened a file in python using open( ) will be at the __________
function but forgot to specify the mode. In a. beginning of the file
which mode the file will open? b. end of the file
a. write c. second line of the file
b. append d. the end of the first line
c. read Ans. b. end of the file
d. read and write both Q74. Ravi opened the file myfile.txt in write mode. In
Ans. c. read this file the file object/file handle will
Q68. Which of the following is invalid mode of be at the ______________
opening file? a. beginning of the file
a. r b. end of the file
b. rb c. second line of the file
c. +r d. the end of the first line
d. None of the above Ans. a. beginning of the file
Ans. d. None of the above Q75. Ravi opened the file myfile.txt in read mode. In
Q69. Which of the following mode will create a new this file the file object/file handle will
file, if the file does not exist? be at the _______________
a. ‘a’ a. beginning of the file
b. ‘a+’ b. end of the file
c. ‘+a’ c. second line of the file
d. All of the above d. the end of the first line
Ans. d. All of the above Ans. a. beginning of the file
Q70. Which of the following mode will open the file Page 367 of 391
in binary and read-only mode. Q76. Ravi opened a file in a certain mode. After
a. ‘r’ opening the file, he forgot the mode. One
b. ‘rb’ interesting fact about that mode is ” If the file
c. ‘r+’ already exists, all the contents will be
d. ‘rb+’ overwritten”. Help him to identify the correct mode.
Ans. b. ‘rb’ a. read mode
Page 366 of 391 b. write mode
150

Q71. Which of the following mode will opens the file c. append mode
in read, write and binary mode? d. binary and read mode
Page

a. ‘wb+ Ans. b. write mode

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Q77. Ram opened a file in a certain mode. After automatically.
opening the file, he forgot the mode. The Q82. Mohan wants to open the file to add some
interesting facts about that mode are ” If the file more content in the already existing file.
doesn’t exist, then a new file will be Suggest him the suitable mode to open the file.
created” and “After opening file in that mode the file a. read mode
handle will be at the end of the file” b. append mode
Help him to identify the correct mode. c. write mode
a. read mode d. All of the above
b. write mode Ans. b. append mode
c. append mode Q83. Aman jotted down few features of the “write
d. binary and read mode mode”. Help him to identify the valid
Ans. c. append mode features.
Q78. Which of the following function is used to close a. If we open an already existing file in write mode,
the file? the previous data will be erased
a. close( ) b. In write mode, the file object will be positioned
b. end( ) at the beginning of the file.
c. quit( ) c. In write mode, if the file does not exist then the
d. exit( ) new file will be created.
Ans. a. close( ) d. All of the above
Q79. open( ) function returns a file object called Ans. d. All of the above
______________ Q84. Ananya jotted down few features of the
a. object handle “append mode”. Help her to identify the valid
b. file handle features.
c. read handle a. If we open an existing file in append mode, the
d. write handle previous data will remain there.
Ans. b. file handle b. In append mode the file object will be positioned
Q80. Which of the following is the valid way to open at the end of the file.
the file? c. In append mode, if the file does not exist then the
a. with open (file_name, access_mode) as fo: new file will be created.
b. fo = open (file_name, access_mode) d. All of the above
c. Both of the above Ans. d. All of the above
d. None of the above Q85. Which of the following methods can be used to
Ans. c. Both of the above write data in the file?
Page 368 of 391 a. write( )
Q81. Rohan opened the file “myfile.txt” by using the b. writelines( )
following syntax. His friend told him c. Both of the above
few advantages of the given syntax. Help him to d. None of the above
identify the correct advantage. Ans. c. Both of the above
with open ("myfile.txt", "a") as file_object: Page 369 of 391
a. In case the user forgets to close the file explicitly Q86. Write the output of the following:
the file will closed automatically. >>> f = open("test.txt","w")
b. file handle will always be present in the >>> f.write("File\n#Handling")
beginning of the file even in append mode. a. 17
c. File will be processed faster b. 16
151

d. None of the above c. 14


Ans. a. In case the user forgets to close the file d. 15
Page

explicitly the file will closed Ans. c. 14

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Q87. Which of the following error is returned by the b. read(n)
given code: c. readlines( )
>>> f = open("test.txt","w") d. reading(n)
>>> f.write(345) Ans. b. read(n)
a. Syntax Error Q93. Write the output of the following:
b. TypeError f=open("test.txt","w+")
c. StringError f.write("File-Handling")
d. Run Time Error a=f.read(5)
Ans. b. TypeError print(a)
Q88. Which of the following method is used to clear a. Fileb. File
the buffer? c. File-H
a. clear( ) d. No Output
b. buffer( ) Ans. d. No Output
c. flush( ) Q94. Write the output of the following:
d. clean( ) f=open("test.txt","w+")
Ans. c. flush( ) f.write("File-Handling")
Q89. Which of the following method does not return f.seek(0)
the number of characters written in the a=f.read(5)
file. print(a)
a. write( ) a. Fileb. File
b. writelines( ) c. File-H
c. Both of the above d. No Output
d. None of the above Ans. a. File
Ans. b. writelines( ) Page 371 of 391
Q90. Fill in the blank in the given code: Q95. Write the output of the following:
>>> fo = open("myfile.txt",'w') f=open("test.txt","w+")
>>> lines = ["Hello \n", "Writing strings\n", "third f.write("FileHandling")
line"] f.seek(5)
>>> fo._____________(lines) a=f.read(5)
>>>myobject.close() print(a)
a. write( ) a. andli
b. writelines( ) b. Handl
c. writeline( ) c. eHand
d. None of the above d. No Output
Page 370 of 391 Ans. a. andli
Ans. b. writelines( ) Q96. Write the output of the following:
Q91. In order to read the content from the file, we f=open("test.txt","w+")
can open file in ___________________ f.write("FileHandling")
a. “r” mode f.seek(0)
b. “r+” mode a=f.read()
c. “w+” mode print(a)
d. All of the above a. File
Ans. d. All of the above b. Handling
Q92. Which of the following method is used to read a c. FileHandling
152

specified number of bytes of data from d. No Output


a data file. Ans. c. FileHandling
Page

a. read( ) Q97. Write the output of the following:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


f=open("test.txt","w+") d. None of the above
f.write("FileHandling") Ans. b. This code will read all the lines from the file.
f.seek(0) Q102. Write the output of the following:
a=f.read(-1) f=open("test.txt","w+")
print(a) L = ["My name\n", "is\n", "Amit"]
a. File f.writelines(L)
b. Handling f.seek(0)
c. FileHandling a=f.readlines()
d. No Output print(type(a))
Ans. c. FileHandling a. <class ‘tuple’>
Q98. Which of the following method reads one b. <class ‘list’>
complete line from a file? c. <class ‘string’>
a. read( ) Page 373 of 391
b. read(n) d. None of the above
c. readline( ) Ans. b. <class ‘list’>
d. readlines( ) Q103. Which of the following function return the
Ans. c. readline( ) data of the file in the form of list?
Page 372 of 391 a. read( )
Q99. Write the output of the following: b. read(n)
f=open("test.txt","w+") c. readline( )
f.write("File\nHandling") d. readlines( )
f.seek(0) Ans. d. readlines( )
a=f.readline(-1) Q104. Sanjeev has written a program which is
print(a) showing an error. As a friend of Sanjeev, help
a. File Handling him to identify the wrong statement.
b. FileHandling f=open("test.txt","w") #Statement1
c. File L = ["My name\n", "is\n", "Amit"] #Statement2
d. No Output f.writeline(L) #Statement3
Ans. c. File f.close() #Statement4
Q100. Write the output of the following: a. Statement1
f=open("test.txt","w+") b. Statement2
f.write("File\nHandling") c. Statement3
f.seek(0) d. Statement4
a=f.readline(2) Ans. c. Statement3
print(a) Q105. ____________________ function returns an
a. File\nHandling integer that specifies the current position
b. FileHandling of the file object in the file.
c. Fi a. seek( )
d. No Output b. tell( )
Ans. c. Fi c. disp( )
Q101. Select the correct statement about the code d. None of the above
given below: Ans. b. tell( )
>>> myobj=open("myfile.txt", 'r') Q106. _______ method is used to position the file
>>> print(myobj.readlines()) object at a particular position in a file.
153

a. This code will read one line from the file. a. tell( )
b. This code will read all the lines from the file. b. seek( )
Page

c. This code will read only last line from the file. c. put( )

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d. None of the above Ans. c. 065
Ans. b. seek( ) Page 375 of 391
Q107. In reference to the code given below, the file Q113. How many functions are used in the given
object will move _______ bytes. code?
file_object.seek(10, 0) fileobject=open("practice.txt","r")
a. 0 str = fileobject.readline()
b. 10 while str:
c. 5 print(str)
Page 374 of 391 str=fileobject.readline()
d. 4 fileobject.close()
Ans. b. 10 a. 3
Q108. Ravi wants to move the file object 5 bytes b. 4
from the current position of the file object. c. 5
As a friend of Ravi, help him to write the code. d. 6
a. file_object.seek(5, 1) Ans. c. 5
b. file_object.seek(1, 5) Q114. _________ method is used to write the
c. file_object.seek(5, 0) objects in a binary file.
d. file_object.seek(5, 2) a. write( )
Ans. a. file_object.seek(5, 1) b. dump( )
Q109. Write the output of the following code: c. load( )
f=open("test.txt","w+") d. writer( )
f.write("My name is Amit\n") Ans. b. dump( )
f.seek(5,0) Q115. _________ method is used to read data from a
a=f.read(5) binary file.
print(a) a. write( )
a. me i b. dump( )
b. ame is c. load( )
c. me is d. writer( )
d. Error Ans. c. load( )
Ans. c. me is Q116. Which module is to be imported for working in
Q111. Write the output of the following: binary file?
f=open("test.txt","r") a. unpickle
print(f.tell()) b. pickle
a. 1 c. pickling
b. 2 d. unpickling
c. -1 Ans. b. pickle
d. 0 Q117. Which of the following statement open the file
Ans. d. 0 “marker.txt” so that we can read
Q112. Write the output of the following: existing content from file?
f=open("test.txt","r") a. f = open(“marker.txt”, “r”)
print(f.tell(),end="6") b. f = Open(“marker.txt”, “r”)
f.seek(5) c. f = open(“marker.txt”, “w”)
print(f.tell()) d. None of the above
a. 165 Ans. a. f = open(“marker.txt”, “r”)
154

b. 650 Page 376 of 391


c. 065 Q118. Which of the following statement open the file
Page

d. 506 “marker.txt” as a blank file?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a. f = open(“marker.txt”, “r”) c. Text files are not in Human readable form.
b. f = open(“marker.txt”, “rb”) d. Text files can be opened in Text editor.
c. f = open(“marker.txt”, “w”) Ans. c. Text files are not in Human readable form.
d. None of the above Q124. Identify the statement which can not be
Ans. c. f = open(“marker.txt”, “w”) interpret from the given code:
Q119. Amit has written the following statement. He f = open("test.dat", "ab+")
is working with ______ a. test.dat is a binary file
f = open("data", "rb") b. reading operation can be done on test.dat
a. Text File c. appending operation can be done on test.dat
b. CSV File d. test.dat contains records about books
c. Binary File Ans. d. test.dat contains records about books
d. None of the above Q125. Which module is to be imported for CSV file?
Ans. c. Binary File a. pickle
Q120. Which of the following option is correct? b. unpickle
a. if we try to write in a text file that does not exist, c. csv
an error occurs d. pandas
b. if we try to read a text file that does not exist, the Ans. c. csv
file gets created. Q126. Write the output of the following code :
c. if we try to write on a text file that does not exist, import csv
the file gets Created. f = open(“data.csv”, ‘r’)
d. None of the value row = csv.reader(f)
Ans. c. if we try to write on a text file that does not print(row)
exist, the file gets Created. a. It prints the memory address where csv.reader
Q121. Correct syntax of tell( ) function is _________. object is stored
#f is file object b. It prints the first record of data.csv
a. f.tell( ) c. It prints all the records of data.csv
b. tell(f) d. None of the above
c. f_tell( ) Ans. a. It prints the memory address where
d. None of the above csv.reader object is stored
Ans. a. f.tell( ) Q127. _________ function help us to read the csv
Q122. The syntax of seek() is: file_object.seek(offset file.
[, reference_point]). a. reader( )
___________________ value of reference_point b. read( )
indicate end of file c. read(n)
a. 0 d. readline( )
b. 1 Ans. a. reader( )
c. 2 Q128. Write the output of the second print
d. 3 statement of the given code:
Ans. c. 2 f=open("test.txt","r")
Q123. Which of the following statement is wrong in print(f.read())
reference to Text file? f.seek(7)
a. A text file is usually considered as a sequence of print(f.read())
characters consisting of alphabets, Page 378 of 391
numbers and other special symbols. Output of first print statement is : MynameisAmit
155

b. Each line of a text file is terminated by a special a. isAmit


character. b. sAmit
Page

Page 377 of 391 c. Amit

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


d. eisAmit print(len(f.readlines()))
Ans. b. sAmit a. 4
Q129. Which of the following method returns an b. 5
integer value? c. 6
a. seek( ) d. 7
b. read( ) Ans. a. 4
c. tell( ) Q134. Write the output of the following code:
d. readline( ) f = open("data.txt","w")
Ans. c. tell( ) L=["My\n","name\n","is\n","amit"]
Q130. ___________ refers to the process of f.writelines(L)
converting the structure to a byte stream before f.close()
writing it to the file. f = open("data.txt","r")
a. pickling print(len(f.readline()))
b. unpickling a. 2
c. reading b. 3
d. writing c. 4
Ans. a. pickling d. 5
Q131. Fill in the blank in the given code : Ans. b. 3
import pickle Q135. Fill in the blank in the given code :
f = open("data.dat", "rb") import pickle
l = pickle._______(f) f = open("data.dat", "wb")
print(l) L = [1, 2, 3]
f.close() pickle._______
a. dump f.close()
b. load a. dump(f, L)
c. write b. load(f, L)
d. list c. dump(L, f)
Ans. b. load d. load(L, f)
Q132. Write the output of the following code: Ans. c. dump(L, f)
f = open("data.txt","w") Page 380 of 391
L=["My\n","name\n","is\n","amit"] Q136. Which of the following statement will return
f.writelines(L) attribute error?
f.close() a. print(len(f.readlines( ).split( ))) #f is file handle
f = open("data.txt","r") b. print(len(f.readline( ).split( ))) #f is file handle
print(len(f.read())) C. print(len(f.read( ).split( ))) #f is file handle
a. 13 d. None of the above
b. 14 Ans. a. print(len(f.readlines( ).split( )))
Page 379 of 391 Q137. Ravi is writing a program for counting the
c. 15 number of words in a text file named
d. 16 “data.txt”. He has written the incomplete code. Help
Ans. c. 15 him to complete the code.
Q133. Write the output of the following code: f = open("_________","r") # Statement 1
f = open("data.txt","w") d = f._________ # Statement 2
L=["My\n","name\n","is\n","amit"] nw = d._________ # Statement 3
156

f.writelines(L) print("Number of words are", _________(nw)) #


f.close() Statement 4
Page

f = open("data.txt","r") Identify the suitable code for blank space in the line

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


marked as Statement 1 (Refer Q 141)
a. “data.txt” a. w
b. data.txt b. a
c. “data” c. rb
d. data d. r
Ans. b. data.txt Ans. d. r
Q138. Identify the suitable code for blank space in Q143. Identify the correct option for Statement3
the line marked as Statement 2(Refer Q. (Refer Q 141)
137) a. readlines
a. readlines( ) b. readline
b. readline( ) c. read
c. read( ) d. reader
d. None of the above Ans. d. reader
Ans. c. read( ) Q144. Identify the correct option for Statement4
Q139. Identify the suitable code for blank space in (Refer Q 141)
the line marked as Statement 3(Refer Q. a. row
137) b. d
a. split( ) c. csv
b. break( ) d. i
c. words( ) Ans. a. row
d. jump( ) Page 382 of 391
Ans. a. split( ) Q145. Parth is writing a program to add/insert
Q140. Identify the suitable code for blank space in records in file “data.csv”. He has written the
the line marked as Statement 4(Refer Q. following code. As a programmer, help him to
137) execute it successfully.
a. length import csv
b. len field = [“Roll no” , “Name” , “Class”]
c. Len f = open(“_________” , ‘w’)
d. Length d=__________.writer(f) #Statement1
Page 381 of 391 d.writerow(field) #Statement2
Ans. b. len ch=’y’
Q141. Ananya was writing a program of reading data while ch==’y’ or ch==’Y’:
from csv file named “data.csv”. She rn=int(input(“Enter Roll number: “))
writes the incomplete code. As a friend of Ananya nm = input(“Enter name: “)
help her to complete the code. cls = input(“Enter Class: “)
________ csv #Statement1 rec=[_________] #Statement3
f=open("data.csv", '_______') #Statement2 d.writerow(rec)
d=csv.___________(f) #Statement3 ch=input(“Enter more record??(Y/N)”)
for __________ in d: #Statement4 f.close()
print(row) Identify the correct statement for Statement 1
Identify the suitable option for Statement 1 a. data
a. import b. data.csv
b. create c. file_data.csv
c. data d. None of the above
157

d. Import Ans. b. data.csv


Ans. a. import Q146. Identify the correct statement for Statement
Page

Q142. Identify the correct option for Statement2 2. (Refer Q. 145)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


a. CSV d. f1
b. csv Ans. b. d1
c. file Q151. Simran is writing a function by name
d. csv_ “bookshop” in which she is asking about book
Ans. b. csv name and price from the user and storing the details
Q147. Identify the correct statement for Statement in a file “book.txt”. Function is showing
3. (Refer Q. 145)
some error due to some missing words/commands.
a. rollno, name, class
As a programmer help her to write the
b. Roll no, Name, Class
c. rn, nm, cls correct program.
d. field _________________ bookshop: #Statement 1
Ans. c. rn, nm, cls b_name = input("Enter book name:")
Page 383 of 391 b_price=int(input("Enter book price:"))
Q148. Chinki is writing a program to copy the data data = _________________([b_name, b_price])
from “data.csv” to “temp.csv”. However #Statement 2
she is getting some error in executing the following f = open("book.txt","w")
program due to some missing f.write(_____________) #Statement 3
commands. Help her to execute it successfully. Page 384 of 391
import csv f.close()
f=open(“data.csv”,”r”)
Identify the correct option for Statement 1.
f1=open(“temp.csv”,’__________’) #Statement 1
a. def
d=csv._________(f)
b. Def
d1=csv.writer(f1) #Statement 2
for i in d: c. define
___________.writerow(i) d. Define
#Statement3
f.close( ) Ans. a. def
f1.close( ) Q152. Identify the correct option for Statement 2.
Identify the correct statement for Statement 1. a. int
a. r b. str
b. rb+ c. char
c. wa d. float
d. w Ans. b. str
Ans. d. w Q153. Identify the correct option for Statement 3.
Q149. Identify the correct statement for Statement a. data
2.(Refer Q148.) b. b_name
a. read c. b_price
b. reader( ) d. f
c. reader Ans. a. data
d. read(r) Page 385 of 391
Ans. c. reader 1.Which statement will read 5 characters from a
Q150. Identify the correct statement for Statement file(file object 'f')?
2.(Refer Q148.) f.read()
a. d f.read(5)
158

b. d1 f.reads(5)
c. f 2.Which function open file in python?
Page

open()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


new() 13.Which function is used to write data in binary
3.Processing of Text file is faster than binary mode?
files.(T/F) write
True writelines
False Pickle
4.Which mode create new file if the file does not dump
exist? 14.Which function is used to force transfer of data
write mode from buffer to file?
append mode flush()
both save()
5.Which statement will return one line from a file 15.Which function open file in python?
(file object is 'f')? open()
f.readline() new()
f.readlines() 16.readlines() method return?
f.read()f.line String
6.readlines() method return? List
String Dictionary
List 17.Which of the following error is returned when we
Dictionary try to open a file in read mode which
7.EOF stands for ? does not exist?
End of File FileNotFoundError
End on File FileFoundError
8.Which function is used to read data from Text File? FileNotExistError
read( ) 18._______ function returns the list of strings.
writelines read()
pickle readline()
dump readlines()
9.Which of the following will read entire content of 19.Which function is used to open file?
file(file object 'f')? new()
f.reads() create()
f.read() open()
f.read(all) 20.Identify the invalid mode from the following.
10.Which symbol is used for append mode? a
ap Page 387 of 391
aw r+
Page 386 of 391 ar+
11.Which statement will return one line from a file w
(file object is 'f')? Page 388 of 391
f.readline() Q21. Which of the following is not the mode of file
f.readlines() opening?
f.read()f.line read only mode
159

12.File in python is treated as sequence of _______? write only mode


Bytes read and write mode
Page

Bits write and append mode

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


Q22. readlines( ) function returns all the lines of file f=open("data.dat",'rb')
in the form of List. (T/F) d=pickle.load(f)
True f.end()
False Statement 1
Q23. What is 'f' in the following statement? Statement 2
f=open("Data.txt" , "r") Statement 3
File Name Statement 4
File Handle Q30. Which of the following function takes two
Mode of file arguments?
File Handling load( )
Q24. What is full form of CSV dump( )
Comma Separation Value Q31. Almost all the files in our computer stored as
Comma Separated Value _______ File.
Common Syntax Value Text
Q25. Which statement will open file "data.txt" in Binary
append mode? CSV
f = open("data.txt" , "a") None of the above
f = open("data.txt" , "ab") Q32. Binary files are not in human readable
f = new("data.txt" , "a") format.(T/F)
open("data.txt" , "a") True
Q26. Fill in the blank False
f=[ ] Q33. .pdf and .doc are examples of _______ files.
f = ______.load(fileobj) Text
unpickle Binary
pickling CSV
pickle Q34. Which module to be imported for working with
pick binary files.
Q27. Which module to be imported to make the load
following line functional? dump
sys.stdout.write("ABC") pickle
system csv
sys Page 390 of 391
stdout Q35. There is no delimiter to end a line in binary
stdin files.(T/F)
Page 389 of 391 False
Q28. What error is returned by the following True
statement if the file does not exist? Q36. seek( ) method is used for random access to the
f=open("A.txt") file.(T/F)
FileNotFoundError True
NotFoundError False
FileNotFound Q37. Fill in the blanks in the following code of writing
160

FoundError data in binary files. Choose the


Q29. Which statement will return error? answer for statement 1
Page

import pickle import ___________ # Statement 1

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience


rec = [ ]
while True:
rn = int(input("Enter"))
nm = input("Enter")
temp = [rn, nm]
rec.append(temp)
ch = input("Enter choice (Y/N)")
if ch.upper == "N":
break
f = open("stud.dat", "____________") #statement 2
__________ .dump(rec, f) #statement 3
_______.close( ) # statement 4
csv
unpickle
pickle
load
Q38. Refer to the above code and choose the option
for statement 2
w
w+
wb
Page 391 of 391
write
Q39. Refer to the above code and choose the option
for statement 3
unpickle
write
pickle
Q40. Refer to the above code and choose the option
for statement 4.
f
rec
filestud

161
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE, MCP, IAEngg - https://t.me/cbsecomputerscience

You might also like