You are on page 1of 162

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

Concatenates string1 and string2. interpreter/at compile time


It's a syntax error. Correct answer

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


interpreter/at runtime 17.A ___________ error does not cause the
12.Which of the following is correct? program 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 Pascal
a 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 A Python 3 program can always run on a Python 2
or 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


False /This is a comment/

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


//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
pass words (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
No unique number assigned to an object:
machine dependent refnum()
3
Page

Correct answer id()


Yes ref()

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


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
73 class
Any length they confuse the interpreter
Correct answer they are used to indicate global variables
Any length they slow down execution
39.How to swap two variables in one line ? Correct answer
x=y they are used to indicate a private variables of a
x ^= y ^= x ^= y class
x, y = y, x 46.Which of the following is not a keyword?
(x ^= y), (y ^= x), (x ^= y) pass
Correct answer class
x, y = y, x max
40.What is the maximum possible length of an def
identifier? 47.Which of the following are valid Python variable
31 characters names:
63 characters ver1.3
79 characters return
None of the above home_address
41.What is the output of the following code? route66
Age
0 4square
63 48.What is the output of the following code?
Error 50
None 100
42.Which of the following is an invalid statement? Error
num = 1,000,000 None
xyz=123 Correct answer
4
Page

x,y,z = 1, 2, 3 100
x_y_z = 1,000,000 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 let x = 100
is 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
5
Page

56.What is the output of the following code? characters allowed


25 unlimited length

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


none of the mentioned Error
Correct answer 69.What gets printed
unlimited length <class 'set'>
63.Which of the following is not a complex <class 'dict'>
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
6
Page

Error of different data types, convert all of


Correct answer them to the same type beforehand.

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


True 81.What is the return value of trunc()?
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
7
Page

Correct answer False


NameError Correct answer

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


False Correct answer
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
Integer dictionary 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, 100. What does ~5 evaluate to?
select all that apply (Python 3.xx) -5
a = 15 // 3 -7
a = int(15 / 3) -6
8
Page

a = 15 % 3 5
All of the mentioned Correct answer

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


-6 programming language that can not be used as
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
<class 'complex'> file.
<class 'list'> 05. What is output for - min(”hello world”)
Correct answer A. e
<class 'list'> B. a blank space character
Page 22 of 391 C. w
OBJECCTIVE TYPE QUESTIONS: D. hello world
01. In which year was the Python language View Answer
developed? Page 23 of 391
A. 1995 Answer : B
B. 1972 Explanation: python considers a blank space
C. 1981 character as the minimum value in a string.
D. 1989 06. How to output the string “May the odds favor
View Answer you” in Python?
Answer : D A. print(“May the odds favor you”)
Explanation: Python language was developed by B. echo(“May the odds favor you”)
Guido van Rossum in 1989 (late 1980s). C. System.out(“May the odds favor you”)
02. Who developed the Python language? D. printf(“May the odds favor you”)
A. Zim Den View Answer
B. Guido van Rossum Answer : A
C. Niene Stom Explanation: print() function is used to display
D. Wick van Rossum something to the user in python.
View Answer 07. In which year was the Python 3.0 version
Answer : B developed?
Explanation: Python language was developed by A. 2005
Guido van Rossum in the Netherlands in B. 2000
the late 1980s. C. 2010
03. How many keywords are there in python 3.7? D. 2008
A. 32 View Answer
B. 33 Answer : D
C. 31 Explanation: Python 3.0 version was developed on
D. 30 December 3, 2008.
View Answer 08. Which character is used in Python to make a
Answer : B single line comment?
9
Page

Explanation: There are 33 keywords in Python 3.7. A. /


Keywords are reserved words of the B. //

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


C. # Answer : D
D. ? Explanation: Class is not a python’s predefined data
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
D. None of these programming language, and it is also called
View Answer CPython.
Page 24 of 391 15. Do we need to compile a program before
Answer : A execution in Python?
Explanation: Python uses indentation to define A. No
blocks of code. Indentations are simply B. Yes
spaces or tabs used as an indicator that is part of View Answer
the indent code child as Curly braces are Page 25 of 391
used in the C programming language. Answer : A
11. Mathematical operations can be performed on Explanation: We don’t need to compile a program
a string in Python? State whether before execution in Python.
true or false: 16. How to convert the uppercase letters in the
A. False string to lowercase in Python?
B. True A. lowercase()
View Answer B. capilaize()
Answer : A C. lower()
Explanation: We can’t perform mathematical D. toLower()
operations on the string even if the string is in View Answer
the form: ‘1234…’. Answer : C
12. . Which one of the following is not a python’s Explanation: lower() function is used to convert
predefined data type? string into lower case in python.
A. List 17. How to capitalize only the first letter of a
B. Dictionary sentence in Python?
10

C. Tuple A. uppercase() method


Page

D. Class B. capitalize() method


View Answer C. upper() method

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


D. None of the above called operands. An expression involving
View Answer operators and operands is called an expression So,
Answer : B option C is correct.
Explanation: capitalize() method is used to 02. Which is the correct operator for power(xy)?
capitalize 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?
11

View Answer A. 4
Page

Answer : C B. 4.0
Explanation: The objects that operators act on are C. 0

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


D. 25 A. Nope, not a good idea.
View Answer B. Sure! Go for it.
Answer : B View Answer
Explanation: The result of standard division is Answer : A
always 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 >>> abs((1.1 + 2.2) – 3.3) < tolerance
integer 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
D. No error but no output too remember 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
12

09. Should you use the == operator to determine D. 36


Page

whether objects of type float are 3


equal? View Answer

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


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

A. not “Multiplication and Division” are at the same


Page

B. & precedence level. However, Multiplication and


C. * Division operators are at a higher precedence level

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


than Addition and Subtraction operators. variable, x with the value 7?
Page 32 of 391 A. int x
19. What is the output of the following code x=7
print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j)) B. int x=7
A. True True False True C. x=7
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(- A. 16
18 // 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.
Answer : B So, 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 B. 4.5
of 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
14

programming languages. the answer. So, Option A is correct.


Page

03. Which one of the following is the correct way 07. Which of the following is not a valid variable
of declaring and initializing a name in Python?

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


A. _var defined in advance in Python programming.
B. var_name To create a variable, you just assign it a value.
C. var11 12. Why does the name of local variables start
D. 5var with an underscore discouraged?
View Answer A. To identify the variable
Answer : D B. It confuses the interpreter
Explanation: 5var is not a valid variable name in C. It indicates a private variable of a class
python. D. None of these
08. What is the maximum length of an identifier in View Answer
python? Answer : C
A. 32 Explanation: Since there is no concept of private
B. 31 variables in Python language, majorly
C. 63 underscore is used to denote variables that cannot
D. None of the above be accessed from outside the class.
View Answer 13. Which of the following will run without errors?
Answer : D A. round(75.8)
Explanation: In python, the Identifier can be of any B. round()
length. So, Option D is correct. C. round(5352.898,9,5)
09. Which of the following declarations is D. round(6463.123,2,6)
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 B. 32var
successfully 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
D. None Of the above keyword, 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 15. Is Python case sensitive when dealing with
0 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 Page 36 of 391
it is assigned a value: C. Machine dependent
A. True D. None of the above
B. False View Answer
15

View Answer Answer : A


Page

Answer : B Explanation: Case is always significant.


Explanation: Variables need not be declared or 16. In which data type, indexing is not valid?

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


A. List list just leave the list as [].
B. String 21. If x=3.123, then int(x) will give ?
C. Dictionary A. 3.1
D. None of the above B. 0
View Answer C. 1
Answer : C D. 3
Explanation: Indexing is not valid in dictionary. View Answer
17. Select the correct example of complex Answer : D
datatype 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 D. All of the above
types 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 View Answer
true 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 property of data types.
in python? 24. In Python 3, the maximum value for an integer
A. List is 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
A. list=() the 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
16

Answer : D B. Tuple
Page

Explanation: List in python is created by writing C. Dictionary


values inside []. So, for creating an empty Page 38 of 391

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


D. Book C. -3
View Answer D. +3
Answer : D View Answer
Explanation: Book is not a data type Page 39 of 391
26. Which of the following is a valid way to specify Answer : B
the string literal foo'bar in Python: Explanation: ~x is equivalent to -(x+1).
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 D. Tupple
data 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 B. list[-1]
can 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
B. lower case element 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 2. What is the maximum possible length of an
trailing 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
17

30. What does ~4 evaluate to? Explanation: Identifiers can be of any length.
Page

A. -4 3. Which of the following is invalid?


B. -5 a) _a = 1

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


b) __a = 1 trailing underscores
c) __str__ = 1 c) underscore and ampersand are the only two
d) none of the mentioned special characters allowed
Answer: d d) none of the mentioned
Explanation: All the statements will execute Answer: a
successfully but at the cost of reduced Explanation: Variable names can be of any length.
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 names.
a 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 b) X**y
accessed 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
d) None of the mentioned integer 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
18

in Python? answer of this expression in python is 2. To get the


Page

a) unlimited length 2.5 answer, use floor division.


b) all private members must have leading and 3. What is the order of precedence in python?

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


i) Parentheses because exponential has higher
ii) Exponential precedence than multiplication, so 1**3 = 1 and
iii) Multiplication 3*1 = 3. Final answer is 3.
iv) Division 8. Which one of the following has the same
v) Addition precedence level?
vi) Subtraction a) Addition and Subtraction
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
a) 7 higher 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.
a) Left to Right Note 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
19

d) 1 d) Class
Page

Answer: c Answer: d
Explanation: First this expression will solve 1**3 Explanation: Class is a user defined data type.

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


2. Given a function that does not return any value, select all that apply (python 3.xx)
What value is thrown by default when a) x = 13 // 2
executed in shell. b) x = int(13 / 2)
a) int c) x = 13 % 2
b) bool d) All of the mentioned
c) void Answer: d
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 7. What error occurs when you execute the
object back. following 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 1. def example(a):
bytes 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
d) round(7463.123,2,1) strings
Answer: a c) hello2
Explanation: Execute help(round) in the shell to d) hello2hello2
get details of the parameters that are Answer: a
passed into the round function. Explanation: Python codes have to be indented
5. What is the return type of function id? properly.
a) int 9. What data type is the object below?
b) float L = [1, 23, 'hello', 1]
Page 47 of 391 a) list
c) bool b) dictionary
d) dict Page 48 of 391
Answer: a c) array
Explanation: Execute help(id) to find out details in d) tuple
python shell.id returns a integer Answer: a
value that is unique. Explanation: List data type can store any values
6. In python we do not specify types, it is directly within it.
interpreted by the compiler, so consider 10. In order to store values in terms of key and
20

the following operation to be performed. value we use what core data type.
Page

1. >>>x = 13 ? 2 a) list
objective is to make sure x has a integer value, b) tuple

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


c) class c) print(‘hello-‘ + ‘how-are-you’)
d) dictionary d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
Answer: d Answer: c
Explanation: Dictionary stores values in terms of Explanation: Execute in the shell.
keys and values. 15. What is the return value of trunc()?
11. Which of the following results in a SyntaxError? a) int
a) ‘”Once upon a time…”, she said.’ b) bool
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 Page 50 of 391
call. 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 Answer: c
Python 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
21

hello-how-are-you c) -3
Page

a) print(‘hello’, ‘how’, ‘are’, ‘you’) d) +3


b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4) Answer: a

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


Explanation: ~x is equivalent to -(x+1). off is exactly halfway through. See the below
5. What does ~~~~~~5 evaluate to? output.
a) +5 Here’s the runtime output for Python version 2.7
b) -11 interpreter.
c) +11 $ python
d) -5 Python 2.7.17 (default, Nov 7 2019, 10:07:09)
Page 51 of 391 >>> round(0.5)
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)) =
Explanation: ‘+’ cannot be converted to a float. 0 – 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 c) 0.75
is 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
22

round(-0.5) is -1 whereas in Python 3, Python Questions and Answers – Operator


Page

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

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


4/3*(2-1) is the same. a) 43
a) True b) 44
b) False Page 54 of 391
Answer: a c) 22
Explanation: Although the presence of parenthesis d) 23
does affect the order of Answer: b
precedence, in the case shown above, it is not Explanation: The expression shown above is an
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 decimal place.
is 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
16%15//16, which is equal to 1//16, the 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 c) 512, 512, 512
have 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,
23

5. What will be the value of x in the following which is equal to 512. Expression 2 is
Page

Python 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).

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


This is because the associativity of ** operator is evaluated as: 2+9*(36-8)/10, which
from right to left. Hence the result of simplifies to give 2+9*(2.8), which is equal to
the third expression is 512. 2+25.2 = 27.2. Hence the result of this
9. What is the value of the following expression? expression is 27.2.
8/4/2, 8/(4/2) 3. Which of the following expressions involves
Page 55 of 391 coercion when evaluated in Python?
a) (1.0, 4.0) a) 4.7 – 1.5
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:
Associativity – 2 4%3 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
expression? associativity 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 Answer: b
Python 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?
24

d) 27.2 float(4+int(2.39)%2)
Page

Answer: d a) 5.0
Explanation: The expression shown above is b) 5

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


c) 4.0 a) True
d) 4 b) False
Answer: c Answer: b
Explanation: The above expression is an example Explanation: The value of the expression
of explicit conversion. It is evaluated (2**2)**3 = 4**3 = 64. When the expression
as: float(4+int(2.39)%2) = float(4+2%2) = float(4+0) 2**2**3 is evaluated in python, we get the result
= 4.0. Hence the result of this as 256, because this expression is
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 a) 8
explicit 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
c) 77 Python 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
25

shown above is 7. Answer: a


Page

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)

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


yields the value 0010, which is equal to 2. Hence an error. Had we written this
the value of x is 8. expression as int(‘1011’,2), then there would not
4. What will be the output of the following Python be an error.
expression? 8. Which of the following represents the bitwise
int(1011)? XOR operator?
a) 1011 a) &
b) 11 b) ^
c) 13 c) |
d) 1101 d) !
Answer: a Answer: b
Explanation: The result of the expression shown Explanation: The ^ operator represent bitwise XOR
will 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
result 15. The expression is 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
equal to 1, else it gives 0. The binary form of 15 is and that of 0x75 is 1110101. On ORing these two
1111 and that of 12 is 1100. Hence values we get the output as: 1110101, which is
on performing the bitwise AND operation, we get equal to 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.
26

d) int(‘1011’) a) True
Page

Answer: c b) False
Explanation: The expression int(1011,2) results in Answer: b

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


Explanation: In most cases the value of two’s c) 1
complement is different from the d) 0
original value. However, there are cases in which Answer: c
the two’s complement value may be Explanation: Any odd number on being AND-ed
equal to the original value. For example, the two’s with 1 always gives 1. Any even
complement of 10000000 is also number on being AND-ed with this value always
equal to 10000000. Hence the statement is false. gives 0.
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
a) OR to 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 Answer: a
bits 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,
expression? the 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 a=a^b
form 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
27

Page 63 of 391 Answer: c


Page

a) 10 Explanation: The code shown above is used to


b) 2 swap the contents of two memory

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


locations using bitwise X0R operator. Hence the function does not amount to zero. In the first
output of the code shown above is: 20 example, the string ‘False’ is passed to
10. the function bool. This does not amount to zero
Page 64 of 391 and hence the output is true. In the
9. What is the two’s complement of -44? second function, an empty list is passed to the
a) 1011011 function bool. Hence the output is false.
b) 11010100 2. What will be the output of the following Python
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 - True
100 – 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?
28

Answer: d ['f', 't'][bool('spam')]


Page

Explanation: The Boolean function returns true if a) t


the argument passed to the bool b) f

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


c) No output the right operand must be true and
d) Error hence the right operand is returned in each of the
Answer: a above case.
Explanation: The line of code can be translated to 7. What will be the output of the following Python
state that ‘f’ is printed if the code?
argument passed to the Boolean function amount class Truth:
to zero. Else ‘t’ is printed. The pass
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,
b) [1, 0, 2, 0, ‘hello’, ”, []] the 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 elif (9 > 0) or False:
the 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)
29

operand is returned. This is because each function returns the output False.
Page

is evaluated from left to right. The expression -6>=0 and -6<=10 returns the
Since the left operand is false, it is assumed that output False.

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


The expression not(-6<10 or -6==10) returns the foundry”.
output False. 3. What will be the output of the following Python
The expression not(-6>10 or -6==10) returns the expression if x=456?
output True. print("%-06d"%x)
10. What will be the output of the following Python a) 000456
code snippet? b) 456000
not(10<20) and not(10>30) c) 456
a) True d) error
b) False Answer: c
c) Error Explanation: The expression shown above results
d) No output in 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
a) 00000hi order 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 a) print(“-ns”%S)
results 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
code snippet? a 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
30

spaces before a given string ‘X’. Hence the output Explanation: The given number is -122. Here the
Page

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

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


expression. In addition to this, there is a print("-%5d0",989)
negative sign in the given expression. Hence the a) True
output will be – -00122. b) False
7. What will be the output of the following Python Answer: b
expression if the value of x is 34? Explanation: The expression shown above does
print(“%f”%x) not result in an error. The output of
a) 34.00 this expression is -%5d0 989. Hence this statement
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 code snippet?
normally 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
c) 56.23 value, 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
Page 71 of 391 will 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 c) ‘There are %s %d birds.’ %[4, blue]
be 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.’
9. What will be the output of the following Python %(4, 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
c) 22.19 shown 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’
31

the decimal point) should be 5, b) ‘integers…1234…1234…123400’


Page

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’

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


Answer: a d) (‘3.3456789’, 3.3456789)
Explanation: The code shown above prints 1234 Answer: b
for the format specified %d, ‘1234 ’ Explanation: We can simply convert strings with a
for the format specifier %-6d (minus ‘-‘ sign %s format expression or the str
signifies left justification), and 001234 built-in function. Both of these methods have
for the format specifier %06d. Hence the output of been shown in this code. Hence the
this code is: output is: ) (‘3.3456789’, ‘3.3456789’)
‘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
Explanation: The %f %e and %g format specifiers the 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
c) Error by 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 Explanation: The built in function vars() returns a
formatting 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?
32

a) Error s='{0}, {1}, and {2}'


Page

b) (‘3.3456789’, ‘3.3456789’) s.format('hello', 'good', 'morning')


c) (3.3456789, 3.3456789) a) ‘hello good and morning’

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


b) ‘hello, good, morning’ order of the output be: {a}, {0}, {abc},
c) ‘hello, good, and morning’ hence the value of associated with {a} is printed
d) Error first followed by that of {0} and {abc}.
Answer: c Hence the output of the code shown above is: ‘2.5,
Explanation: Within the subject string, curly braces 10, [1, 2]’.
designate substitution targets and 13. What will be the output of the following Python
arguments to be inserted either by position or code?
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
'{a}, {0}, {abc}'.format(10, a=2.5, abc=[1, 2]) represent 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.
33

d) ’10, 2.5, [1, 2]’ Page 77 of 391


Page

Answer: b Python Questions and Answers – Advanced


Explanation: Since we have specified that the Formatting Tools

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


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

4. What will be the output of the following Python values substituted for p and q in the
Page

code? same order. Note that there is no blank space


hex(255), int('FF', 16), 0xFF between p and q. Hence the output is:

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


sanfoundry. b) 1.23,
8. What will be the output of the following Python c) (,1.23)
code? d) ‘1.23’
'The {} side {1} {2}'.format('bright', 'of', 'life') Answer: a
a) Error Explanation: The formatting expression accepts
b) ‘The bright side of life’ either a single substitution value, or a
c) ‘The {bright} side {of} {life}’ tuple of one or more items. Since single item can
Page 79 of 391 be given either by itself or within the
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 codes?
manual 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 ‘4.56’, ‘[4.56]’
is: ‘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 a) [‘ab’, ‘cd’]
since 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 Answer: a
the output of the code shown above: Explanation: The function upper() does not modify
‘1.2399’. a string in place, it returns a new
11. What will be the output of the following Python string which isn’t being stored anywhere.
35

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


Page

'%s' %((1.23,),) code?


a) ‘(1.23,)’ x = ['ab', 'cd']

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


for i in x: break
x.append(i.upper()) print(i)
print(x) i += 1
a) [‘AB’, ‘CD’] a) 5 6 7 8 9 10
b) [‘ab’, ‘cd’, ‘AB’, ‘CD’] b) 5 6 7 8
c) [‘ab’, ‘cd’] c) 5 6
d) none of the mentioned d) error
Answer: d Answer: b
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 code?
space 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 code?
becomes 7. i=2
5. What will be the output of the following Python while True:
code? if i%3 == 0:
36

i=5 break
Page

while True: print(i)


if i%0O11 == 0: i += 2

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


a) 2 4 6 8 10 … break
b) 2 4 else:
c) 2 3 print(0)
d) error a) 0 1 2 0
Answer: b b) 0 1 2
Explanation: The numbers 2 and 4 are printed. The c) error
next value of i is 6 which is d) none of the mentioned
divisible by 3 and hence control exits the loop. Answer: b
9. What will be the output of the following Python Explanation: The else part is not executed if
code? control 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 Answer: d
it’s 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=" ")
37

print(i) a) no output
Page

i += 1 b) i i i i i i …
if i == 3: c) a b c d e f

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


d) abcdef code?
Answer: a x = "abcdef"
Explanation: “i” is not in “abcdef”. i = "a"
5. What will be the output of the following Python while i in x[:-1]:
code? print(i, end = " ")
x = "abcdef" a) a a a a a
i = "a" b) a a a a a a
while i in x: c) a a a a a a …
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, x = "abcdef"
the 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, x = "abcdef"
the 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'
38

Explanation: The string x is being shortened by one for i in x:


Page

character in each iteration. print(i)


8. What will be the output of the following Python x.upper()

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


a) a B C D print(i.upper())
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) 1 2 3 4
Explanation: Changes do not happen in-place, Answer: c
rather a new instance of the string is Explanation: Objects of type int have no attribute
returned. upper().
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
39

code? c) error
Page

x = 'abcd' d) none of the mentioned


for i in range(len(x)): Answer: c

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


Explanation: Objects of type int aren’t for i in d:
subscriptable. However, if the statement was print(i)
x[i], an error would not have been thrown. a) 0 1 2
9. What will be the output of the following Python b) a b c
code snippet? 2 c 1 b c) 0 a
x = 'abcd' d) none of the mentioned
for i in range(len(x)): Answer: a
x = 'a' Explanation: Loops over the keys of the dictionary.
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 b) a b c
of 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.
40

2. What will be the output of the following Python 6. What will be the output of the following Python
Page

code? code?
d = {0: 'a', 1: 'b', 2: 'c'} d = {0: 'a', 1: 'b', 2: 'c'}

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


for x in d.values(): for x in d:
print(x) print(d.add(x))
a) 0 1 2 a) 0 1 2
b) a b c b) 0 1 2 0 1 2 0 1 2 …
2 c 1 b c) 0 a c) None None None
d) none of the mentioned d) None of the mentioned
Answer: b Answer: c
Explanation: Loops over the values. Explanation: Variable x takes the values 0, 1 and 2.
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 Answer: b
and prints them. Explanation: range(int(2.0)) is the same as
41

10. What will be the output of the following Python range(2).


Page

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


d = {0, 1, 2} code?

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


for i in range(float('inf')): b) d c b a
print (i) c) error
a) 0.0 0.1 0.2 0.3 … d) none of the mentioned
b) 0 1 2 3 … Answer: b
c) 0.0 1.0 2.0 3.0 … Explanation: [::-1] reverses the string.
d) none of the mentioned 8. What will be the output of the following Python
Answer: d code snippet?
Explanation: Error, objects of type float cannot be for i in '':
interpreted as an integer. print (i)
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
c) 0.0 1.0 2.0 3.0 … character 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 Answer: b
a 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
42

for i in 'abcd'[::-1]: Loops – 6


Page

print (i) 1. What will be the output of the following Python


a) a b c d code?

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


for i in range(10): print(i)
if i == 5: for i in x:
break print(i)
else: a) 0 1 2
print(i) b) error
else: c) 0 1 2 0 1 2
print("Here") d) none of the mentioned
a) 0 1 2 3 4 Here Answer: a
b) 0 1 2 3 4 5 Here Explanation: We can loop over a generator object
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 b) 0 1 2 2
generator object. c) 3 3 3 3
4. What will be the output of the following Python d) error
code? Page 99 of 391
43

Page 98 of 391 Answer: b


Page

x = (i for i in range(3)) Explanation: The value of a[-1] changes in each


for i in x: iteration.

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


8. What will be the output of the following Python error
code snippet? Correct answer
a = [0, 1, 2, 3] 0
for a[0] in a: 2. What will be the output of the following Python
print(a[0]) code snippet?
a) 0 1 2 3 True
b) 0 1 2 2 False
c) 3 3 3 3 None
d) error Error
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 code?
current 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 code snippet?
for 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
44

1. What will be the output of the following Python sr


Page

code? Correct answer


201 rs

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


8. What will be the output of the following Python 14.What will be the output of the following Python
code snippet? code snippet?
mn22qr Pq rs tu
mn22qr22 Pq rs tU
mnopqr22 Page 103 of 391
none of the mentioned Pq Rs Tu
Correct answer None of the mentioned
mn22qr22 Correct answer
9. What will be the output of the following Python Pq Rs Tu
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 hello\ code?
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
45

[‘pq’, ‘rs’, ‘tv\n’] Error


Page

Correct answer 20.What will be the output of the following Python


['pq', 'rs', 'tv'] code snippet?

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


(‘pqtv’) ('wx', 'yz', '')
(‘pqtv’, ‘rs’, ”) 27.What will be the output of the following Python
('pqtv', '', '') code snippet?
error Pq rs-tu
21.What will be the output of the following Python Pq Rs-tu
code? Pq Rs-Tu
Python fbb and fbb 28.None of the mentioned
Python 'fbb' and fbb 29.What will be the output of the following Python
Python fbb and ‘bin’ code snippet?
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']
46

('wx', 'yz', '') 34.What will be the output of the following Python
Page

none of the mentioned code snippet?


Correct answer 2,223,334,445

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


222,333,444,5 code snippet?
223334445 The sum of 2 and 12 is 14
Page 107 of 391 The sum of 10 and c is 16
Error The sum of 10 and a is c
Correct answer Error
2,223,334,445 41.What will be the output of the following Python
35.What will be the output of the following Python code?
code? error
pqrstv uty
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
38.What will be the output of the following Python encode()?
code? ascii
{88: 50, 89: 51, 90: 52} qwerty
{80: 50, 81: 51, 82: 52} utf-8
432 utf-16
234 Correct answer
Correct answer utf-8
{88: 50, 89: 51, 90: 52} 45.What will be the output of the following Python
39.What will be the output of the following Python code?
code? 12mnopqr12
Page 108 of 391 mnopqr1212
1pqrstv 1212mnopqr
pqrstv1 error
pqrstv Correct answer
error error
47

Correct answer 46.What will be the output of the following Python


Page

1pqrstv code?
40.What will be the output of the following Python x

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


2xy@ len(s)
xy size(s)
y s.size()
47.What will be the output of the following Python Correct answer
code? Page 111 of 391
\tboo s.__len__()
boo 53.What will be the output of the following Python
\boo statement?
none of the mentioned x
Correct answer yz
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
code snippet? output of example.count(‘l’)?
True 21
False Page 112 of 391
None None
Error 0
Correct answer Correct answer
True 2
48

52.To return the length of string s what command 58.What will be the output of the following Python
Page

do we execute? code?
s.__len__() 01

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


True Error
False None of the mentioned
Correct answer Correct answer
False Error
59.Say s=”hello” what will be the return value of 65.What will be the output of the following Python
type(s)? code?
int 201
bool error
str Correct answer
String 2
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?
49

code? 4350
Page

Python faa and bin Correct answer


Python (‘faa’, ‘bin’) and (‘faa’, ‘bin’) 5

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


Page 115 of 391 SRQP
71.What will be the output of the following Python 77.What will be the output of the following Python
code? code snippet?
pqr xyz ('rs')
PQR XYZ (")
Pqr xyz ('rs', ", ")
Pqr Xyz ('', 'rs', '')
72.What will be the output of the following Python Correct answer
code snippet? ('', 'rs', '')
['mn', 'qr', 'stop'] 78.What will be the output of the following Python
[‘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
50

PQRS pqrstv
Page

pqrs error
Correct answer none of the mentioned

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


Correct answer 89.What arithmetic operators cannot be used with
error strings?
83.What will be the output of the following Python +_
statement? All of the mentioned
Error Correct answer
Output equivalent to print ‘black\berry’ _
blackberry 90.What will be the output of the following Python
black berry code snippet?
Correct answer 2,223,334,445
blackberry 222,333,444,5
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
51

x.__ADD(y) True
Page

Correct answer 96.What will be the output of the following Python


x.__add__(y) code?

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


Page 121 of 391 pq rs tv
None None None of the mentioned
None 22 Correct answer
22 None None of the mentioned
Error is generated 103. What will be the output of the following
Correct answer Python code?
Error is generated (‘mn’, ‘op’, ‘qr’, ‘st’, ‘uv’)
97.What will be the output of the following Python ('mn', 'op', 'qrstuv')
code? (‘mnopqr’, ‘st, ‘uv’)
w error
world 104. What will be the output of the following
he Python 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
P Python 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 method.
Python 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 all of the mentioned
Python code? 107. What will be the output of the following
224 Python statement?
Error aqrQ
12 Correct answer
None q
Correct answer 108. What will be the output of the following
12 Python code?
102. What will be the output of the following Python bin and fab
52

Python code? Python fab and bin


Page

pq+rs+tv Error
pq++++++++rs++++++++tv None of the mentioned

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


Page 124 of 391 115. What will be the output of the following
Correct answer Python code?
Python fab and bin xyz. PQR
109. What will be the output of the following XYZ. PQR
Python code? Xyz. pqr
nthopy Xyz. Pqr
python 116. What will be the output of the following
hn Python code?
Correct answer Python fff and bbb
n Python (‘fff’, ‘bbb’) and (‘fff’, ‘bbb’)
110. What will be the output of the following Error
Python 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 int
Python code? bool
True str
23 118. What will be the output of the following
None of the mentioned Python code?
Correct answer rppq
2 rq
112. What will be the output of the following rppqrqrp
Python code? none of the mentioned
(‘pq’, ‘tv’) Correct answer
(‘pqtv’) rppq
('pq', 'rs', 'tv') 119. What will be the output of the following
2 Python code?
Page 125 of 391 xyz
113. What will be the output of the following 'xyz'
Python code? b’xyz’
error h’xyz’
rppqpqq Correct answer
r b’xyz’
pqr 120. What will be the output of the following
Correct answer Python code?
rppqpqq Python fff and bin
114. What will be the output of the following Python {name1} and {name2}
Python code? Error
Error Python and
-1 Correct answer
53

40 Error
Page

Correct answer 121. What will be the output of the following


4 Python code?

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


pq rs tu ____345.355
pqrstu _____345.354
pq\trs\ttu Correct answer
Page 127 of 391 ___345.355
pq rs tu Page 129 of 391
Correct answer 129. What will be the output of the following
pq rs tu Python code?
122. What will be the output of the following An exception is thrown
Python code? {0: 'X0', 1: 'X1', 2: 'X2', 3: 'X3', 4: 'X4'}
Python fff and bin {0: ‘X’, 1: ‘X’, 2: ‘X’, 3: ‘X’, 4: ‘X’}
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 fff and bin Python code snippet?
123. What will be the output of the following True
Python code? False
201 None
none of the mentioned Error
Correct answer Correct answer
2 True
124. What will be the output of the following 131. What will be the output of the following
Python code? Python 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 132. What will be the output of the following
Python code snippet? Python 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
ord('a'));? Python 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]}
54

“10.3f”) (_ indicates space). 134. What will be the output of the following
Page

__345.355 Python code snippet?


___345.355 0

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


None method del doesn’t exist for the dictionary
An exception is thrown del deletes the values in the dictionary
3 del deletes the entire dictionary
135. What will be the output of the following del deletes the keys in the dictionary
Python code? Correct answer
Syntax error del deletes the entire dictionary
“check” Page 133 of 391
Page 131 of 391 143. What will be the output of the following
{2: 'check', 3: 'check', 4: 'check'} Python code snippet?
{2:None,3:None,4:None} Counter({5: 4, 4: 4, 3: 2})
Correct answer {3:2}
{2: 'check', 3: 'check', 4: 'check'} [(5, 3), (3, 2)]
136. What will be the output of the following {4:3}
Python code? Correct answer
None [(5, 3), (3, 2)]
{ None:None, None:None, None:None} 144. What will be the output of the following
{1:None, 2:None, 3:None} Python 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
Method any() doesn’t exist for dictionary Python 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 Method update() doesn’t exist for dictionaries
Python 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
Counter({4: 2}) Python 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 {‘Numbers’: {2: 90}, ‘Letters’: {5: ‘A’}}
Python code snippet? 147. What will be the output of the following
Page 132 of 391 Python 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 148. What will be the output of the following
Python code snippet? Python code snippet?
865 {2,3,4,5}
55

An exception is thrown Counter({5, 4, 3, 2})


Page

142. What will be the output of the following Page 135 of 391
Python code snippet? Counter({5: 3, 2: 2, 4: 2, 3: 1})

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


{5: 3, 2: 3, 3: 4, 3: 2} Python code snippet?
Correct answer True
Counter({5: 3, 2: 2, 4: 2, 3: 1}) False
149. What will be the output of the following None
Python code? Error
An exception is thrown since the dictionary is 154. Suppose x = {“jack”:30, “henry”:35}, to delete
empty the entry for “jack” what
‘‘ command do we use?
1 x.delete(“jack”:30)
Error x.delete(“jack”)
Correct answer del x[“jack”]
Error del x(“jack”:30)
150. What will be the output of the following Correct answer
Python 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
the dictionary? and 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
Correct answer Python code?
{1,”A”,2”B”} ['X', 'Y', 'Z']
1. Suppose x = {“jack”:30, “henry”:35}. To obtain [‘Y’,’Z’,’X’]
the 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
Page 136 of 391 Python 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 [1,2,3,4]
Python 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
Error, syntax error for pop() method Python code?
{2: 6, 3: 4} {1: 'P', 2: 'Q', 3: 'R'}
56

Correct answer {1: ‘P’, 2: ‘S’, 3: ‘R’}


Page

{2: 6, 4: 5} Error, copy() method doesn’t exist for dictionaries


153. What will be the output of the following “None” is printed

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


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

165. What will be the output of the following Removes an arbitrary element
Page

Python code? Removes all the key-value pairs


{‘2’:2, ‘0’:0, ‘1’:1} Removes the key-value pair for the key given as an

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


argument Invalid syntax for get method
Invalid method for dictionary 177. What will be the output of the following
Correct answer Python code?
Removes an arbitrary element 123
171. What will be the output of the following ‘X’ ‘Y’ ‘Z’
Python code snippet? 1 ‘X’ 2 ‘Y’ 3 ‘Z’
Error as the key-value pair of 1:’A’ is already Error, it should be: for i in a.items():
deleted Correct answer
021 123
172. What will be the output of the following 178. What will be the output of the following
Python code snippet? Python code?
Page 142 of 391 dict_items([(1, 'P'), (2, 'Q'), (3, 'R')])
[“jack”:30, “john”:35] Syntax error
['jack', 'john'] dict_items([(1,2,3)])
(“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 180. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1
Python 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 [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
Python code snippet? 181. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], What is list1[-
1X2Y3Z 1]?
123 3510
XYZ Correct answer
1:”X” 2:”Y” 3:”Z” 0
Correct answer 182. Let list1 = [0.5 a for a in range(0, 4)], list1 is
1X2Y3Z ________
175. Which of the following isn’t true about [0, 1, 2, 3]
dictionary keys? [0, 1, 2, 3, 4]
More than one key isn’t allowed [0.0, 0.5, 1.0, 1.5]
Keys must be immutable [0.0, 0.5, 1.0, 1.5, 2.0]
Keys must be integers Correct answer
When duplicate keys encountered, the last [0.0, 0.5, 1.0, 1.5]
assignment wins 183. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], What is list1[:-
Correct answer 1]?
Keys must be integers 0
176. What will be the output of the following [1, 3, 2, 4, 5, 2, 1]
58

Python code snippet? [1, 3, 2, 4, 5, 2]


Page

Page 143 of 391 [1, 3, 2, 4, 5, 2, 1, 0]


14X Correct answer

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


[1, 3, 2, 4, 5, 2, 1] [‘olleh’]
184. What Will be The output Of the following code Correct answer
snippet? [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
Page 145 of 391 192. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1
11 after list1.pop(1)?
1 33 [3, 4, 5, 20, 5, 25, 1, 3]
31 [1, 3, 3, 4, 5, 5, 20, 25]
3 33 [3, 5, 20, 5, 25, 1, 3]
Correct answer [1, 3, 4, 5, 20, 5, 25]
3 33 [3, 1, 25, 5, 20, 5, 4]
185. Let list1 = [1, 3, 2, 4, 5, 2, 1, 0], Which of the Correct answer
following is correct? [3, 5, 20, 5, 25, 1, 3]
print(list1[0]) 193. To insert 5 to the third position in list1, use
print(list1[:2]) _______.
print(list1[:-2]) list1.insert(3, 5)
print(list1[4:6]) list1.insert(2, 5)
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]
59

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’] [25, 20, 5, 5, 4, 3, 3, 1]


Page

[‘hello’] [1, 3, 4, 5, 20, 5, 25, 3]


[‘llo’] [3, 1, 25, 5, 20, 5, 4, 3]

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


Correct answer ['pq']
[3, 1, 25, 5, 20, 5, 4, 3] ['rs']
198. Let list1 = [3, 4, 5, 20, 5, 25, 1, 3], what is list1 ['pqrs']
after list1.sort()? Correct answer
Page 148 of 391 ['p', 'q', 'r', 's']
[3, 4, 5, 20, 5, 25, 1, 3] Page 150 of 391
[1, 3, 3, 4, 5, 5, 20, 25] 205. What will be the output of the following code
[25, 20, 5, 5, 4, 3, 3, 1] snippet?
[1, 3, 4, 5, 20, 5, 25, 3] 234561
Correct answer 112345
[1, 3, 3, 4, 5, 5, 20, 25] 612345
199. What will be the output of the following code 12344
snippet? Correct answer
[2] [3] [4] 12344
123 206. What is list("a#b#c#d".split('#'))?
[2, 3, 4] ['a', 'b', 'c', 'd']
[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
60

2 5
Page

204. What is list("pqrs")? 211. To remove string "red" from list1, use
['p', 'q', 'r', 's'] _______.

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


list1.remove("red") 22345233452344523455
list1.remove(red) 22234522223453452345
list1.removeAll("red") Page 154 of 391
list1.removeOne("red") Correct answer
Correct answer 22345233452344523455
list1.remove("red") 220. What will be the output of the following code?
Page 152 of 391 1234
212. What will be the output of the following code? Correct answer
False 2
True 221. What will be the output of the following code?
Error [5,8]
None []
213. What will be the output of the following code? [5, 7]
674 Invalid arguments for filter function
22 Correct answer
Correct answer [5, 7]
4 222. What will be the output of the following code?
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?
61

219. What will be the output of the following code? Option 1


Page

2234336334523445455 Option 2
2234334544523423345 Option 3

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


Option 4 starting at index 0
Correct answer Return a list containing the items from L starting
Option 3 from index 0, omitting every third
228. What will be the output of the following code? item
Page 157 of 391 Correct answer
2367 Return a list containing every third item from L
229. What will be the output of the following code? starting at index 0
['2, 4, 6'] 235. What will be the output of the following code?
[2] [ 2, 4] [2, 4, 6] ['Monkey', 'Fox', 'Deer']
[2, 4, 6] ['Monkey', 'Fox', 'Lion']
[2] [4] [6] ['Monkey', 'Fox', 'Tiger']
Correct answer ['Monkey', 'Tiger', 'Lion']
[2, 4, 6] Correct answer
230. What will be the output of the following code? ['Monkey', 'Fox', 'Lion']
14 236. What will be the output of the following code?
[2,3,5,7] Option 1
5 Option 2
[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 [2, 4, 6, 5]
723 [ 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 Correct answer
3 7 44 [ 2, 4, 5]
The program prints two rows 3 6 5 2 followed by 44 239. What will be the output of the following code?
623 2546
233. What will be the output of the following Correct answer
Python 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]]
62

starting at index 0 Correct answer


Page

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?

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


Option 1 8
Option 2 Syntax error
Option 3 Correct answer
Option 4 8
Correct answer 249. Which of the following commands will create a
Option 4 list?
242. What will be the output of the following code? list1 = []
[2] [3] list1 = list()
Page 162 of 391 list1 = list([1, 2, 3])
[49] [50] all of the mentioned
[[2]] [[3]] Page 164 of 391
Syntax error 250. What will be the output of the following code?
243. What will be the output of the following code? Option 1
[‘Mango’, ‘Nail’, ‘Ox’] Option 2
['Ox', 'Nail', 'Mango'] Option 3
['Ox', 'Mango', 'Nail' ] Option 4
Invalid syntax for sort() Correct answer
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?
63

248. What will be the output of the following code? Page 166 of 391
Page

561 132
12 None

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


Correct answer 56
1 44
256. What will be the output of the following code? 7
[4, 8, 9, 7, 2, 3] Correct answer
Syntax error 44
[4,[8,9],5,2,3] 263. What will be the output of the following code?
[4,5,6,7,8] [[4, 2.5], [2, 3], [0.7, 0.7]]
Correct answer [[0.7, 0.7], [2, 3], [4, 2.5]]
[4, 8, 9, 7, 2, 3] [[0.7, 0.7], [4, 2.5], [2, 3]]
257. What will be the output of the following code? [[2, 3], [4, 2.5], [0.7, 0.7]]
66234 Correct answer
62345 [[0.7, 0.7], [2, 3], [4, 2.5]]
34562 264. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of
34566 the following is correct syntax
Correct answer for slicing operation?
34566 print(list1[0])
258. What will be the output of the following code? print(list1[:2])
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
64

5 [14]
Page

Page 168 of 391 Correct answer


262. What will be the output of the following code? [2, 3, 4, 5]

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


269. What will be the output of the following code? Correct answer
3 44 5
4 44 277. What will be the output of the following
5 44 Python code?
67 40
270. What will be the output of the following code? 45
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] “jimmy”
[[0, 2, 3], [1, 3, 4], [2, 4, 5]] “jack”
[1, 2, 3, 4, 5, 6, 7, 8, 9] Correct answer
[0, 1, 2, 1, 2, 3, 2, 3, 4] 45
Correct answer 278. What will be the output of the following
[[0, 2, 3], [1, 3, 4], [2, 4, 5]] Python code?
Page 171 of 391 (2,3,4,6)
272. Which of the following is a Python tuple? (3,4,2,6)
[1, 2, 3] None
(1, 2, 3) Error, tuple has no attribute sort
{1, 2, 3} Correct answer
{} Error, tuple has no attribute sort
Correct answer 279. What will be the output of the following
(1, 2, 3) Python 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
Error, tuple slicing doesn’t exist Python code?
[2,3] 523
(2,3,4) None
(2,3) Correct answer
275. What will be the output of the following 3
Python code? 281. What will be the output of the following
Error, tuples are immutable Python 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 282. What will be the output of the following
Python code? Python code?
(min - 5) (False, False, False)
65

5 False
Page

Error True
None of these above Page 174 of 391

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


None Python code?
Correct answer gaf
False None
283. Is the following Python code valid? Correct answer
No because tuple is immutable f
Yes, first element in the tuple is deleted 290. What will be the output of the following
Yes, the entire tuple is deleted Python code?
No, invalid syntax for del method Page 176 of 391
Correct answer False
Yes, the entire tuple is deleted True
284. What will be the output of the following Error, < operator is not valid for tuples
Python code? Error, < operator is valid for tuples but not if there
Now, a=(1,2,4) are sub-tuples
Now, a=(1,3,4) 291. What will be the output of the following
Now a=(3,4) Python code?
Error as tuple is immutable Too many arguments for sum() method
Correct answer The method sum() doesn’t exist for tuples
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 False
Python code? 293. What will be the output of the following
Page 175 of 391 Python 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
(3, 5, 4) Python code?
287. What will be the output of the following Page 177 of 391
Python 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 [(2, 3), (3, 4), (4, 9)]
Python code? 295. Suppose p = (1, 2, 4, 3), which of the following
fga Python code is incorrect?
None print(p[3])
66

Correct answer p[3] = 45


Page

g print(max(p))
289. What will be the output of the following print(len(p))

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


Correct answer (0, 2)
p[3] = 45 302. What will be the output of the following
296. What will be the output of the following Python code?
Python code? ("Yellow", "Green", "Blue")
(max - 75) 'tuple' object does not support item assignment
75 ("Red", "Green", "Blue")
Error None
None of these above Correct answer
Correct answer 'tuple' object does not support item assignment
75 303. What will be the output of the following
297. What will be the output of the following Python code?
Python code? True
125 False
Error Error
Correct answer None
Error Correct answer
298. What will be the output of the following False
Python code? 304. What will be the output of the following
Page 178 of 391 Python 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 An exception is thrown
Python 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 306. What type of data is: x=[(1,1),(2,4),(3,9)]?
Python 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 Yes, z will be ((1,2,3),(‘X’,’Y’,’Z’))
Python 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
67

(0, 1) Correct answer


Page

(0, 2) Yes, z will be ((0, 1, 2),(‘X’,’Y’,’Z’))


Correct answer 308. What will be the output of the following

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


Python code? >>> L=[‘w’,’e’,’l’,’c’,’o’,’m’,’e’]
(2, 3, 2, 3) >>> print(len(L))
[2, 3, 2, 3] a. 7
(2, 2, 3, 3) b. 8
[2, 2, 3, 3] c. 9
Correct answer d. None
(2, 3, 2, 3) Ans. a. 7
309. What will be the output of the following Q4. Write the output of the following code :
Python code? >>> L=[“Amit”,”Anita”,”Zee”,”Longest Word”]
(1, 2) >>> print(max(L))
(1, 2, 4) a. Zee
(3, 4) b. Longest Word
(2, 4, 3) c. Error
310. What will be the output of the following d. None of the above
Python code? Ans. a. Zee
(‘Check’,’Check’,’Check’) Q5. Write the output of the following code :
Operator not valid for tuples >>> L=[“Amit”,”Anita”,”Zee”,”Longest Word”,123]
(‘CheckCheckCheck’) >>> print(max(L))
Syntax error a. Longest Word
Correct answer b. Zee
(‘CheckCheckCheck’) c. Amit
311. What will be the output of the following d. Error
Python code? Ans. d. Error
(6,8) Q6. Write the output of the following code :
Invalid syntax >>>L=[1,5,9]
Page 182 of 391 >>>print(sum(L),max(L),min(L))
(8,6) Page 184 of 391
Nothing is printed a. 15 9 1
Correct answer b. Error
(8,6) c. Max and Min are only for String Value
Page 183 of 391 d. None of the above
MCQ on List in Python Ans. a. 15 9 1
Q1. Which of the following statement will create Q7. Do we have any inbuilt function for shuffling
list? the 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
68

d. None of the above Ans. a. [6, 7, 8]


Page

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”)

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


print(L[20 : -1]) d. [“Amit”,”Sumit”,”Naina”,”Amit”,”Sumit”,”Naina”]
a. [‘c’ , ‘o’] Ans. a. Error
b. [‘c’ , ‘o’ , ‘m’] Q15. Write the output of the following code :
c. (com) L=[0.5 * x for x in range(4)]
d. Error print(L)
Ans. a. [‘c’ , ‘o’] a. [0.0, 0.5, 1.0, 1.5]
Q10. Write the output of the following code : b. (0,.5, 1, 1.5)
>>>L=list(“www.csiplearninghub.com”) c. [0.0, 0.5, 1.0, 1.5, 2.0]
>>>print(L[20 : 0]) d. Error
a. Error Ans. a. [0.0, 0.5, 1.0, 1.5]
b. No Value Q16. Write the output of the following code :
c. None L=[‘a’ * x for x in range(4)]
d. [ ] print(L)
Ans. d. [ ] a. [‘ ‘ , ‘a’ , ‘aa’ , ‘aaa’]
Q11. Write the output of the following code : b. [‘a’, ‘aa’, ‘aaa’]
>>>L=[“Amit”,”Sumit”,”Naina”] c. Error
>>>print(L[-1][-1]) d. None of the above
a. [Naina] Ans. a. [‘ ‘ , ‘a’ , ‘aa’ , ‘aaa’]
b. [a] Page 186 of 391
c. a Q17. Write the output of the following code :
d. None of the above L= [1*x for x in range(10,1,-4)]
Page 185 of 391 print(L)
Ans. c. a a. [10, 6, 2]
Q12. Write the output of the following code : b. [10, 7, 4]
>>>L=[“Amit”,”Sumit”,”Naina”] c. Error
>>>print(L[1:-1]) d. None of the above
a. [‘Sumit’] Ans. a. [10, 6, 2]
b. [a] Q18. Write the output of the following code :
c. [Naina] L=[1,2,3,4,5]
d. None of the above for i in L:
Ans. a. [‘Sumit’] print(i,end=” “)
Q13. Write the output of the following code : i=i+1
L=[“Amit”,”Sumit”,”Naina”] a. 1, 2, 3, 4, 5
print(L*2) b. 1, 3, 5
a. [‘Amit’, ‘Sumit’, ‘Naina’, ‘Amit’, ‘Sumit’, ‘Naina’] c. Error
b. [“Amit” , “Sumit” , “Naina”] d. None of the above
c. Error Ans. a. 1, 2, 3, 4, 5
d. None of the above Q19. Write the output of the following code :
Ans. a. [‘Amit’, ‘Sumit’, ‘Naina’, ‘Amit’, ‘Sumit’, L=[“Amit”,”Sumit”,”Naina”]
‘Naina’] L1=[“Sunil”]
Q14. Write the output of the following code : print(L + L1)
L=[“Amit”,”Sumit”,”Naina”] a. [‘Amit’ , ‘Sumit’ , ‘Naina’ , [‘Sunil’]]
print(L**2) b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’]
a. Error c. List can not concatenate
69

b. [“Amit”,”Sumit”,”Naina”] d. None of the above


Page

[“Amit”,”Sumit”,”Naina”] Ans. b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’]


c. [“Amit”,”Sumit”,”Naina”] Q20. Which command is used to add an element in

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


List named L1 Ans. b. [1, 2, 3, 4, 3, 4, 5, 6]
a. L1.add(4) Q26. Write the output of the following:
b. L1.append(4) T = [1,2,3,4]
c. L1.new(4) T1 = [3,4,5,6]
d. None of the above T2 = T.append(T1)
Ans. b. L1.append(4) print(T2)
Q21. Write the output of the following : a. [1, 2, 3, 4, [3, 4, 5, 6]]
L = “123456” b. [1, 2, 3, 4, 3, 4, 5, 6]
L = list(L) c. None
print(type(L[0])) Page 188 of 391
a. class ‘str’ d. None of the above
b. class ‘int’ Ans. c. None
c. 1 Q27. del statement can delete the following from
d. Error the List?
Page 187 of 391 a. Single Element
Ans. a. class ‘str’ b. Multiple Elements
Q22. Write the output of the following: c. All elements along with List object
T=(1,2,3,4,5.5) d. All of the above
L = list(T) Ans. d. All of the above
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
T = [1,2,3,4] following 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
70

b. [1, 2, 3, 4, 3, 4, 5, 6] c. ValueError
Page

c. [4, 6, 8, 10] d. None of the above


d. Error Ans. c. ValueError

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


Q30. Write the output of the following. L1=["Sumit"]
T = [1,2,3,4] print(L - L1)
T1=[5,6,7] a. [“Amit” , “Naina”]
L=T.append(T1) b. [“Amit” , “Naina”, “Sumit”]
print(L) Page 190 of 391
a. None c. Show Error
b. [1, 2, 3, 4, [5, 6, 7]] d. None of the above
c. [ ] Ans. c. Show Error
Page 189 of 391 Q37. Write the output of the following:
d. Error a. Error
Ans. a. None b. 14 + 9 -1
Q31. Write the output of the following: c. 23
L=["Amit","Sumit","Naina"] d. 24
L1=["Sunil"] Ans. c. 23
print(L + L1) Q38. Which mathematical operator is used for
a. [“Amit” , “Sumit” , “Naina” , [“Sunil”] ] repetition?
b. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’] a. *
c. Error b. **
d. [‘Amit’ , ‘Sumit’ , ‘Naina’ , ‘Sunil’][‘Amit’ , ‘Sumit’ , c. +
‘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
a. True same 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
71

Ans. a. [6, 12, 18, 24] Code:


Page

Q36. Write the output of the following : T = list(tuple([1,2,3]))


L=["Amit","Sumit","Naina"] print(type(T))

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


a. Tuple print(L[len(L) - 1])
b. List Page 192 of 391
Page 191 of 391 a. 9
c. Nested List b. 1
d. None of the above c. Error
Ans. b. List d. None of the above
Q43. List and String are different Ans. d. None of the above
a. in reference to their indexing Q49. We can concatenate only two list at one time.
b. in reference to data type of elements they (T/F)
contain a. True
c. None of the above b. False
d. Both of the above Ans. b. False
Ans. b. in reference to data type of elements they Q50. The following statements is showing ______
contain operation in List.
Q44. List can have elements of _____________ data L1 = [1,2,3,4]
types. L2 = [1,2,3,4]
a. Same L = L1 + L2
b. Different a. Replication of List
c. Both of the above b. Concatenation of String
d. None of the above c. Indexing of String
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
72

Ans. b. L[-1] c. TypeError


Page

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

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


Ans. c. TypeError b. if
Q54. Name the operator which is used in the c. if–elif
following print statement. d. None of the above
a. Concatenation Ans. a. loop
b. Repetition Q61. Write the output of the following:
c. Membership print(len(tuple[1]))
d. None of the above a. 1
Ans. b. Repetition b. 0
Q55. print(L1 + L1) and print(L1 * 2) will produce c. Error
the same result.(L1 is a List)(T/F) d. None of the above
a. True Ans. c. Error
b. False Q62. Write the output of the following :
Ans. a. True L = [[1,2,3,5,6,7,[1,[2,3]]]]
Q56. Which operator helps to check whether an print(len(L))
element is present in list or not? a. 4
a. + b. 3
b. in c. 2
c. ** d. 1
d. None of the above Ans. d. 1
Ans. b. in Q63. Which function returns the length of a list?
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
73

_________ list in-place(T/F)


Page

a. loop a. True
Page 194 of 391 b. False

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


Ans. a. True d. None of the above
Q67. Which of the following function creates the Ans. a. [ ]
new list? Q72. Which of the following will give output as
a. sort( ) [21,2,9,7] ? if list L = [1,21,4,2,5,9,6,7]
b. sorted( ) a. print(L[1 : 8 : 2])
c. reverse( ) b. print(L[1 : : 2])
d. All of the above c. Both of the above
Ans. b. sorted( ) d. None of the above
Q68. Write the output of the following : Ans. print(L[1 : : 2])
D = [1,2,3] Q73. Write the output of the following :
D1 = D L = ['Amit', 'anita', 'Sumant', 'Zaid']
D.append(4) print(max(L))
print(D1) a. Zaid
a. [1, 2, 3, 4] b. Sumant
b. [1, 2, 3] c. anita
c. Error d. Amit
d. None of the above Ans. c. anita
Ans. a. [1, 2, 3, 4] Q74. Write the output of the following:
Q69. Fill in the blanks with same word in both L=[13, 12, 15, 27, 3, 46]
places list1.pop(3)
>>> import __________ print(L)
>>> 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
74

a. [ ] Ans. c. [3, 2, 5, 7, 3, 6, 3]
Page

b. 0 Q77. Write the output of the following


c. Error L = [14, 2, 3, 16, 15]

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


L[1:4] = [5, 4, 8] Q82. Write the output of the following:
print(L) L = [[5, 7, 9, 1 ], [12, 23, 4, 9]]
a. [14, 5, 4, 8, 15] for r in L:
b. [14, 5, 4, 8, 2, 3, 16, 15] r.sort()
c. Error for e in r:
d. None of the above print(e, end = ” “)
Ans. a. [14, 5, 4, 8, 15] a. 1 5 7 9 4 9 12 23
Q78. Write the output of the following b. 1 4 5 7 9 9 12 23
L = ["Amit", 'Sumit', 'Ravi'] c. 9 7 5 1 23 12 9 4
print(L[0][1]) d. None of the above
a. A Ans. a. 1 5 7 9 4 9 12 23
b. Amit Q83. How many elements will be there in list ‘L’
c. S L = [[p, q] for p in (0, 4) for q in (0, 4)]
d. m a. 2
Ans.d. m b. 4
Q79. Write the output of the following c. 8
L = ["Amit", 'Sumit', 'Ravi'] d. 16
print("@".join(L)) Ans. b. 4
a. @Amit Q84. Write the output of the following:
b. Amit@Sumit@Ravi L = [[p, q] for p in (0, 4) for q in (0, 4)]
c. Amit@Sumit@Ravi@ print(L[0])
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
75

Error Q87. Write the output of the following:


Page

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])

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


print(len(L)) d. None of the above
a. 8 Ans. b. [1, 1, 1, 1, 1]
b. 5 Q92. Write the output of the following :
c. 4 L= [1,2,3,4,5]
d. None of the above m = [m + 3 for m in L]
Ans. b. 5 print(m)
Q88. Write the output of the following : a. [4, 5, 6, 7, 8, 9]
L = [11, 21, 31, 41] b. [4, 5, 6, 7, 8, 9, 10]
L.extend([51,62,73,84]) c. [4, 5, 6, 7, 8]
print(len(L)) d. Error
a. 8 Ans. c. [4, 5, 6, 7, 8]
b. 4 Q93. Write the output of the following :
c. 5 L1 = [1, 2, 3, 4, 5]
d. Error L2 = [9, 8, 7, 6, 5]
Ans. a. 8 S= [L1 + 3 for L1 in L2]
Q89. Write the output of the following print(S)
L1 = ['C++', 'C-Sharp', 'Visual Basic'] a. [12, 11, 10, 9, 8]
L2 = [name.upper() for name in L1] b. [1, 2, 3, 4, 5, 6, 7, 8, 9]
L3 = [name for name in L1] c. [4, 5, 6, 7, 8]
if(L2[2][0] == L3[2][0]): Page 201 of 391
print("YES") d. Error
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
print(m) generate the square of given list L ?
76

a. [1, 2, 3, 4, 5] L = [1, 2, 3, 4, 5]
Page

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]

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


c. [x ^ 3 for x in L a) a
d. None of the above b) ab
Ans. a. [x ** 2 for x in L c) cd
Q97. Which of the following function is used to d) dc
shuffle the list ? Answer: c
a. random( ) Explanation: Slice operation is performed on
b. swap( ) string.
c. shuffle( ) 3. The output of executing string.ascii_letters can
d. None of the above also be achieved by:
Ans. a. random( ) a) string.ascii_lowercase_string.digits
Q98. Both the print statement will produce the b) string.ascii_lowercase+string.ascii_upercase
same result.(T/F) c) string.letters
L = ["Amit", "Ananya", "Parth"] d) string.lowercase_string.upercase
print(L[-1]) Answer: b
print(L[-1][-1]) Explanation: Execute in shell and check.
a. True 4. What will be the output of the following Python
b. False code?
Page 202 of 391 1. >>> str1 = 'hello'
Ans. b. False 2. >>> str2 = ','
Q99. Write the output of the following: 3. >>> str3 = 'world'
L1 = [1, 2, 3] 4. >>> str1[-1:]
L2 = [1, 2, 3, 4, 5, 6] a) olleh
print(L1 in L2) b) hello
a. True c) h
b. False d) o
Ans. b. False Answer: d
Q100. Which of the following command will insert 7 Explanation: -1 corresponds to the last index.
in third position of List L. 5. What arithmetic operators cannot be used with
a. L.insert(3, 7) strings?
b. L.insert(2, 7) a) +
c. L.add(3, 7) b) *
d. L.append(3, 7) Page 204 of 391
Ans. b. L.insert(2, 7) c) –
Page 203 of 391 d) All of the mentioned
Questions and Answers –Strings – 1 Answer: c
1. What will be the output of the following Python Explanation: + is used to concatenate and * is used
statement? to multiply strings.
1. >>>"a"+"bc" 6. What will be the output of the following Python
a) a code?
b) bc 1. >>>print (r"\nhello")
c) bca a) a new line and hello
d) abc b) \nhello
Answer: d c) the letter r and then hello
Explanation: + operator is concatenation operator. d) error
77

2. What will be the output of the following Python Answer: b


Page

statement? Explanation: When prefixed with the letter ‘r’ or


1. >>>"abcd"[2:] ‘R’ a string literal becomes a raw

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


string and the escape sequences such as \n are not Page 206 of 391
converted. Python Questions and Answers – Strings – 2
7. What will be the output of the following Python 1. What will be the output of the following Python
statement? code?
1. >>>print('new' 'line') 1. class father:
a) Error 2. def __init__(self, param):
b) Output equivalent to print ‘new\nline’ 3. self.o1 = param
c) newline 4.
d) new line 5. class child(father):
Answer: c 6. def __init__(self, param):
Explanation: String literal separated by whitespace 7. self.o2 = param
are allowed. They are 8.
concatenated. 9. >>>obj = child(22)
8. What will be the output of the following Python 10.>>>print "%d %d" % (obj.o1, obj.o2)
statement? a) None None
1. >>> print('x\97\x98') b) None 22
a) Error c) 22 None
b) d) Error is generated
97 Answer: d
98 Explanation: self.o1 was never created.
c) x\97 2. What will be the output of the following Python
d) \x97\x98 code?
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
78

integer literals representing the Answer: a


Page

decimal values 10, 11 and 12 respectively. There Explanation: Execute in the shell and verify.
sum is 33. Page 207 of 391

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


4. What will be the output of the following Python d) 1
code? Answer: b
1. >>>example = "snow world" Explanation: Returns highest index.
2. >>>example[3] = 's' 9. What will be the output of the following Python
3. >>>print example code?
a) snow 1. >>>example="helloworld"
b) snow world 2. >>>example[::-1].startswith("d")
c) Error a) dlrowolleh
d) snos world b) True
Answer: c c) -1
Explanation: Strings cannot be modified. d) None
5. What will be the output of the following Python Answer: b
code? Explanation: Starts with checks if the given string
1. >>>max("what are you") starts with the parameter that is
a) error passed.
b) u 10. To concatenate two strings to a third what
c) t statements are applicable?
d) y a) s3 = s1 . s2
Answer: d b) s3 = s1.add(s2)
Explanation: Max returns the character with the c) s3 = s1.__add__(s2)
highest ascii value. d) s3 = s1 * s2
6. Given a string example=”hello” what is the Answer: c
output 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.
79

a) -1 3. Which of the following statement prints hello\


Page

b) 4 example\test.txt?
c) 3 a) print(“hello\example\test.txt”)

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


b) print(“hello\\example\\test.txt”) 3. >>>print(format(924.656, "3.2f"))
c) print(“hello\”example\”test.txt”) a) Welcome# 111#924.66
d) print(“hello”\example”\test.txt”) b) Welcome#111#924.66
Answer: b c) Welcome#111#.66
Explanation: \is used to indicate that the next \ is d) Welcome # 111#924.66
not an escape sequence. Answer: d
4. Suppose s is “\t\tWorld\n”, what is s.strip()? Explanation: Execute in the shell to verify.
a) \t\tWorld\n 9. What will be displayed by print(ord(‘b’) –
b) \t\tWorld\n ord(‘a’))?
c) \t\tWORLD\n a) 0
d) World b) 1
Answer: d c) -1
Explanation: Execute help(string.strip) to find d) 2
details. Answer: b
5. The format function, when applied on a string Explanation: ASCII value of b is one more than a.
returns ___________ Hence the output of this code is 98-
a) Error 97, which is equal to 1.
b) int Page 211 of 391
c) bool 10. Say s=”hello” what will be the return value of
d) str type(s)?
Page 210 of 391 a) int
Answer: d b) bool
Explanation: Format function returns a string. c) str
6. What will be the output of the “hello” +1+2+3? d) String
a) hello123 Answer: c
b) hello Explanation: str is used to represent strings in
c) Error python.
d) hello6 Page 212 of 391
Answer: c Python Questions and Answers – Strings – 4
Explanation: Cannot concatenate str and int 1. What is “Hello”.replace(“l”, “e”)?
objects. a) Heeeo
7. What will be the output of the following Python b) Heelo
code? c) Heleo
1. >>>print("D", end = ' ') d) None
2. >>>print("C", end = ' ') Answer: a
3. >>>print("B", end = ' ') Explanation: Execute in shell to verify.
4. >>>print("A", end = ' ') 2. To retrieve the character at index 3 from string
a) DCBA s=”Hello” what command do we execute
b) A, B, C, D (multiple answers allowed)?
c) D C B A a) s[]
d) D, C, B, A will be displayed on four lines b) s.getitem(3)
Answer: c c) s.__getitem__(3)
Explanation: Execute in the shell. d) s.getItem(3)
8. What will be the output of the following Python Answer: c
80

statement?(python 3.xx) Explanation: __getitem(..) can be used to get


Page

1. >>>print(format("Welcome", "10s"), end = '#') character at index specified as parameter.


2. >>>print(format(111, "4d"), end = '#') 3. To return the length of string s what command

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


do we execute? a) True False
a) s.__len__() b) True True
b) len(s) c) False True
c) size(s) d) False False
d) s.size() Answer: c
Answer: a Explanation: Execute in the shell objects cannot
Explanation: Execute in shell to verify. have same id, however in the case of
4. If a class defines the __str__(self) method, for an strings its different.
object obj for the class, you can use 8. What will be the output of the following Python
which command to invoke the __str__ method. code?
a) obj.__str__() 1. class Name:
b) str(obj) 2. def __init__(self, firstName, mi, lastName):
c) print obj 3. self.firstName = firstName
d) all of the mentioned 4. self.mi = mi
Answer: d 5. self.lastName = lastName
Explanation: Execute in shell to verify. 6.
5. To check whether string s1 contains another 7. firstName = "John"
string s2, use ________ 8. name = Name(firstName, 'F', "Smith")
a) s1.__contains__(s2) 9. firstName = "Peter"
b) s2 in s1 10.name.lastName = "Pan"
c) s1.contains(s2) 11.print(name.firstName, name.lastName)
d) si.in(s2) Page 214 of 391
Page 213 of 391 a) Peter Pan
Answer: a b) John Pan
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,
1. class Count: “10.3f”) (_ 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
81

9. s1 = "Good" Python Questions and Answers – Strings – 5


Page

10.s2 = "Good" 1. What will be the output of the following Python


11.print(id(s1) == id(s2)) code?

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


print("abc DEF".capitalize()) c) *abcdef *
a) abc def d) * abcdef*
b) ABC DEF Answer: b
c) Abc def Explanation: Padding is done towards the left-
d) Abc Def hand-side first when the final string is of
Answer: c odd length. Extra spaces are present since we
Explanation: The first letter of the string is haven’t overridden the value of sep.
converted to uppercase and the others are 6. What will be the output of the following Python
converted to lowercase. code?
2. What will be the output of the following Python print('*', "abcdef".center(7), '*', sep='')
code? a) * abcdef *
print("abc. DEF".capitalize()) b) * abcdef *
a) abc. def c) *abcdef *
b) ABC. DEF d) * abcdef*
c) Abc. def Answer: d
d) Abc. Def Explanation: Padding is done towards the left-
Answer: c hand-side first when the final string is of
Explanation: The first letter of the string is odd length.
converted to uppercase and the others are 7. What will be the output of the following Python
converted to lowercase. code?
3. What will be the output of the following Python print('*', "abcde".center(6), '*', sep='')
code? a) * abcde *
print("abcdef".center()) b) * abcde *
a) cd c) *abcde *
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 of even length.
one 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
82

Page 216 of 391 c) abcdef


Page

a) * abcdef * Page 217 of 391


b) * abcdef * d) error

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


Answer: a string, starting from position 2.
Explanation: The character ‘1’ is used for padding 4. What will be the output of the following Python
instead of a space. code?
10. What will be the output of the following Python print("xyyzxyzxzxyy".count('xyy', 0, 100))
code? a) 2
print("abcdef".center(10, '12')) b) 0
a) 12abcdef12 c) 1
b) abcdef1212 d) error
c) 1212abcdef Answer: a
d) error Explanation: An error will not occur if the end
Answer: d value is greater than the length of the
Explanation: The fill character must be exactly one string itself.
character long. 5. What will be the output of the following Python
Page 218 of 391 code?
Python Questions and Answers – Strings – 6 Page 219 of 391
1. What will be the output of the following Python print("xyyzxyzxzxyy".count('xyy', 2, 11))
code? a) 2
print("xyyzxyzxzxyy".count('yy')) b) 0
a) 2 c) 1
b) 0 d) error
c) error Answer: b
d) none of the mentioned Explanation: Counts the number of times the
Answer: a substring ‘xyy’ is present in the given
Explanation: Counts the number of times the string, starting from position 2 and ending at
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’
83

Answer: c Answer: c
Page

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

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


encode()? Explanation: Execute in the shell to verify.
a) ascii 3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is
b) qwerty len(listExample)?
c) utf-8 a) 5
d) utf-16 b) 4
Answer: c c) None
Explanation: The default value of encoding is utf-8. d) Error
9. What will be the output of the following Python Answer: a
code? Explanation: Execute in the shell and verify.
print("xyyzxyzxzxyy".endswith("xyy")) 4. Suppose list1 is [2445,133,12454,123], what is
a) 1 max(list1)?
b) True a) 2445
c) 3 b) 133
d) 2 c) 12454
Page 220 of 391 d) 123
Answer: b Answer: c
Explanation: The function returns True if the given Explanation: Max returns the maximum element
string ends with the specified in the list.
substring. 5. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1)?
10. What will be the output of the following Python a) 3
code? b) 5
print("xyyzxyzxzxyy".endswith("xyy", 0, 2)) c) 25
a) 0 d) 1
b) 1 Answer: d
c) True Explanation: Min returns the minimum element in
d) False the list.
Answer: d Page 222 of 391
Explanation: The function returns False if the given 6. Suppose list1 is [1, 5, 9], what is sum(list1)?
string does not end with the a) 1
specified substring b) 9
Page 221 of 391 c) 15
Python Questions and Answers – Lists – 1 d) Error
1. Which of the following commands will create a Answer: c
list? Explanation: Sum returns the sum of all elements
a) list1 = list() in the list.
b) list1 = [] 7. To shuffle the list(say list1) what function do we
c) list1 = list([1, 2, 3]) use?
d) all of the mentioned a) list1.shuffle()
Answer: d b) shuffle(list1)
Explanation: Execute in the shell to verify c) random.shuffle(list1)
2. What is the output when we execute d) random.shuffleList(list1)
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
84

c) [‘llo’] following is correct syntax for slicing


Page

d) [‘olleh’] operation?
Answer: a a) print(list1[0])

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


b) print(list1[:2]) 10. if ls[0] == 'Alice':
c) print(list1[:-2]) 11. sum += 1
d) all of the mentioned 12. if ls[1] == 'Bob':
Answer: d 13. sum += 10
Explanation: Slicing is allowed in lists just as in the 14.
case of strings. 15.print sum
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[- a) 11
1]? b) 12
a) Error c) 21
b) None d) 22
c) 25 Answer: b
d) 2 Explanation: When assigning names1 to names2,
Answer: c we create a second reference to the
Explanation: -1 corresponds to the last index in the same list. Changes to names2 affect names1.
list. When assigning the slice of all elements in
10. Suppose list1 is [2, 33, 222, 14, 25], What is names1 to names3, we are creating a full copy of
list1[:-1]? names1 which can be modified
a) [2, 33, 222, 14] independently.
b) Error 3. Suppose list1 is [1, 3, 2], What is list1 * 2?
c) 25 a) [2, 6, 4]
d) [25, 14, 222, 33, 2] b) [1, 3, 2, 1, 3]
Answer: a c) [1, 3, 2, 1, 3, 2]
Explanation: Execute in the shell to verify. d) [1, 3, 2, 3, 2, 1]
Page 223 of 391 Page 225 of 391
Page 224 of 391 Answer: c
Python Questions and Answers – Lists – 2 Explanation: Execute in the shell and verify.
1. What will be the output of the following Python 4. Suppose list1 = [0.5 * x for x in range(0, 4)], list1
code? is:
1. >>>names = ['Amir', 'Bear', 'Charlton', 'Daman'] a) [0, 1, 2, 3]
2. >>>print(names[-1][-1]) b) [0, 1, 2, 3, 4]
a) A c) [0.0, 0.5, 1.0, 1.5]
b) Daman d) [0.0, 0.5, 1.0, 1.5, 2.0]
c) Error Answer: c
d) n Explanation: Execute in the shell to verify.
Answer: d 5. What will be the output of the following Python
Explanation: Execute in the shell to verify. code?
2. What will be the output of the following Python 1. >>>list1 = [11, 2, 23]
code? 2. >>>list2 = [11, 2, 2]
1. names1 = ['Amir', 'Bear', 'Charlton', 'Daman'] 3. >>>list1 < list2 is
2. names2 = names1 a) True
3. names3 = names1[:] b) False
4. c) Error
5. names2[0] = 'Alice' d) None
6. names3[1] = 'Bob' Answer: b
85

7. Explanation: Elements are compared one by one.


Page

8. sum = 0 6. To add a new element to a list we use which


9. for ls in (names1, names2, names3): command?

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


a) list1.add(5) d) [3, 1, 25, 5, 20, 5, 4, 3]
b) list1.append(5) Answer: d
c) list1.addLast(5) Explanation: Execute in the shell to verify.
d) list1.addEnd(5) 2. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3],
Answer: b what is list1 after listExample.extend([34,
Explanation: We use the function append to add 5])?
an element to the list. a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
7. To insert 5 to the third position in list1, we use b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
which command? c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
a) list1.insert(3, 5) d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
b) list1.insert(2, 5) Answer: a
c) list1.add(3, 5) Explanation: Execute in the shell to verify.
d) list1.append(3, 5) 3. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3],
Answer: b what is list1 after listExample.pop(1)?
Explanation: Execute in the shell to verify. a) [3, 4, 5, 20, 5, 25, 1, 3]
8. To remove string “hello” from list1, we use which b) [1, 3, 3, 4, 5, 5, 20, 25]
command? c) [3, 5, 20, 5, 25, 1, 3]
a) list1.remove(“hello”) d) [1, 3, 4, 5, 20, 5, 25]
b) list1.remove(hello) Answer: c
c) list1.removeAll(“hello”) Explanation: pop() removes the element at the
Page 226 of 391 position specified in the parameter.
d) list1.removeOne(“hello”) 4. Suppose listExample is [3, 4, 5, 20, 5, 25, 1, 3],
Answer: a what is list1 after listExample.pop()?
Explanation: Execute in the shell to verify. a) [3, 4, 5, 20, 5, 25, 1]
9. Suppose list1 is [3, 4, 5, 20, 5], what is b) [1, 3, 3, 4, 5, 5, 20, 25]
list1.index(5)? c) [3, 5, 20, 5, 25, 1, 3]
a) 0 d) [1, 3, 4, 5, 20, 5, 25]
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
Page 227 of 391 in 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 code?
list1 after list1.reverse()? 1. >>>list("a#b#c#d".split('#'))
86

a) [3, 4, 5, 20, 5, 25, 1, 3] a) [‘a’, ‘b’, ‘c’, ‘d’]


Page

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’]

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


d) [‘abcd’] Explanation: Lists should be copied by executing [:]
Answer: a operation.
Explanation: Execute in the shell to verify. 10. What will be the output of the following Python
7. What will be the output of the following Python code?
code? 1. def f(values):
1. myList = [1, 5, 5, 5, 5, 1] 2. values[0] = 44
2. max = myList[0] 3.
3. indexOfMax = 0 4. v = [1, 2, 3]
4. for i in range(1, len(myList)): 5. f(v)
5. if myList[i] > max: 6. print(v)
6. max = myList[i] a) [1, 44]
7. indexOfMax = i b) [1, 2, 3, 44]
8. c) [44, 2, 3]
9. >>>print(indexOfMax) d) [1, 2, 3]
a) 1 Answer: c
b) 2 Explanation: Execute in the shell to verify.
c) 3 Page 230 of 391
d) 4 Python Questions and Answers – Lists – 4
Answer: a 1. What will be the output of the following Python
Explanation: First time the highest number is code?
encountered is at index 1. 1. def f(i, values = []):
8. What will be the output of the following Python 2. values.append(i)
code? 3. return values
1. myList = [1, 2, 3, 4, 5, 6] 4.
2. for i in range(1, 6): 5. f(1)
3. myList[i - 1] = myList[i] 6. f(2)
4. 7. v = f(3)
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
87

c) [1, 4] c) 2
Page

d) [1, 3, 4] d) Error
Answer: b Answer: c

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


Explanation: Execute in the shell to verify. Answer: d
3. What will be the output of the following Python Explanation: + appends all the elements
code? individually into a new list.
1. names1 = ['Amir', 'Bala', 'Charlie'] 7. What will be the output of the following Python
2. names2 = [name.lower() for name in names1] code?
3. 1. def addItem(listParam):
4. print(names2[2][0]) 2. listParam += [1]
a) None 3.
b) a 4. mylist = [1, 2, 3, 4]
c) b 5. addItem(mylist)
d) c 6. print(len(mylist))
Answer: d a) 1
Explanation: List Comprehension are a shorthand b) 4
for creating new lists. c) 5
Page 231 of 391 Page 232 of 391
4. What will be the output of the following Python d) 8
code? Answer: c
1. numbers = [1, 2, 3, 4] Explanation: + will append the element to the list.
2. 8. What will be the output of the following Python
3. numbers.append([5,6,7,8]) code?
4. 1. def increment_items(L, increment):
5. print(len(numbers)) 2. i = 0
a) 4 3. while i < len(L):
b) 5 4. L[i] = L[i] + increment
c) 8 5. i = i + 1
d) 12 6.
Answer: b 7. values = [1, 2, 3]
Explanation: A list is passed in append so the 8. print(increment_items(values, 2))
length is 5. 9. print(values)
5. To which of the following the “in” operator can a)
be 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
88

b) 4 code?
Page

c) 5 1. def example(L):
d) 8 2. ''' (list) -> list

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


3. ''' d) 32
4. i = 0 Answer: c
5. result = [] Explanation: Execute in the shell to verify.
6. while i < len(L): 3. What will be the output of the following Python
7. result.append(L[i]) code?
8. i = i + 3 1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
9. return result 2.
a) Return a list containing every third item from L 3. v = values[0][0]
starting at index 0 4. for row in range(0, len(values)):
b) Return an empty list 5. for column in range(0, len(values[row])):
c) Return a list containing every third index from L 6. if v < values[row][column]:
starting at index 0 7. v = values[row][column]
d) Return a list containing the items from L starting 8.
from index 0, omitting every third item 9. print(v)
Page 233 of 391 a) 3
Answer: a b) 5
Explanation: Run the code to get a better c) 6
understanding with many arguments. d) 33
10. What will be the output of the following Python Answer: d
code? Explanation: Execute in the shell to verify.
1. veggies = ['carrot', 'broccoli', 'potato', 4. What will be the output of the following Python
'asparagus'] code?
2. veggies.insert(veggies.index('broccoli'), 'celery') 1. values = [[3, 4, 5, 1], [33, 6, 1, 2]]
3. print(veggies) 2.
a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, ‘asparagus’] 3. v = values[0][0]
Correct 1.00 4. for lst in values:
b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’] 5. for element in lst:
c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’, ‘asparagus’] 6. if v > element:
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()
89

a) 8 5. for element in row:


Page

b) 12 6. print(element, end = " ")


c) 16 7. print()

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


a) The program prints two rows 3 4 5 1 followed by 3. print(data[1][0][0])
33 6 1 2 a) 1
b) The program prints on row 3 4 5 1 33 6 1 2 b) 2
c) The program prints two rows 3 4 5 1 followed by c) 4
33 6 1 2 d) 5
d) The program prints two rows 1 3 4 5 followed by Answer: d
1 2 6 33 Explanation: Execute in the shell to verify.
Answer: d 9. What will be the output of the following Python
Explanation: Execute in the shell to verify. code?
6. What will be the output of the following Python 1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
code? 2.
1. matrix = [[1, 2, 3, 4], 3. def ttt(m):
2. [4, 5, 6, 7], 4. v = m[0][0]
3. [8, 9, 10, 11], 5.
4. [12, 13, 14, 15]] 6. for row in m:
5. 7. for element in row:
6. for i in range(0, 4): 8. if v < element: v = element
7. print(matrix[i][1], end = " ") 9.
a) 1 2 3 4 10. return v
b) 4 5 6 7 11.
c) 1 3 8 12 12.print(ttt(data[0]))
d) 2 5 9 13 a) 1
Answer: d b) 2
Explanation: Execute in the shell to verify. c) 4
7. What will be the output of the following Python d) 5
code? Answer: c
1. def m(list): Explanation: Execute in the shell to verify.
2. v = list[0] 10. What will be the output of the following Python
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)
90

code? a[3][0]=95
Page

1. data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] a[1]=34
2. print(b)

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


a) [10,34,56,[95]] print(a)
b) [10,23,56,[78]] b=list(s.split("@",3))
c) [10,23,56,[95]] print(b)
d) [10,34,56,[78]] a)
Answer: c [‘a’,’b’,’c’,’d’]
Explanation: The above copy is a type of shallow [‘a’,’b’,’c’,’d’]
copy and only changes made in sublist b)
is reflected in the copied list. [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
2. What will be the output of the following Python [‘a’,’b’,’c’,’d’]
code? c)
print(list(zip((1,2,3),('a'),('xxx','yyy')))) [‘a’,’@’,’b@c@d’]
print(list(zip((2,4),('b','c'),('yy','xx')))) [‘a’,’b’,’c’,’d’]
a) d)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)] [‘a’,’@’,’b@c@d’]
[(2,4),(‘b’,’c’),(‘yy’,’xx’)] [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
b) Answer: c
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’ ‘)] Explanation: The partition function only splits for
[(2, 'b', 'yy'), (4, 'c', 'xx')] the first parameter along with the
c) Syntax error separator while split function splits for the number
d) of times given in the second
[(1, 'a', 'xxx')] argument but without the separator.
[(2, 'b', 'yy'), (4, 'c', 'xx')] 5. What will be the output of the following Python
Answer: d code?
Explanation: The zip function combines the a=[1,2,3,4]
individual attributes of the lists into a list b=[sum(a[0:x+1]) for x in range(0,len(a))]
of tuples. print(b)
3. What will be the output of the following Python a) 10
code? b) [1,3,5,7]
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
a[1]=34 cumulative 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
91

code? Explanation: Variable x iterates over each letter in


Page

s="a@b@c@d" string a hence the length of each


a=list(s.partition("@")) letter is 1.

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


7. What will be the output of the following Python c) [3,[7,8],6,1,2]
code? d) [3,4,6,7,8]
a=[1,2,3,4] Answer: a
b=[sum(a[0:x+1]) for x in range(0,len(a))] Explanation: In the piece of code, slice assignment
print(b) has been implemented. The sliced
a) 10 list is replaced by the assigned elements in the list.
b) [1,3,5,7] Type in python shell to verify.
c) 4 Page 242 of 391
d) [1,3,6,10] Python Questions and Answers – Lists – 7
Answer: d 1. What will be the output of the following Python
Explanation: The above code returns the code?
cumulative sum of elements in a list. a=[1,2,3]
8. What will be the output of the following Python b=a.append(4)
code? print(a)
a=[[]]*3 print(b)
a[1].append(7) a)
print(a) [1,2,3,4]
a) Syntax error [1,2,3,4]
b) [[7], [7], [7]] b)
c) [[7], [], []] [1, 2, 3, 4]
d) [[],7, [], []] None
Answer: b c) Syntax error
Explanation: The first line of the code creates d)
multiple reference copies of sublist. [1,2,3]
Hence when 7 is appended, it gets appended to all [1,2,3,4]
the sublists. Answer: b
9. What will be the output of the following Python Explanation: Append function on lists doesn’t
code? return anything. Thus the value of b is
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 Answer: b
the 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])
92

print(lst) a.extend([45,67])
Page

a) [3, 7, 8, 6, 1, 2] print(a)
b) Syntax error a) [13, 56, 17, [87], 45, 67]

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


b) [13, 56, 17, 87, 45, 67] print(list1 is list2)
c) [13, 56, 17, 87,[ 45, 67]] a)
d) [13, 56, 17, [87], [45, 67]] True
Answer: a True
Explanation: The append function simply adds its b)
arguments to the list as it is while False
extend function extends its arguments and later True
appends it. c)
Page 243 of 391 False
4. What is the output of the following piece of False
code? d)
a=list((45,)*4) Page 244 of 391
print((45)*4) True
print(a) False
a) Answer: d
180 Explanation: In the above case, both the lists are
[(45),(45),(45),(45)] equivalent but not identical as they
b) have different objects.
(45,45,45,45) 7. What will be the output of the following Python
[45,45,45,45] code?
c) def unpack(a,b,c,d):
180 print(a+d)
[45,45,45,45] x = [1,2,3,4]
d) Syntax error unpack(*x)
Answer: c a) Error
Explanation: (45) is an int while (45,) is a tuple of b) [1,4]
one element. Thus when a tuple is c) [5]
multiplied, it created references of itself which is d) 5
later converted to a list. Answer: d
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’]
93

list1=[1,2,3] Answer: b
Page

list2=[1,2,3] Explanation: places1 is an alias of the list places.


print(word1 is word2) Hence, any change made to places1 is

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


reflected in places. places2 is a copy of the list second for-loop.
places. Thus, any change made to places2 12. What will be the output of the following Python
isn’t reflected in places. code?
9. What will be the output of the following Python def change(var, lst):
code? var = 1
x=[[1],[2]] lst[0] = 44
print(" ".join(list(map(str,x)))) k=3
a) [1] [2] a = [1, 2, 3]
b) [49] [50] change(k, a)
c) Syntax error print(k)
d) [[1]] [[2]] print(a)
Page 245 of 391 a)
Answer: a 3
Explanation: The elements 1 and 2 are first put [44, 2, 3]
into separate lists and then combined b)
with a space in between using the join attribute. Page 246 of 391
10. What will be the output of the following Python 1
code? [1,2,3]
a=165 c)
b=sum(list(map(int,str(a)))) 3
print(b) [1,2,3]
a) 561 d)
b) 5 1
c) 12 [44,2,3]
d) Syntax error Answer: a
Answer: c Explanation: A list is mutable, hence it’s value
Explanation: First, map converts the number to changes after function call. However,
string and then places the individual integer isn’t mutable. Thus its value doesn’t
digits in a list. Then, sum finds the sum of the change.
digits in the list. The code basically finds 13. What will be the output of the following Python
the sum of digits in the number. code?
11. What will be the output of the following Python a = [1, 5, 7, 9, 9, 1]
code? <br class="blank" />b=a[0]
a= [1, 2, 3, 4, 5] <br class="blank" />x= 0
for i in range(1, 5): for x in range(1, len(a)):
a[i-1] = a[i] if a[x] > b:
for i in range(0, 5): b = a[x]
print(a[i],end = " ") b= x
a) 5 5 1 2 3 print(b)
b) 5 1 2 3 4 a) 5
c) 2 3 4 5 1 b) 3
d) 2 3 4 5 5 c) 4
Answer: d d) 0
Explanation: The items having indexes from 1 to 4 Answer: c
94

are shifted forward by one index Explanation: The above piece of code basically
Page

due to the first for-loop and the item of index four prints the index of the largest element in
is printed again because of the the list.

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


14. What will be the output of the following Python 3. What will be the output of the following Python
code? code?
a=["Apple","Ball","Cobra"] 1. >>>t=(1,2,4,3)
<br class="blank" />a.sort(key=len) 2. >>>t[1:3]
print(a) a) (1, 2)
a) [‘Apple’, ‘Ball’, ‘Cobra’] b) (1, 2, 4)
b) [‘Ball’, ‘Apple’, ‘Cobra’] c) (2, 4)
c) [‘Cobra’, ‘Apple’, ‘Ball’] d) (2, 4, 3)
d) Invalid syntax for sort() Answer: c
Answer: b Explanation: Slicing in tuples takes place just as it
Explanation: The syntax isn’t invalid and the list is does in strings.
sorted according to the length of the 4. What will be the output of the following Python
strings in the list since key is given as len. code?
15. What will be the output of the following Python 1. >>>t=(1,2,4,3)
code? 2. >>>t[1:-1]
num = ['One', 'Two', 'Three'] a) (1, 2)
for i, x in enumerate(num): b) (1, 2, 4)
Page 247 of 391 c) (2, 4)
print('{}: {}'.format(i, x),end=" ") d) (2, 4, 3)
a) 1: 2: 3: Answer: c
b) Exception is thrown Explanation: Slicing in tuples takes place just as it
c) One Two Three does in strings.
d) 0: One 1: Two 2: Three 5. What will be the output of the following Python
Answer: d code?
Explanation: enumerate(iterator,start=0) is a built- 1. >>>t = (1, 2, 4, 3, 8, 9)
in function which returns 2. >>>[t[i] for i in range(0, len(t), 2)]
(0,lst[0]),(1,lst[1]) and so on where lst is a a) [2, 3, 9]
list(iterator). b) [1, 2, 4, 3, 8, 9]
Page 248 of 391 Page 249 of 391
Python Questions and Answers – Tuples – 1 c) [1, 4, 8]
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
95

Answer: b code?
Page

Explanation: Values cannot be modified in the case 1. >>>t = (1, 2)


of tuple, that is, tuple is immutable. 2. >>>2 * t

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


a) (1, 2, 1, 2) Explanation: Tuples can be used for keys into
b) [1, 2, 1, 2] dictionary. The tuples can have mixed
c) (1, 1, 2, 2) length and the order of the items in the tuple is
d) [1, 1, 2, 2] considered when comparing the
Answer: a equality of the keys.
Explanation: * operator concatenates tuple. Page 251 of 391
8. What will be the output of the following Python Python Questions and Answers – Tuples – 2
code? 1. What is the data type of (1)?
1. >>>t1 = (1, 2, 4, 3) a) Tuple
2. >>>t2 = (1, 2, 3, 4) b) Integer
3. >>>t1 < t2 c) List
a) True d) Both tuple and integer
b) False Answer: b
c) Error Explanation: A tuple of one element must be
d) None created as (1,).
Answer: b 2. If a=(1,2,3,4), a[1:-1] is _________
Explanation: Elements are compared one by one in a) Error, tuple slicing doesn’t exist
this case. b) [2,3]
9. What will be the output of the following Python c) (2,3,4)
code? d) (2,3)
1. >>>my_tuple = (1, 2, 3, 4) Answer: d
2. >>>my_tuple.append( (5, 6, 7) ) Explanation: Tuple slicing exists and a[1:-1] returns
3. >>>print len(my_tuple) (2,3).
a) 1 3. What will be the output of the following Python
b) 2 code?
c) 5 >>> a=(1,2,(4,5))
Page 250 of 391 >>> b=(1,2,(3,4))
d) Error >>> a<b
Answer: d a) False
Explanation: Tuples are immutable and don’t have b) True
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
10. What will be the output of the following Python there are sub-tuples
code? Answer: a
2. numberGames = {} Explanation: Since the first element in the sub-
3. numberGames[(1,2,4)] = 8 tuple 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’)
96

c) 33 d) Syntax error
Page

d) 12 Answer: c
Answer: c Explanation: Here (“Check”) is a string not a tuple

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


because there is no comma after the >>> b=slice(0,2)
element. >>> a[b]
5. What will be the output of the following Python a) Invalid syntax for slicing
code? b) [0,2]
>>> a=(1,2,3,4) Page 253 of 391
Page 252 of 391 c) (0,1)
>>> del(a[2]) d) (0,2)
a) Now, a=(1,2,4) Answer: c
b) Now, a=(1,3,4) Explanation: The method illustrated in the above
c) Now a=(3,4) piece of code is that of naming of
d) Error as tuple is immutable slices.
Answer: d 10. Is the following Python code valid?
Explanation: ‘tuple’ object doesn’t support item >>> a=(1,2,3)
deletion. >>> b=('A','B','C')
6. What will be the output of the following Python >>> c=tuple(zip(a,b))
code? a) Yes, c will be ((1, ‘A’), (2, ‘B’), (3, ‘C’))
>>> a=(2,3,4) b) Yes, c will be ((1,2,3),(‘A’,’B’,’C’))
>>> sum(a,3) c) No because tuples are immutable
a) Too many arguments for sum() method d) No because the syntax for zip function isn’t valid
b) The method sum() doesn’t exist for tuples Answer: a
c) 12 Explanation: Zip function combines individual
d) 9 elements of two iterables into tuples.
Answer: c Execute in Python shell to verify.
Explanation: In the above case, 3 is the starting Page 254 of 391
value to which the sum of the tuple is Python Questions and Answers – Tuples-3
added to. 1. Is the following Python code valid?
7. Is the following Python code valid? >>> a,b,c=1,2,3
>>> a=(1,2,3,4) >>> a,b,c
>>> del a a) Yes, [1,2,3] is printed
a) No because tuple is immutable b) No, invalid syntax
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) Error, tuples are immutable
a list making it a list of tuples. b)
97

9. What will be the output of the following Python (('check',),)


Page

code? ((('check',),),)
>>> a=(0,1,2,3,4) c) ((‘check’,)’check’,)

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


d) Explanation: The above piece of code illustrates
(('check',)’check’,) the unpacking of variables.
((('check',)’check’,)’check’,) 6. What will be the output of the following Python
Answer: b code?
Explanation: The loop runs two times and each >>> import collections
time the loop runs an extra parenthesis >>> a=collections.namedtuple('a',['i','j'])
along with a comma is added to the tuple (as >>> obj=a(i=4,j=7)
a=(a’)). >>> obj
3. Is the following Python code valid? a) a(i=4, j=7)
>>> a,b=1,2,3 b) obj(i=4, j=7)
a) Yes, this is an example of tuple unpacking. a=1 c) (4,7)
and b=2 d) An exception is thrown
b) Yes, this is an example of tuple unpacking. Answer: a
a=(1,2) and b=3 Explanation: The above piece of code illustrates
c) No, too many values to unpack the concept of named tuples.
d) Yes, this is an example of tuple unpacking. a=1 7. Tuples can’t be made keys of a dictionary.
and b=(2,3) a) True
Answer: c b) False
Explanation: For unpacking to happen, the number Answer: b
of values of the right hand side Explanation: Tuples can be made keys of a
must be equal to the number of variables on the dictionary because they are hashable.
left hand side. 8. Is the following Python code valid?
4. What will be the output of the following Python >>> a=2,3,4,5
code? >>> a
>>> a=(1,2) a) Yes, 2 is printed
>>> b=(3,4) b) Yes, [2,3,4,5] is printed
>>> c=a+b Page 256 of 391
Page 255 of 391 c) No, too many values to unpack
>>> c d) Yes, (2,3,4,5) is printed
a) (4,6) Answer: d
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.
98

c) (7,6) 10. Is the following Python code valid?


Page

d) Nothing is printed >>> a=(1,2,3)


Answer: c >>> b=a.update(4,)

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


a) Yes, a=(1,2,3,4) and b=(1,2,3,4) d) Error
b) Yes, a=(1,2,3) and b=(1,2,3,4) Answer: a
c) No because tuples are immutable Explanation: In can be used to check if the key is
d) No because wrong syntax for update() method int dictionary.
Answer: c 4. What will be the output of the following Python
Explanation: Tuple doesn’t have any update() code snippet?
attribute because it is immutable. 1. d1 = {"john":40, "peter":45}
11. What will be the output of the following Python 2. d2 = {"john":466, "peter":45}
code? 3. d1 == d2
>>> a=[(2,4),(1,2),(3,9)] a) True
>>> a.sort() b) False
>>> a c) None
a) [(1, 2), (2, 4), (3, 9)] d) Error
b) [(2,4),(1,2),(3,9)] Answer: b
c) Error because tuples are immutable Explanation: If d2 was initialized as d2 = d1 the
d) Error, tuple has no sort attribute answer would be true.
Answer: a 5. What will be the output of the following Python
Explanation: A list of tuples is a list itself. Hence code snippet?
items of a list can be sorted. 1. d1 = {"john":40, "peter":45}
Page 257 of 391 2. d2 = {"john":466, "peter":45}
Python Questions and Answers – Dictionary – 1 Page 258 of 391
1. Which of the following statements create a 3. d1 > d2
dictionary? a) True
a) d = {} b) False
b) d = {“john”:40, “peter”:45} c) Error
c) d = {40:”john”, 45:”peter”} d) None
d) All of the mentioned Answer: c
Answer: d Explanation: Arithmetic > operator cannot be used
Explanation: Dictionaries are created by specifying with dictionaries.
keys and values. 6. What will be the output of the following Python
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 Explanation: Execute in the shell to verify.
keys and values. 7. Suppose d = {“john”:40, “peter”:45}, to delete
3. What will be the output of the following Python the 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”)
99

a) True c) del d[“john”]


Page

b) False d) del d(“john”:40)


c) None Answer: c

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


Explanation: Execute in the shell to verify. accessed using keys but the keys of a
8. Suppose d = {“john”:40, “peter”:45}. To obtain dictionary can’t be accessed using values.
the number of entries in dictionary which 2. Which of the following is not a declaration of the
command do we use? dictionary?
a) d.size() a) {1: ‘A’, 2: ‘B’}
b) len(d) b) dict([[1,”A”],[2,”B”]])
c) size(d) c) {1,”A”,2”B”}
d) d.len() d) { }
Answer: b Answer: c
Explanation: Execute in the shell to verify. Explanation: Option c is a set, not a dictionary.
9. What will be the output of the following Python 3. What will be the output of the following Python
code snippet? code snippet?
1. d = {"john":40, "peter":45} a={1:"A",2:"B",3:"C"}
2. print(list(d.keys())) for i,j in a.items():
a) [“john”, “peter”] print(i,j,end=" ")
b) [“john”:40, “peter”:45] a) 1 A 2 B 3 C
c) (“john”, “peter”) b) 1 2 3
Page 259 of 391 c) A B C
d) (“john”:40, “peter”:45) d) 1:”A” 2:”B” 3:”C”
Answer: a Answer: a
Explanation: The output of the code shown above Explanation: In the above code, variables i and j
is a list containing only keys of the iterate over the keys and values of the
dictionary d, in the form of a list. dictionary respectively.
10. Suppose d = {“john”:40, “peter”:45}, what 4. What will be the output of the following Python
happens when we try to retrieve a value using code snippet?
the expression d[“susan”]? a={1:"A",2:"B",3:"C"}
a) Since “susan” is not a value in the set, Python print(a.get(1,4))
raises a KeyError exception a) 1
b) It is executed fine and no exception is raised, and b) A
it returns None c) 4
c) Since “susan” is not a key in the set, Python d) Invalid syntax for get method
raises a KeyError exception Answer: b
d) Since “susan” is not a key in the set, Python Explanation: The get() method returns the value of
raises a syntax error the key if the key is present in the
Answer: c dictionary and the default value(second
Explanation: Execute in the shell to verify. parameter) 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
100

c) Dictionaries aren’t ordered b) A


d) Dictionaries are mutable c) 5
Page

Answer: b d) 4
Explanation: The values of a dictionary can be Answer: d

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


Explanation: The get() method returns the default b=a.copy()
value(second parameter) if the key b[2]="D"
isn’t present in the dictionary. print(a)
6. What will be the output of the following Python a) Error, copy() method doesn’t exist for
code snippet? dictionaries
a={1:"A",2:"B",3:"C"} b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
print(a.setdefault(3)) c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
a) {1: ‘A’, 2: ‘B’, 3: ‘C’} d) “None” is printed
b) C Answer: b
c) {1: 3, 2: 3, 3: 3} Explanation: Changes made in the copy of the
d) No method called setdefault() exists for dictionary isn’t reflected in the original
dictionary one.
Answer: b 10. What will be the output of the following Python
Explanation: setdefault() is similar to get() but will code?
set dict[key]=default if key is not a={1:"A",2:"B",3:"C"}
already in the dictionary. a.clear()
7. What will be the output of the following Python print(a)
code snippet? a) None
a={1:"A",2:"B",3:"C"} b) { None:None, None:None, None:None}
a.setdefault(4,"D") c) {1:None, 2:None, 3:None}
print(a) d) { }
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’} Answer: d
b) None Explanation: The clear() method clears all the key-
c) Error value pairs in the dictionary.
d) [1,3,6,10] 11. Which of the following isn’t true about
Answer: a dictionary keys?
Explanation: setdefault() will set dict[key]=default a) More than one key isn’t allowed
if key is not already in the b) Keys must be immutable
dictionary. c) Keys must be integers
8. What will be the output of the following Python d) When duplicate keys encountered, the last
code? assignment wins
a={1:"A",2:"B",3:"C"} Answer: c
b={4:"D",5:"E"} Explanation: Keys of a dictionary may be any data
a.update(b) type that is immutable.
print(a) 12. What will be the output of the following Python
a) {1: ‘A’, 2: ‘B’, 3: ‘C’} code?
b) Method update() doesn’t exist for dictionaries a={1:5,2:3,3:4}
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’} a.pop(3)
d) {4: ‘D’, 5: ‘E’} print(a)
Page 262 of 391 a) {1: 5}
Answer: c b) {1: 5, 2: 3}
Explanation: update() method adds dictionary b’s c) Error, syntax error for pop() method
key-value pairs to dictionary a. Page 263 of 391
101

Execute in python shell to verify. d) {1: 5, 3: 4}


9. What will be the output of the following Python Answer: b
Page

code? Explanation: pop() method removes the key-value


a={1:"A",2:"B",3:"C"} pair for the key mentioned in the

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


pop() method. d) Values of a dictionary can be a mixture of letters
13. What will be the output of the following Python and numbers
code? Answer: c
a={1:5,2:3,3:4} Explanation: More than one key can have the
print(a.pop(4,9)) same value.
a) 9 2. What will be the output of the following Python
b) 3 code snippet?
c) Too many arguments for pop() method >>> a={1:"A",2:"B",3:"C"}
d) 4 >>> del a
Answer: a a) method del doesn’t exist for the dictionary
Explanation: pop() method returns the value when b) del deletes the values in the dictionary
the key is passed as an argument c) del deletes the entire dictionary
and otherwise returns the default value(second d) del deletes the keys in the dictionary
argument) if the key isn’t present in the Answer: c
dictionary. Explanation: del deletes the entire dictionary and
14. What will be the output of the following Python any further attempt to access it will
code? throw an error.
a={1:"A",2:"B",3:"C"} 3. If a is a dictionary with some key-value pairs,
for i in a: what does a.popitem() do?
print(i,end=" ") a) Removes an arbitrary element
a) 1 2 3 b) Removes all the key-value pairs
b) ‘A’ ‘B’ ‘C’ c) Removes the key-value pair for the key given as
c) 1 ‘A’ 2 ‘B’ 3 ‘C’ an argument
d) Error, it should be: for i in a.items(): d) Invalid method for dictionary
Answer: a Answer: a
Explanation: The variable i iterates over the keys Explanation: The method popitem() removes a
of the dictionary and hence the keys random key-value pair.
are printed. 4. What will be the output of the following Python
15. What will be the output of the following Python code snippet?
code? total={}
>>> a={1:"A",2:"B",3:"C"} def insert(items):
>>> a.items() if items in total:
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 c) 2
if false? Page 265 of 391
102

a) More than one key can have the same value d) 0


b) The values of the dictionary can be accessed as Answer: c
Page

dict[key] Explanation: The insert() function counts the


c) Values of a dictionary must be unique number of occurrences of the item being

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


inserted into the dictionary. There are only 2 keys d) An exception is thrown
present since the key ‘Apple’ is Answer: a
repeated. Thus, the length of the dictionary is 2. Explanation: In the second line of code, the
5. What will be the output of the following Python dictionary becomes an empty dictionary.
code snippet? Thus, length=0.
a = {} 8. What will be the output of the following Python
a[1] = 1 code snippet?
a['1'] = 2 test = {1:'A', 2:'B', 3:'C'}
a[1]=a[1]+1 del test[1]
count = 0 test[1] = 'D'
for i in a: del test[2]
count += a[i] print(len(test))
print(count) a) 0
a) 1 b) 2
b) 2 c) Error as the key-value pair of 1:’A’ is already
c) 4 deleted
d) Error, the keys can’t be a mixture of letters and d) 1
numbers Answer: b
Answer: c Explanation: After the key-value pair of 1:’A’ is
Explanation: The above piece of code basically deleted, the key-value pair of 1:’D’ is
finds the sum of the values of keys. added.
6. What will be the output of the following Python 9. What will be the output of the following Python
code snippet? code snippet?
numbers = {} a = {}
letters = {} a[1] = 1
comb = {} a['1'] = 2
numbers[1] = 56 a[1.0]=4
numbers[3] = 7 count = 0
letters[4] = 'B' for i in a:
comb['Numbers'] = numbers count += a[i]
comb['Letters'] = letters print(count)
print(comb) a) An exception is thrown
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={}
103

Page 266 of 391 a['a']=1


a) 0 a['b']=[2,3,4]
Page

b) None print(a)
c) 3 Page 267 of 391

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


a) Exception is thrown the n number key-value pairs where
b) {‘b’: [2], ‘a’: 1} the value is the most recurring.
c) {‘b’: [2], ‘a’: [3]} Page 268 of 391
d) {‘b’: [2, 3, 4], ‘a’: 1} 14. What will be the output of the following Python
Answer: d code snippet?
Explanation: Mutable members can be used as the >>> import collections
values of the dictionary but they >>> a=collections.Counter([2,2,3,3,3,4])
cannot be used as the keys of the dictionary. >>> b=collections.Counter([2,2,3,4,4])
11. What will be the output of the following Python >>> a|b
code snippet? a) Counter({3: 3, 2: 2, 4: 2})
>>>import collections b) Counter({2: 2, 3: 1, 4: 1})
>>> a=collections.Counter([1,1,2,3,3,4,4,4]) c) Counter({3: 2})
>>> a d) Counter({4: 1})
a) {1,2,3,4} Answer: a
b) Counter({4, 1, 3, 2}) Explanation: a|b returns the pair of keys and the
c) Counter({4: 3, 1: 2, 3: 2, 2: 1}) highest recurring value.
d) {4: 3, 1: 2, 3: 2, 2: 1} 15. What will be the output of the following Python
Answer: c code snippet?
Explanation: The statement >>> import collections
a=collections.OrderedDict() generates a dictionary >>> a=collections.Counter([3,3,4,5])
with >>> b=collections.Counter([3,4,4,5,5,5])
the number as the key and the count of times the >>> a&b
number appears as the value. a) Counter({3: 12, 4: 1, 5: 1})
12. What will be the output of the following Python b) Counter({3: 1, 4: 1, 5: 1})
code snippet? c) Counter({4: 2})
>>>import collections d) Counter({5: 1})
>>> b=collections.Counter([2,2,3,4,4,4]) Answer: b
>>> b.most_common(1) Explanation: a&b returns the pair of keys and the
a) Counter({4: 3, 2: 2, 3: 1}) lowest recurring value.
b) {3:1} Page 269 of 391
c) {4:3} Python Questions and Answers – Dictionary – 4
d) [(4, 3)] 1. The following Python code is invalid.
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
104

c) {4:3} code?
d) [(4, 3)] count={}
Page

Answer: d count[(1,2,4)] = 5
Explanation: The most_common() method returns count[(4,2,1)] = 7

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


count[(1,2)] = 6 d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
count[(4,2,1)] = 2 Answer: d
tot = 0 Explanation: Dictionary comprehension is
for i in count: implemented in the above piece of code.
tot=tot+count[i] 6. What will be the output of the following Python
print(len(count)+tot) code?
a) 25 >>> a={}
b) 17 >>> a.fromkeys([1,2,3],"check")
c) 16 a) Syntax error
d) Tuples can’t be made keys of a dictionary b) {1:”check”,2:”check”,3:”check”}
Answer: c c) “check”
Explanation: Tuples can be made keys of a d) {1:None,2:None,3:None}
dictionary. Length of the dictionary is 3 as Answer: b
the value of the key (4,2,1) is modified to 2. The Explanation: The dictionary takes values of keys
value of the variable tot is 5+6+2=13. from the list and initializes it to the
3. What will be the output of the following Python default value (value given in the second
code? parameter). Execute in Python shell to verify.
a={} 7. What will be the output of the following Python
a[2]=1 code?
a[1]=[2,3,4] >>> b={}
print(a[1][1]) >>> all(b)
a) [2,3,4] a) { }
b) 3 b) False
c) 2 c) True
d) An exception is thrown d) An exception is thrown
Answer: b Answer: c
Explanation: Now, a={1:[2,3,4],2:1} . a[1][1] refers Explanation: Function all() returns True if all keys
to second element having key 1. of the dictionary are true or if the
Page 270 of 391 dictionary is empty.
4. What will be the output of the following Python Page 271 of 391
code? 8. If b is a dictionary, what does any(b) do?
>>> a={'B':5,'A':9,'C':7} a) Returns True if any key of the dictionary is true
>>> 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()))
105

>>> a >>> b
a) Dictionary comprehension doesn’t exist a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
Page

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’: }

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


d) {1: ‘a’, 2: ‘b’, 3: ‘c’} 13. What will be the output of the following Python
Answer: d code?
Explanation: The above piece of code inverts the >>> import collections
key-value pairs in the dictionary. >>> a=dict()
10. What will be the output of the following Python >>> a=collections.defaultdict(str)
code? >>> a['A']
>>> a={i: 'A' + str(i) for i in range(5)} a) An exception is thrown since the dictionary is
>>> a empty
a) An exception is thrown b) ‘ ‘
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’} c) ‘A’
c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’} d) 0
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’} Answer: b
Answer: b Explanation: The statement
Explanation: Dictionary comprehension and string a=collections.defaultdict(str) gives the default
concatenation is implemented in the value of ‘ ‘
above piece of code. even if the keys don’t exist in the dictionary.
11. What will be the output of the following Python 14. What will be the output of the following Python
code? code?
>>> a=dict() >>> import collections
>>> a[1] >>> b=dict()
a) An exception is thrown since the dictionary is >>> b=collections.defaultdict(lambda: 7)
empty >>> b[4]
b) ‘ ‘ a) 4
c) 1 b) 0
d) 0 c) An exception is thrown
Answer: a d) 7
Explanation: The values of a dictionary can be Answer: d
accessed through the keys only if the Explanation: The statement
keys exist in the dictionary. a=collections.defaultdict(lambda: x) gives the
12. What will be the output of the following Python default value
code? of x even if the keys don’t exist in the dictionary.
Page 272 of 391 15. What will be the output of the following Python
>>> 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 Answer: b
106

value of 0 Explanation: The line of code


(since int data type is given within the parenthesis) a=collections.OrderedDict() generates a dictionary
Page

even if the keys don’t exist in the satisfying the conditions given within the
dictionary. parenthesis and in an ascending order of the

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


keys. Explanation: Docstring used for providing the
Page 274 of 391 specifications of program elements.
Python Questions and Answers – Python Modules 5. Which of the following is true about top-down
1. Which of these definitions correctly describes a design process?
module? a) The details of a program design are addressed
a) Denoted by triple quotes for providing the before the overall design
specification of certain program elements b) Only the details of the program are addressed
b) Design and implementation of specific c) The overall design of the program is addressed
functionality to be incorporated into a program before the details
c) Defines the specification of how it is to be used Page 275 of 391
d) Any program that reuses code d) Only the design of the program is addressed
Answer: b Answer: c
Explanation: The term “module” refers to the Explanation: Top-down design is an approach for
implementation of specific functionality deriving a modular design in which
to be incorporated into a program. the overall design.
2. Which of the following is not an advantage of 6. In top-down design every module is broken into
using modules? same number of submodules.
a) Provides a means of reuse of program code a) True
b) Provides a means of dividing up tasks b) False
c) Provides a means of reducing the size of the Answer: b
program Explanation: In top-down design every module can
d) Provides a means of testing individual parts of even be broken down into different
the program number of submodules.
Answer: c 7. All modular designs are because of a top-down
Explanation: The total size of the program remains design process.
the same regardless of whether a) True
modules are used or not. Modules simply divide b) False
the program. Answer: b
3. Program code making use of a given module is Explanation: The details of the program can be
called a ______ of the module. addressed before the overall design too.
a) Client Hence, all modular designs are not because of a
b) Docstring top-down design process.
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
107

b) Modularity from mod2 import change


c) Client #main
Page

d) Docstring s=[1,2,3]
Answer: d change(s)

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


a) [2,4,6] module becomes available to, but not part of, the
b) [1,4,9] importing module.
c) 12. Which of the following is false about “from-
[2,4,6] import” form of import?
[1,4,9] a) The syntax is: from modulename import
d) There is a name clash identifier
Answer: d b) This form of import prevents name clash
Explanation: A name clash is when two different c) The namespace of imported module becomes
entities with the same identifier part of importing module
become part of the same scope. Since both the d) The identifiers in module are accessed directly
modules have the same function name, as: identifier
there is a name clash. Answer: b
Page 276 of 391 Explanation: In the “from-import” form of import,
9. Which of the following isn’t true about main there may be name clashes because
modules? names of the imported identifiers aren’t specified
a) When a python file is directly executed, it is along with the module name.
considered main module of a program 13. Which of the statements about modules is
b) Main modules may import any number of false?
modules a) In the “from-import” form of import, identifiers
c) Special name given to main modules is: __main__ beginning with two underscores are
d) Other main modules can import main modules private and aren’t imported
Answer: d b) dir() built-in function monitors the items in the
Explanation: Main modules are not meant to be namespace of the main module
imported into other modules. c) In the “from-import” form of import, all
10. Which of the following is not a valid identifiers regardless of whether they are private
namespace? or public are imported
a) Global namespace d) When a module is loaded, a compiled version of
b) Public namespace the module with file extension .pyc is
c) Built-in namespace Page 277 of 391
d) Local namespace automatically produced
Answer: b Answer: c
Explanation: During a Python program execution, Explanation: In the “from-import” form of import,
there are as many as three identifiers beginning with two
namespaces – built-in namespace, global underscores are private and aren’t imported.
namespace and local namespace. 14. What will be the output of the following Python
11. Which of the following is false about “import code?
modulename” form of import? from math import factorial
a) The namespace of imported module becomes print(math.factorial(5))
part of importing module a) 120
b) This form of import prevents name clash b) Nothing is printed
c) The namespace of imported module becomes c) Error, method factorial doesn’t exist in math
available to importing module module
d) The identifiers in module are accessed as: d) Error, the statement should be: print(factorial(5))
108

modulename.identifier Answer: d
Answer: a Explanation: In the “from-import” form of import,
Page

Explanation: In the “import modulename” form of the imported identifiers (in this
import, the namespace of imported case factorial()) aren’t specified along with the

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


module name. whose absolute value is that of the
15. What is the order of namespaces in which first argument and the sign is that of the second
Python looks for an identifier? argument.
a) Python first searches the global namespace, then 4. What is displayed on executing print(math.fabs(-
the local namespace and finally the builtin 3.4))?
namespace a) -3.4
b) Python first searches the local namespace, then b) 3.4
the global namespace and finally the builtin c) 3
namespace d) -3
c) Python first searches the built-in namespace, Answer: b
then the global namespace and finally the Explanation: A negative floating point number is
local namespace returned as a positive floating point
d) Python first searches the built-in namespace, number.
then the local namespace and finally the 5. Is the output of the function abs() the same as
global namespace that of the function math.fabs()?
Answer: b a) sometimes
Explanation: Python first searches for the local, b) always
then the global and finally the built-in c) never
namespace. d) none of the mentioned
Page 278 of 391 Page 279 of 391
Python Questions and Answers – Math module– 1 Answer: a
1. What is returned by math.ceil(3.4)? Explanation: math.fabs() always returns a float
a) 3 and does not work with complex
b) 4 numbers whereas the return type of abs() is
c) 4.0 determined by the type of value that is
d) 3.0 passed to it.
Answer: b 6. What is the value returned by math.fact(6)?
Explanation: The ceil function returns the smallest a) 720
integer that is bigger than or equal b) 6
to the number itself. c) [1, 2, 3, 6]
2. What is the value returned by math.floor(3.4)? d) error
a) 3 Answer: d
b) 4 Explanation: NameError, fact() is not defined.
c) 4.0 7. What is the value of x if x = math.factorial(0)?
d) 3.0 a) 0
Answer: a b) 1
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 Explanation: Factorial of 0 is 1.
print(math.copysign(3, -1))? 8. What is math.factorial(4.0)?
a) 1 a) 24
b) 1.0 b) 1
109

c) -3 c) error
d) -3.0 d) none of the mentioned
Page

Answer: d Answer: a
Explanation: The copysign function returns a float Explanation: The factorial of 4 is returned.

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


9. What will be the output of we use sum with floating point
print(math.factorial(4.5))? numbers. Hence the function fsum is preferable.
a) 24 4. What is returned by math.isfinite(float(‘inf’))?
b) 120 a) True
c) error b) False
d) 24.0 c) None
Answer: c d) error
Explanation: Factorial is only defined for non- Answer: b
negative integers. Explanation: float(‘inf’) is not a finite number.
10. What is math.floor(0o10)? 5. What is returned by math.isfinite(float(‘nan’))?
a) 8 a) True
b) 10 b) False
c) 0 c) None
d) 9 d) error
Page 280 of 391 Page 282 of 391
Answer: a Answer: b
Explanation: 0o10 is 8 and floor(8) is 8. Explanation: float(‘nan’) is not a finite number.
Page 281 of 391 6. What is x if x = math.isfinite(float(‘0.0’))?
Python Questions and Answers – Math module– 2 a) True
1. What does the function math.frexp(x) return? b) False
a) a tuple containing the mantissa and the c) None
exponent of x d) error
b) a list containing the mantissa and the exponent Answer: a
of x Explanation: float(‘0.0’) is a finite number.
c) a tuple containing the mantissa of x 7. What will be the output of the following Python
d) a list containing the exponent of x code?
Answer: a >>> -float('inf') + float('inf')
Explanation: It returns a tuple with two elements. a) inf
The first element is the mantissa and b) nan
the second element is the exponent. c) 0
2. What is the result of math.fsum([.1 for i in d) 0.0
range(20)])? Answer: b
a) 2.0 Explanation: The result of float(‘inf’)-float(‘inf’) is
b) 20 undefined.
c) 2 8. What will be the output of the following Python
d) 2.0000000000000004 code?
Answer: a print(math.isinf(float('-inf')))
Explanation: The function fsum returns an a) error, the minus sign shouldn’t have been inside
accurate 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
110

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)?
Page

Answer: d a) 1
Explanation: There is some loss of accuracy when b) 2.0

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


c) 0.5 d) none of the mentioned
d) none of the mentioned Answer: a
Answer: d Explanation: One is subtracted from the result of
Explanation: The value returned by ldexp(x, y) is x math.exp(p) and returned.
* (2 ** y). In the current case x is 5. What is the default base used when math.log(x)
1.0. is found?
10. What is returned by math.modf(1.0)? a) e
a) (0.0, 1.0) b) 10
b) (1.0, 0.0) c) 2
c) (0.5, 1) d) none of the mentioned
Page 283 of 391 Answer: a
d) (0.5, 1.0) Explanation: The natural log of x is returned by
Answer: a default.
Explanation: The first element is the fractional part Page 285 of 391
and the second element is the 6. Which of the following aren’t defined in the math
integral part of the argument. module?
Page 284 of 391 a) log2()
Python Questions and Answers – Math module– 3 b) log10()
1. What is the result of math.trunc(3.1)? c) logx()
a) 3.0 d) none of the mentioned
b) 3 Answer: c
c) 0.1 Explanation: log2() and log10() are defined in the
d) 1 math module.
Answer: b 7. What is returned by int(math.pow(3, 2))?
Explanation: The integral part of the floating point a) 6
number is returned. b) 9
2. What is the output of print(math.trunc(‘3.1’))? c) error, third argument required
a) 3 d) error, too many arguments
b) 3.0 Answer: b
c) error Explanation: math.pow(a, b) returns a ** b.
d) none of the mentioned 8. What is output of print(math.pow(3, 2))?
Answer: c a) 9
Explanation: TypeError, a string does not have b) 9.0
__trunc__ method. c) None
3. Which of the following is the same as d) None of the mentioned
math.exp(p)? Answer: b
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)
111

4. What is returned by math.expm1(p)? Answer: b


a) (math.e ** p) – 1 Explanation: The function returns one floating
Page

b) math.e ** (p – 1) point number.


c) error 10. What does math.sqrt(X, Y) do?

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


a) calculate the Xth root of Y the correct syntax world be:
b) calculate the Yth root of X random.choice([2,3,4]).
c) error 4. What will be the output of the following Python
d) return a tuple with the square root of X and Y code?
Answer: c import random
Explanation: The function takes only one random.choice([10.4, 56.99, 76])
argument. a) Error
Page 286 of 391 b) Either 10.4, 56.99 or 76
Python Question and Answers – Random module – c) Any number other than 10.4, 56.99 and 76
1 d) 56.99 only
1. To include the use of functions which are present Answer: b
in the random library, we must use the Explanation: The function random.choice(a,b,c,d)
option: returns a random number which is
a) import random Page 287 of 391
b) random.h selected from a, b, c and d. The output can be
c) import.random either a, b, c or d. Hence the output of the
d) random.random snippet of code shown above can be either 10.4,
Answer: a 56.99 or 76.
Explanation: The command import random is used 5. What will be the output of the following Python
to import the random module, function (random module has already
which enables us to use the functions which are been imported)?
present in the random library. random.choice('sun')
2. The output of the following Python code is either a) sun
1 or 2. b) u
import random c) either s, u or n
random.randint(1,2) d) error
a) True Answer: c
b) False Explanation: The above function works with
Answer: a alphabets just as it does with numbers.
Explanation: The function random.randint(a,b) The output of this expression will be either s, u or
helps us to generate an integer between n.
‘a’ and ‘b’, including ‘a’ and ‘b’. In this case, since 6. What will be the output of the following Python
there are no integers between 1 and function, assuming that the random
2, the output will necessarily be either 1 or 2’. module has already been imported?
3. What will be the output of the following Python random.uniform(3,4)
code? a) Error
import random b) Either 3 or 4
random.choice(2,3,4) c) Any integer other than 3 and 4
a) An integer other than 2, 3 and 4 d) Any decimal value between 3 and 4
b) Either 2, 3 or 4 Answer: d
c) Error Explanation: This question depicts the basic
d) 3 only difference between the functions
Answer: c random.randint(a, b) and random.uniform(a, b).
112

Explanation: The code shown above displays the While random.randint(a,b) generates
incorrect syntax of the function an integer between ‘a’ and ‘b’, including ‘a’ and
Page

random.choice(). This functions takes its numeric ‘b’, the function random.uniform(a,b)
parameter in the form of a list. Hence generates a decimal value between ‘a’ and ‘b’.

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


7. What will be the output of the following Python a) (0,1)
function if the random module has b) (0,1]
already been imported? c) [0,1]
random.randint(3.5,7) d) [0,1)
a) Error Answer: d
b) Any integer between 3.5 and 7, including 7 Explanation: The function random.random()
c) Any integer between 3.5 and 7, excluding 7 generates a random value in the interval
d) The integer closest to the mean of 3.5 and 7 [0,1), that is, including zero but excluding one.
Answer: a 11. What will be the output of the following Python
Explanation: The function random.randint() does code?
not accept a decimal value as a random.randrange(0,91,5)
parameter. Hence the function shown above will a) 10
throw an error. b) 18
8. Which of the following functions helps us to c) 79
randomize the items of a list? d) 95
a) seed Answer: a
b) randomise Explanation: The function shown above will
c) shuffle generate an output which is a multiple of 5
d) uniform and is between 0 and 91. The only option which
Page 288 of 391 satisfies these criteria is 10. Hence the
Answer: c only possible output of this function is 10.
Explanation: The function shuffle, which is 12. Both the functions randint and uniform accept
included in the random module, helps us to ____________ parameters.
randomize the items of a list. This function takes a) 0
the list as a parameter. b) 1
9. What will be the output of the following Python c) 3
code? Page 289 of 391
random.seed(3) d) 2
random.randint(1,5) Answer: d
2 Explanation: Both of these functions, that is,
random.seed(3) randint and uniform are included in the
random.randint(1,5) random module and both of these functions
a) 3 accept 2 parameters. For example:
b) 2 random.uniform(a,b) where ‘a’ and ‘b’ specify the
c) Any integer between 1 and 5, including 1 and 5 range.
d) Any integer between 1 and 5, excluding 1 and 5 13. The randrange function returns only an integer
Answer: b value.
Explanation: We use the seed function when we a) True
want to use the same random number b) False
once again in our program. Hence the output of Answer: a
the code shown above will be 2, since 2 Explanation: The function randrange returns only
was generated previously following which we used an integer value. Hence this
the seed function. statement is true.
113

10. What is the interval of the value generated by 14. What will be the output of the following Python
the function random.random(), assuming code?
Page

that the random module has already been random.randrange(1,100,10)


imported? a) 32

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


b) 67 d) none of the mentioned
c) 91 Answer: c
d) 80 Explanation: Only integers can be returned.
Answer: c 3. Which of the following is equivalent to
Explanation: The output of this function can be random.randrange(3)?
any value which is a multiple of 10, a) range(3)
plus 1. Hence a value like 11, 21, 31, 41…91 can be b) random.choice(range(0, 3))
the output. Also, the value should c) random.shuffle(range(3))
necessarily be between 1 and 100. The only option d) random.select(range(3))
which satisfies this criteria is 91. Answer: b
15. What will be the output of the following Python Explanation: It returns one number from the given
function, assuming that the random range.
library has already been included? 4. The function random.randint(4) can return only
random.shuffle[1,2,24] one of the following values. Which?
a) Randomized list containing the same numbers in a) 4
any order b) 3.4
b) The same list, that is [1,2,24] c) error
c) A list containing any random numbers between 1 d) 5
and 24 Answer: c
d) Error Explanation: Error, the function takes two
Answer: d arguments.
Explanation: The function shown above will result 5. Which of the following is equivalent to
in an error because this is the random.randint(3, 6)?
incorrect syntax for the usage of the function a) random.choice([3, 6])
shuffle(). The list should be previously b) random.randrange(3, 6)
declared and then passed to this function to get an c) 3 + random.randrange(3)
output. d) 3 + random.randrange(4)
An example of the correct syntax: Answer: d
>>> l=['a','b','c','d'] Explanation: random.randint(3, 6) can return any
>>> random.shuffle(l) one of 3, 4, 5 and 6.
>>> print(l) Page 291 of 391
Page 290 of 391 6. Which of the following will not be returned by
Python Questions and Answers – Random Module random.choice(“1 ,”)?
–2 a) 1
1. What the does random.seed(3) return? b) (space)
a) True c) ,
b) None d) none of the mentioned
c) 3 Answer: d
d) 1 Explanation: Any of the characters present in the
Answer: b string may be returned.
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}))?
114

random.randrange(4)? a) 0
a) 0 b) 1
Page

b) 3 c) KeyError: 1
c) 2.3 d) none of the mentioned

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


Answer: a 2. Which keyword is used for function?
Explanation: It will not print 0 but dict[0] i.e. 1 a) Fun
may be printed. b) Define
8. What does random.shuffle(x) do when x = [1, 2, c) Def
3]? d) Function
a) error Answer: c
b) do nothing, it is a placeholder for a function that Explanation: None.
is yet to be implemented 3. What will be the output of the following Python
c) shuffle the elements of the list in-place code?
d) none of the mentioned 1. def sayHello():
Answer: c 2. print('Hello World!')
Explanation: The elements of the list passed to it 3. sayHello()
are shuffled in-place. 4. sayHello()
9. Which type of elements are accepted by a)
random.shuffle()? Hello World!
a) strings Hello World!
b) lists b)
c) tuples 'Hello World!'
d) integers 'Hello World!'
Answer: b c)
Explanation: Strings and tuples are immutable and Hello
an integer has no len(). Hello
10. What is the range of values that d) None of the mentioned
random.random() can return? Answer: a
a) [0.0, 1.0] Explanation: Functions are defined using the def
b) (0.0, 1.0] keyword. After this keyword comes an
c) (0.0, 1.0) identifier name for the function, followed by a pair
d) [0.0, 1.0) of parentheses which may enclose some
Answer: d names of variables, and by the final colon that ends
Explanation: Any number that is greater than or the line. Next follows the block of
equal to 0.0 and lesser than 1.0 can be statements that are part of this function.
returned. 1. def sayHello():
Page 292 of 391 2. print('Hello World!') # block belonging to the
CHAPTER-3 WORKING WITH FUNCTIONS function
1. Which of the following is the use of function in 3. # End of function #
python? Page 293 of 391
a) Functions are reusable pieces of programs 4.
b) Functions don’t provide better modularity for 5. sayHello() # call the function
your application 6. sayHello() # call the function again
c) you can’t also create your own functions 4. What will be the output of the following Python
d) All of the mentioned code?
Answer: a 1. def printMax(a, b):
Explanation: Functions are reusable pieces of 2. if a > b:
115

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:
Page

using the specified name anywhere in 5. print(a, 'is equal to', b)


your program and any number of times. 6. else:

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


7. print(b, 'is maximum') 5. x = 2
8. printMax(3, 4) 6. print('Changed global x to', x)
a) 3 7. func()
b) 4 8. print('Value of x is', x)
c) 4 is maximum a)
d) None of the mentioned x is 50
Answer: c Changed global x to 2
Explanation: Here, we define a function called Value of x is 50
printMax that uses two parameters called a b)
and b. We find out the greater number using a x is 50
simple if..else statement and then print the Changed global x to 2
bigger number. Value of x is 2
5. What will be the output of the following Python c)
code? x is 50
1. x = 50 Changed global x to 50
2. def func(x): Value of x is 50
3. print('x is', x) d) None of the mentioned
4. x = 2 Answer: b
5. print('Changed local x to', x) Explanation: The global statement is used to
6. func(x) declare that x is a global variable – hence, when
7. print('x is now', x) we assign a value to x inside the function, that
a) x is now 50 change is reflected when we use the value of x
b) x is now 2 in the main block.
c) x is now 100 7. What will be the output of the following Python
d) None of the mentioned code?
Answer: a 1. def say(message, times = 1):
Explanation: The first time that we print the value 2. print(message * times)
of the name x with the first line in the 3. say('Hello')
function’s body, Python uses the value of the 4. say('World', 5)
parameter declared in the main block, above a)
the function definition. Hello
Next, we assign the value 2 to x. The name x is local WorldWorldWorldWorldWorld
to our function. So, when we change b)
the value of x in the function, the x defined in the Hello
main block remains unaffected. World 5
With the last print function call, we display the c)
value of x as defined in the main block, Hello
thereby confirming that it is actually unaffected by World,World,World,World,World
the local assignment within the d)
previously called function. Hello
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
116

1. x = 50 make some parameters optional and use


2. def func(): Page 295 of 391
Page

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

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


the help of default argument values. You can without a default argument value, followed by
specify default argument values for parameters two parameters with default argument values.
by appending to the parameter name in the In the first usage, func(3, 7), the parameter a gets
function definition the assignment operator (=) the value 3, the parameter b gets the value
followed by the default value. 7 and c gets the default value of 10.
The function named say is used to print a string as In the second usage func(25, c=24), the variable a
many times as specified. If we don’t gets the value of 25 due to the position of
supply a value, then by default, the string is printed the argument. Then, the parameter c gets the value
just once. We achieve this by specifying of 24 due to naming i.e. keyword
a default argument value of 1 to the parameter arguments. The variable b gets the default value of
times. 5.
In the first usage of say, we supply only the string In the third usage func(c=50, a=100), we use
and it prints the string once. In the second keyword arguments for all specified values.
usage of say, we supply both the string and an Notice that we are specifying the value for
argument 5 stating that we want to say the parameter c before that for a even though a is
string message 5 times. defined before c in the function definition.
8. What will be the output of the following Python Page 296 of 391
code? 9. What will be the output of the following Python
1. def func(a, b=5, c=10): code?
2. print('a is', a, 'and b is', b, 'and c is', c) 1. def maximum(x, y):
3. 2. if x > y:
4. func(3, 7) 3. return x
5. func(25, c = 24) 4. elif x == y:
6. func(c = 50, a = 100) 5. return 'The numbers are equal'
a) 6. else:
a is 7 and b is 3 and c is 10 7. return y
a is 25 and b is 5 and c is 24 8.
a is 5 and b is 100 and c is 50 9. print(maximum(2, 3))
b) a) 2
a is 3 and b is 7 and c is 10 b) 3
a is 5 and b is 25 and c is 24 c) The numbers are equal
a is 50 and b is 100 and c is 5 d) None of the mentioned
c) Answer: b
a is 3 and b is 7 and c is 10 Explanation: The maximum function returns the
a is 25 and b is 5 and c is 24 maximum of the parameters, in this case the
a is 100 and b is 5 and c is 50 numbers supplied to the function. It uses a simple
d) None of the mentioned if..else statement to find the greater value
Answer: c and then returns that value.
Explanation: If you have some functions with many 10. Which of the following is a feature of DocString?
parameters and you want to specify only a) Provide a convenient way of associating
some of them, then you can give values for such documentation with Python modules, functions,
parameters by naming them – this is called classes, and methods
keyword arguments – we use the name (keyword) b) All functions should have a docstring
117

instead of the position (which we have c) Docstrings can be accessed by the __doc__
been using all along) to specify the arguments to attribute on objects
Page

the function. d) All of the mentioned


The function named func has one parameter Answer: d

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


Explanation: Python has a nifty feature called c) All of the mentioned
documentation strings, usually referred to by d) None of the mentioned
its shorter name docstrings. DocStrings are an Answer: a
important tool that you should make use of Explanation: Each object in Python has a unique id.
since it helps to document the program better and The id() function returns the object’s id.
makes it easier to understand. 16. Which of the following refers to mathematical
11. Which are the advantages of functions in function?
python? a) sqrt
a) Reducing duplication of code b) rhombus
b) Decomposing complex problems into simpler c) add
pieces d) rhombus
c) Improving clarity of the code Answer: a
d) All of the mentioned Explanation: Functions that are always available for
Answer: d usage, functions that are contained
Explanation: None. within external modules, which must be imported
12. What are the two main types of functions? and functions defined by a programmer
a) Custom function with the def keyword.
b) Built-in function & User defined function Eg: math import sqrt
c) User function A sqrt() function is imported from the math
Page 297 of 391 module.
d) System function Page 298 of 391
Answer: b 17. What will be the output of the following Python
Explanation: Built-in functions and user defined code?
ones. The built-in functions are part of the 1. def cube(x):
Python language. Examples are: dir(), len() or abs(). 2. return x * x * x
The user defined functions are functions 3. x = cube(3)
created with the def keyword. 4. print x
13. Where is function defined? a) 9
a) Module b) 3
b) Class c) 27
c) Another function d) 30
d) All of the mentioned Answer: c
Answer: d Explanation: A function is created to do a specific
Explanation: Functions can be defined inside a task. Often there is a result from such a
module, a class or another function. task. The return keyword is used to return values
14. What is called when a function is defined inside from a function. A function may or may not
a class? return a value. If a function does not have a return
a) Module keyword, it will send a none value.
b) Class 18. What will be the output of the following Python
c) Another function code?
d) Method 1. def C2F(c):
Answer: d 2. return c * 9/5 + 32
Explanation: None. 3. print C2F(100)
118

15. Which of the following is the use of id() function 4. print C2F(0)
in python? a)
Page

a) Id returns the identity of the object 212


b) Every object doesn’t have a unique id 32

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


b) 8. print sum.__doc__
314 9. print sum(1, 2, 3)
24 10.print sum(1, 2, 3, 4, 5)
c) a)
567 6
98 15
d) None of the mentioned b)
Answer: a 6
Explanation: The code shown above is used to 100
convert a temperature in degree celsius to c)
fahrenheit. 123
19. What will be the output of the following Python 12345
code? d) None of the mentioned
1. def power(x, y=2): Answer: a
2. r = 1 Explanation: We use the * operator to indicate, that
3. for i in range(y): the function will accept arbitrary number
4. r = r * x of arguments. The sum() function will return the
5. return r sum of all arguments. The first string in the
6. print power(3) function body is called the function documentation
7. print power(3, 3) string. It is used to document the
a) function. The string must be in triple quotes.
212 21. Python supports the creation of anonymous
32 functions at runtime, using a construct called
b) __________
Page 299 of 391 a) lambda
9 b) pi
27 c) anonymous
c) d) none of the mentioned
567 Page 300 of 391
98 Answer: a
d) None of the mentioned Explanation: Python supports the creation of
Answer: b anonymous functions (i.e. functions that are not
Explanation: The arguments in Python functions bound to a name) at runtime, using a construct
may have implicit values. An implicit value called lambda. Lambda functions are
is used, if no value is provided. Here we created a restricted to a single expression. They can be used
power function. The function has one wherever normal functions can be used.
argument with an implicit value. We can call the 22. What will be the output of the following Python
function with one or two arguments. code?
20. What will be the output of the following Python 1. y = 6
code? 2. z = lambda x: x * y
1. def sum(*args): 3. print z(8)
2. '''Function returns the sum a) 48
3. of all values''' b) 14
119

4. r = 0 c) 64
5. for i in args: d) None of the mentioned
Page

6. r += i Answer: a
7. return r Explanation: The lambda keyword creates an

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


anonymous function. The x is a parameter, that a) 432
is passed to the lambda function. The parameter is b) 24000
followed by a colon character. The code c) 430
next to the colon is the expression that is executed, d) No output
when the lambda function is called. The Answer: a
lambda function is assigned to the z variable. Explanation: None.
The lambda function is executed. The number 8 is 28. What will be the output of the following Python
passed to the anonymous function and it code?
returns 48 as the result. Note that z is not a name 1. def writer():
for this function. It is only a variable to 2. title = 'Sir'
which the anonymous function was assigned. 3. name = (lambda x:title + ' ' + x)
23. What will be the output of the following Python 4. return name
code? 5.
1. lamb = lambda x: x ** 3 6. who = writer()
2. print(lamb(5)) 7. who('Arthur')
a) 15 a) Arthur Sir
b) 555 b) Sir Arthur
c) 125 c) Arthur
d) None of the mentioned d) None of the mentioned
Answer: c Answer: b
Explanation: None. Explanation: None.
24. Does Lambda contains return statements? 29. What will be the output of the following Python
a) True code?
b) False 1. L = [lambda x: x ** 2,
Answer: b 2. lambda x: x ** 3,
Explanation: lambda definition does not include a 3. lambda x: x ** 4]
return statement. it always contains an 4.
expression which is returned. Also note that we can 5. for f in L:
put a lambda definition anywhere a 6. print(f(3))
function is expected. We don’t have to assign it to a a)
variable at all. 27
25. Lambda is a statement. 81
a) True Page 302 of 391
b) False 343
Page 301 of 391 b)
Answer: b 69
Explanation: lambda is an anonymous function in 12
Python. Hence this statement is false. c)
26. Lambda contains block of statements. 9
a) True 27
b) False 81
Answer: b d) None of the mentioned
Explanation: None. Answer: c
120

27. What will be the output of the following Python Explanation: None.
code? 30. What will be the output of the following Python
Page

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)

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


2. min(101*99, 102*98) def a(b):
a) 9997 b = b + [5]
b) 9999 c = [1, 2, 3, 4]
c) 9996 a(c)
d) None of the mentioned print(len(c))
Answer: c a) 4
Explanation: None. b) 5
31. What is a variable defined outside a function c) 1
referred to as? d) An exception is thrown
a) A static variable Answer: b
b) A global variable Explanation: Since a list is mutable, any change
c) A local variable made in the list in the function is reflected
d) An automatic variable outside the function.
Answer: b 35. What will be the output of the following Python
Explanation: The value of a variable defined outside code?
all function definitions is referred to as a=10
a global variable and can be used by multiple b=20
functions of the program. def change():
32. What is a variable defined inside a function global b
referred to as? a=45
a) A global variable b=56
b) A volatile variable change()
c) A local variable print(a)
d) An automatic variable print(b)
Answer: c a)
Explanation: The variable inside a function is called 10
as local variable and the variable 56
definition is confined only to that function. b)
33. What will be the output of the following Python 45
code? 56
Page 303 of 391 Page 304 of 391
i=0 c)
def change(i): 10
i=i+1 20
return i d) Syntax Error
change(1) Answer: a
print(i) Explanation: The statement “global b” allows the
a) 1 global value of b to be accessed and
b) Nothing is displayed changed. Whereas the variable a is local and hence
c) 0 the change isn’t reflected outside the
d) An exception is thrown function.
Answer: c 36. What will be the output of the following Python
Explanation: Any change made in to an immutable code?
121

data type in a function isn’t reflected def change(i = 1, j = 2):


outside the function. i=i+j
Page

34. What will be the output of the following Python j=j+1


code? print(i, j)

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


change(j = 1, i = 2) Answer: a
a) An exception is thrown because of conflicting Explanation: The loop runs three times and ‘z’ is
values printed each time.
b) 1 2 40. What will be the output of the following Python
c) 3 3 code?
d) 3 2 def find(a, **b):
Answer: d print(type(b))
Explanation: The values given during function call is find('letters',A='1',B='2')
taken into consideration, that is, i=2 a) String
and j=1. b) Tuple
37. What will be the output of the following Python c) Dictionary
code? d) An exception is thrown
def change(one, *two): Answer: c
print(type(two)) Explanation: b combines the remaining parameters
change(1,2,3,4) into a dictionary.
a) Integer 41. Which of the following functions is a built-in
b) Tuple function in python?
c) Dictionary a) seed()
d) An exception is thrown b) sqrt()
Answer: b c) factorial()
Explanation: The parameter two is a variable d) print()
parameter and consists of (2,3,4). Hence the Answer: d
data type is tuple. Explanation: The function seed is a function which is
38. If a function doesn’t have a return statement, present in the random module. The
which of the following does the function functions sqrt and factorial are a part of the math
return? module. The print function is a built-in
a) int function which prints a value directly to the system
b) null output.
c) None 42. What will be the output of the following Python
d) An exception is thrown without the return expression?
statement round(4.576)
Page 305 of 391 a) 4.5
Answer: c b) 5
Explanation: A function can exist without a return c) 4
statement and returns None if the function d) 4.6
doesn’t have a return statement. Page 306 of 391
39. What will be the output of the following Python Answer: b
code? Explanation: This is a built-in function which rounds
def display(b, n): a number to give precision in decimal
while n > 0: digits. In the above case, since the number of
print(b,end="") decimal places has not been specified, the
n=n-1 decimal number is rounded off to a whole number.
display('z',3) Hence the output will be 5.
122

a) zzz 43. The function pow(x,y,z) is evaluated as:


b) zz a) (x**y)**z
Page

c) An exception is executed b) (x**y) / z


d) Infinite loop c) (x**y) % z

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


d) (x**y)*z function?
Answer: c import math
Explanation: The built-in function pow() can accept abs(math.sqrt(25))
two or three arguments. When it takes in a) Error
two arguments, they are evaluated as x**y. When it b) -5
takes in three arguments, they are c) 5
evaluated as (x**y)%z. d) 5.0
44. What will be the output of the following Python Answer: d
function? Explanation: The abs() function prints the absolute
all([2,4,0,6]) value of the argument passed. For
a) Error example: abs(-5)=5. Hence, in this case we get
b) True abs(5.0)=5.0.
c) False 48. What will be the output of the following Python
d) 0 function?
Answer: c sum(2,4,6)
Explanation: The function all returns false if any one sum([1,2,3])
of the elements of the iterable is zero a) Error, 6
and true if all the elements of the iterable are non b) 12, Error
zero. Hence the output of this function will c) 12, 6
be false. d) Error, Error
45. What will be the output of the following Python Answer: a
expression? Explanation: The first function will result in an error
round(4.5676,2)? because the function sum() is used to
a) 4.5 find the sum of iterable numbers. Hence the
b) 4.6 outcomes will be Error and 6 respectively.
c) 4.57 49. What will be the output of the following Python
d) 4.56 function?
Answer: c all(3,0,4.2)
Explanation: The function round is used to round off a) True
the given decimal number to the b) False
specified decimal places. In this case, the number c) Error
should be rounded off to two decimal d) 0
places. Hence the output will be 4.57. Answer: c
46. What will be the output of the following Python Explanation: The function all() returns ‘True’ if any
function? one or more of the elements of the
any([2>8, 4>2, 1>2]) iterable are non zero. In the above case, the values
a) Error are not iterable, hence an error is thrown.
b) True 50. What will be the output of the following Python
c) False function?
d) 4>2 min(max(False,-3,-4), 2,7)
Page 307 of 391 a) 2
Answer: b b) False
Explanation: The built-in function any() returns true c) -3
123

if any or more of the elements of the d) -4


iterable is true (non zero), If all the elements are Page 308 of 391
Page

zero, it returns false. Answer: b


47. What will be the output of the following Python Explanation: The function max() is being used to

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


find the maximum value from among -3, -4 the function is in the form of complex() or
and false. Since false amounts to the value zero, complex(0), then the output will be 0j.
hence we are left with min(0, 2, 7) Hence Page 309 of 391
the output is 0 (false). 54. The function divmod(a,b), where both ‘a’ and ‘b’
51. What will be the output of the following Python are integers is evaluated as:
functions? a) (a%b, a//b)
chr(‘97’) b) (a//b, a%b)
chr(97) c) (a//b, a*b)
a) d) (a/b, a%b)
a Answer: b
Error Explanation: The function divmod(a,b) is evaluated
b) as a//b, a%b, if both ‘a’ and ‘b’ are
‘a’ integers.
a 55. What will be the output of the following Python
c) function?
Error divmod(10.5,5)
a divmod(2.4,1.2)
d) a)
Error (2.00, 0.50)
Error (2.00, 0.00)
Answer: c b)
Explanation: The built-in function chr() returns the (2, 0.5)
alphabet corresponding to the value given (2, 0)
as an argument. This function accepts only integer c)
type values. In the first function, we have (2.0, 0.5)
passed a string. Hence the first function throws an (2.0, 0.0)
error. d)
52. What will be the output of the following Python (2, 0.5)
function? (2)
complex(1+2j) Answer: c
a) Error Explanation: See python documentation for the
b) 1 function divmod.
c) 2j 56. The function complex(‘2-3j’) is valid but the
d) 1+2j function complex(‘2 – 3j’) is invalid.
Answer: d a) True
Explanation: The built-in function complex() returns b) False
the argument in a complex form. Hence Answer: a
the output of the function shown above will be Explanation: When converting from a string, the
1+2j. string must not contain any blank spaces
53. What is the output of the function complex()? around the + or – operator. Hence the function
a) 0j complex(‘2 – 3j’) will result in an error.
b) 0+0j 57. What will be the output of the following Python
c) 0 function?
124

d) Error list(enumerate([2, 3]))


Answer: a a) Error
Page

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)]

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


d) [(2, 3)] arguments?
Answer: c a) enumerate()
Explanation: The built-in function enumerate() b) all()
accepts an iterable as an argument. The c) chr()
Page 310 of 391 d) max()
function shown in the above case returns Answer: c
containing pairs of the numbers given, starting Explanation: The functions enumerate(), all() and
from 0. Hence the output will be: [(0, 2), (1,3)]. max() accept iterables as arguments
58. What will be the output of the following Python Page 311 of 391
functions? whereas the function chr() throws an error on
x=3 receiving an iterable as an argument. Also note
eval('x^2') that the function chr() accepts only integer values.
a) Error 61. Which of the following functions accepts only
b) 1 integers as arguments?
c) 9 a) ord()
d) 6 b) min()
Answer: b c) chr()
Explanation: The function eval is use to evaluate the d) any()
expression that it takes as an argument. Answer: c
In the above case, the eval() function is used to Explanation: The function chr() accepts only
perform XOR operation between 3 and 2. integers as arguments. The function ord()
Hence the output is 1. accepts only strings. The functions min() and max()
59. What will be the output of the following Python can accept floating point as well as
functions? integer arguments.
float('1e-003') 62. Suppose there is a list such that: l=[2,3,4]. If we
float('2e+003') want to print this list in reverse order,
a) which of the following methods should be used?
3.00 a) reverse(l)
300 b) list(reverse[(l)])
b) c) reversed(l)
0.001 d) list(reversed(l))
2000.0 Answer: d
c) Explanation: The built-in function reversed() can be
0.001 used to reverse the elements of a list.
200 This function accepts only an iterable as an
d) argument. To print the output in the form of a
Error list, we use: list(reversed(l)). The output will be:
2003 [4,3,2].
Answer: b 63. What will be the output of the following Python
Explanation: The output of the first function will be function?
0.001 and that of the second function float(' -12345\n')
will be 2000.0. The first function created a floating (Note that the number of blank spaces before the
point number up to 3 decimal places and number is 5)
125

the second function adds 3 zeros after the given -12345.0 (5 blank spaces before the number) a
number. b) -12345.0 )
Page

60. Which of the following functions does not c) Error


necessarily accept only iterables as d) -12345.000000000…. (infinite decimal places)

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


Answer: b be inf.
Explanation: The function float() will remove all the 66. Which of the following functions will not result
blank spaces and convert the integer to in an error when no arguments are
a floating point number. Hence the output will be: - passed to it?
12345.0. a) min()
64. What will be the output of the following Python b) divmod()
function? c) all()
ord(65) d) float()
ord(‘A’) Answer: d
a) Explanation: The built-in functions min(), max(),
A divmod(), ord(), any(), all() etc throw an
65 error when no arguments are passed to them.
b) However there are some built-in functions like
Error float(), complex() etc which do not throw an error
65 when no arguments are passed to them.
Page 312 of 391 The output of float() is 0.0.
c) 67. What will be the output of the following Python
A function?
Error hex(15)
d) Page 313 of 391
Error a) f
Error b) 0xF
Answer: b c) 0Xf
Explanation: The built-in function ord() is used to d) 0xf
return the ASCII value of the alphabet Answer: d
passed to it as an argument. Hence the first Explanation: The function hex() is used to convert
function results in an error and the output of the the given argument into its hexadecimal
second function is 65. representation, in lower case. Hence the output of
65. What will be the output of the following Python the function hex(15) is 0xf.
function? 68. Which of the following functions does not throw
float(‘-infinity’) an error?
float(‘inf’) a) ord()
a) b) ord(‘ ‘)
–inf c) ord(”)
inf d) ord(“”)
b) Answer: b
–infinity Explanation: The function ord() accepts a character.
inf Hence ord(), ord(”) and ord(“”) throw
c) errors. However the function ord(‘ ‘) does not
Error throw an error because in this case, we are
Error actually passing a blank space as an argument. The
d) output of ord(‘ ‘) is 32 (ASCII value
Error corresponding to blank space).
126

Junk value 69. What will be the output of the following Python
Answer: a function?
Page

Explanation: The output of the first function will be len(["hello",2, 4, 6])


–inf and that of the second function will a) 4

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


b) 3 73. What will be the output of the following Python
c) Error code?
d) 6 def foo(k):
Answer: a k[0] = 1
Explanation: The function len() returns the length of q = [0]
the number of elements in the iterable. foo(q)
Therefore the output of the function shown above print(q)
is 4. a) [0]
70. What will be the output of the following Python b) [1]
function? c) [1, 0]
oct(7) d) [0, 1]
oct(‘7’) Answer: b
a) Explanation: Lists are passed by reference.
Error 74. How are keyword arguments specified in the
07 function heading?
b) a) one-star followed by a valid identifier
0o7 b) one underscore followed by a valid identifier
Error c) two stars followed by a valid identifier
c) d) two underscores followed by a valid identifier
0o7 Answer: c
Error Explanation: Refer documentation.
d) Page 315 of 391
07 75. How many keyword arguments can be passed
0o7 to a function in a single function call?
Page 314 of 391 a) zero
Answer: c b) one
Explanation: The function oct() is used to convert its c) zero or more
argument into octal form. This function d) one or more
does not accept strings. Hence the second function Answer: c
results in an error while the output of the Explanation: Zero keyword arguments may be
first function is 0o7. passed if all the arguments have default
71. What is the type of each element in sys.argv? values.
a) set 76. What will be the output of the following Python
b) list code?
c) tuple def foo(fname, val):
d) string print(fname(val))
Answer: d foo(max, [1, 2, 3])
Explanation: It is a list of strings. foo(min, [1, 2, 3])
72. What is the length of sys.argv? a) 3 1
a) number of arguments b) 1 3
b) number of arguments + 1 c) error
c) number of arguments – 1 d) none of the mentioned
d) none of the mentioned Answer: a
127

Answer: b Explanation: It is possible to pass function names as


Explanation: The first argument is the name of the arguments to other functions.
Page

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?

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


def foo(): print(foo(i))
return total + 1 a) [0] [1] [2]
total = 0 b) [0] [0, 1] [0, 1, 2]
print(foo()) c) [1] [2] [3]
a) 0 d) [1] [1, 2] [1, 2, 3]
b) 1 Answer: b
c) error Explanation: When a list is a default value, the same
d) none of the mentioned list will be reused.
Answer: b 81. What will be the output of the following Python
Explanation: It is possible to read the value of a code?
global variable directly. def foo(k):
78. What will be the output of the following Python k = [1]
code? q = [0]
def foo(): foo(q)
total += 1 print(q)
return total a) [0]
total = 0 b) [1]
print(foo()) c) [1, 0]
a) 0 d) [0, 1]
b) 1 Answer: a
c) error Explanation: A new list object is created in the
d) none of the mentioned function and the reference is lost. This can be
Page 316 of 391 checked by comparing the id of k before and after k
Answer: c = [1].
Explanation: It is not possible to change the value of Page 317 of 391
a global variable without explicitly 82. How are variable length arguments specified in
specifying it. the function heading?
79. What will be the output of the following Python a) one star followed by a valid identifier
code? b) one underscore followed by a valid identifier
def foo(x): c) two stars followed by a valid identifier
x = ['def', 'abc'] d) two underscores followed by a valid identifier
return id(x) Answer: a
q = ['abc', 'def'] Explanation: Refer documentation.
print(id(q) == foo(q)) 83. Which module in the python standard library
a) True parses options received from the command
b) False line?
c) None a) getopt
d) Error b) os
Answer: b c) getarg
Explanation: A new object is created in the d) main
function. Answer: a
80. What will be the output of the following Python Explanation: getopt parses options received from
code? the command line.
128

def foo(i, x=[]): 84. What is the type of sys.argv?


x.append(i) a) set
Page

return x b) list
for i in range(3): c) tuple

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


d) string function.
Answer: b 89. Where are the arguments received from the
Explanation: It is a list of elements. command line stored?
85. What is the value stored in sys.argv[0]? a) sys.argv
a) null b) os.argv
b) you cannot access it c) argv
c) the program’s name d) none of the mentioned
d) the first argument Answer: a
Answer: c Explanation: Refer documentation.
Explanation: Refer documentation. 90. What will be the output of the following Python
86. How are default arguments specified in the code?
function heading? def foo(i, x=[]):
a) identifier followed by an equal to sign and the x.append(x.append(i))
default value return x
b) identifier followed by the default value within for i in range(3):
backticks (“) y = foo(i)
c) identifier followed by the default value within print(y)
square brackets ([]) a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]
d) identifier b) [[0], [[0], 1], [[0], [[0], 1], 2]]
Answer: a c) [0, None, 1, None, 2, None]
Explanation: Refer documentation. d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]
87. How are required arguments specified in the Answer: c
function heading? Explanation: append() returns None.
a) identifier followed by an equal to sign and the Page 319 of 391
default value 91. What will be the output of the following Python
Page 318 of 391 code?
b) identifier followed by the default value within def f1():
backticks (“) x=15
c) identifier followed by the default value within print(x)
square brackets ([]) x=12
d) identifier f1()
Answer: d a) Error
Explanation: Refer documentation. b) 12
88. What will be the output of the following Python c) 15
code? d) 1512
def foo(x): Answer: c
x[0] = ['def'] Explanation: In the code shown above, x=15 is a
x[1] = ['abc'] local variable whereas x=12 is a global
return id(x) variable. Preference is given to local variable over
q = ['abc', 'def'] global variable. Hence the output of the
print(id(q) == foo(q)) code shown above is 15.
a) True 92. What will be the output of the following Python
b) False code?
129

c) None def f1():


d) Error x=100
Page

Answer: a print(x)
Explanation: The same object is modified in the x=+1

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


f1() x
a) Error 95. What will be the output of the following Python
b) 100 code?
c) 101 def f1(x):
d) 99 global x
Answer: b x+=1
Explanation: The variable x is a local variable. It is print(x)
first printed and then modified. Hence f1(15)
the output of this code is 100. print("hello")
93. What will be the output of the following Python a) error
code? b) hello
def san(x): c) 16
print(x+1) d)
x=-2 16
x=4 hello
san(12) Answer: a
a) 13 Explanation: The code shown above will result in an
b) 10 error because ‘x’ is a global variable.
c) 2 Had it been a local variable, the output would be:
d) 5 16
Answer: a hello
Explanation: The value passed to the function san() 96. What will be the output of the following Python
is 12. This value is incremented by one code?
and printed. Hence the output of the code shown x=12
above is 13. def f1(a,b=x):
94. What will be the output of the following Python print(a,b)
code? x=15
Page 320 of 391 f1(4)
def f1(): Page 321 of 391
global x a) Error
x+=1 b) 12 4
print(x) c) 4 12
x=12 d) 4 15
print("x") Answer: c
a) Error Explanation: At the time of leader processing, the
b) 13 value of ‘x’ is 12. It is not modified later.
c) The value passed to the function f1 is 4. Hence the
13 output of the code shown above is 4 12.
x 97. What will be the output of the following Python
d) x code?
Answer: d def f():
Explanation: In the code shown above, the variable global a
‘x’ is declared as global within the print(a)
130

function. Hence the output is ‘x’. Had the variable a = "hello"


‘x’ been a local variable, the output would print(a)
Page

have been: a = "world"


13 f()

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


print(a) r = 30
a) s = 40
hello print(p,q,r,s)
hello p,q,r,s = 1,2,3,4
world f(5,10,15)
b) a) 1 2 3 4
world b) 5 10 15 4
hello c) 10 20 30 40
hello d) 5 10 15 40
c) Answer: c
hello Explanation: The above code shows a combination
world of local and global variables. The output
world of this code is: 10 20 30 40
d) 100. What will be the output of the following
world Python code?
hello def f(x):
world print("outer")
Answer: b def f1(a):
Explanation: Since the variable ‘a’ has been print("inner")
explicitly specified as a global variable, the print(a,x)
value of a passed to the function is ‘world’. Hence f(3)
the output of this code is: f1(1)
world a)
hello outer
hello error
98. What will be the output of the following Python b)
code? inner
def f1(a,b=[]): error
b.append(a) c)
return b outer
print(f1(2,[3,4])) inner
Page 322 of 391 d) error
a) [3,2,4] Page 323 of 391
b) [2,3,4] Answer: a
c) Error Explanation: The error will be caused due to the
d) [3,4,2] statement f1(1) because the function is
Answer: d nested. If f1(1) had been called inside the function,
Explanation: In the code shown above, the integer 2 the output would have been different and
is appended to the list [3,4]. Hence the there would be no error.
output of the code is [3,4,2]. Both the variables a 101. What will be the output of the following
and b are local variables. Python code?
99. What will be the output of the following Python x=5
code? def f1():
131

def f(p, q, r): global x


global s x=4
Page

p = 10 def f2(a,b):
q = 20 global x

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


return a+b+x the function. x is a global variable because
f1() it is explicitly specified so in the code. Hence, x, y
total = f2(1,2) and z are global variables.
print(total) 104. Which of the following data structures is
a) Error returned by the functions globals() and
b) 7 locals()?
c) 8 a) list
d) 15 b) set
Answer: b c) dictionary
Explanation: In the code shown above, the variable d) tuple
‘x’ has been declared as a global variable Answer: c
under both the functions f1 and f2. The value Explanation: Both the functions, that is, globals()
returned is a+b+x = 1+2+4 = 7. and locals() return value of the data
102. What will be the output of the following structure dictionary.
Python code? 105. What will be the output of the following
x=100 Python code?
def f1(): x=1
global x def cg():
x=90 global x
def f2(): x=x+1
global x cg()
x=80 x
print(x) a) 2
a) 100 b) 1
b) 90 c) 0
c) 80 d) Error
d) Error Answer: a
Answer: a Explanation: Since ‘x’ has been declared a global
Explanation: The output of the code shown above is variable, it can be modified very easily
100. This is because the variable ‘x’ has within the function. Hence the output is 2.
been declared as global within the functions f1 and 106. On assigning a value to a variable inside a
f2. function, it automatically becomes a global
103. Read the following Python code carefully and variable.
point out the global variables? a) True
y, z = 1, 2 b) False
def f(): Answer: b
global x Explanation: On assigning a value to a variable
Page 324 of 391 inside a function, t automatically becomes a
x = y+z local variable. Hence the above statement is false.
a) x Page 325 of 391
b) y and z 107. What will be the output of the following
c) x, y and z Python code?
d) Neither x, nor y, nor z e="butter"
132

Answer: c def f(a): print(a)+e


Explanation: In the code shown above, x, y and z f("bitter")
Page

are global variables inside the function f. y a) error


and z are global because they are not assigned in b)

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


butter b)
error locals()
c) locals()
bitter c)
error globals()
d) bitterbutter locals()
Answer: c d)
Explanation: The output of the code shown above globals()
will be ‘bitter’, followed by an error. The globals()
error is because the operand ‘+’ is unsupported on Answer: c
the types used above. Explanation: The function globals() returns a
108. What happens if a local variable exists with the dictionary of the module namespace, whereas
same name as the global variable you the function locals() returns a dictionary of the
want to access? current namespace.
a) Error Page 327 of 391
b) The local variable is shadowed CHAPTER-4 – FILE HANDLING
c) Undefined behavior 1. To open a file c:\scores.txt for reading, we use
d) The global variable is shadowed _____________
Answer: d a) infile = open(“c:\scores.txt”, “r”)
Explanation: If a local variable exists with the same b) infile = open(“c:\\scores.txt”, “r”)
name as the local variable that you want c) infile = open(file = “c:\scores.txt”, “r”)
to access, then the global variable is shadowed. d) infile = open(file = “c:\\scores.txt”, “r”)
That is, preference is given to the local Answer: b
variable. Explanation: Execute help(open) to get more
109. What will be the output of the following details.
Python code? 2. To open a file c:\scores.txt for writing, we use
a=10 ____________
globals()['a']=25 a) outfile = open(“c:\scores.txt”, “w”)
print(a) b) outfile = open(“c:\\scores.txt”, “w”)
a) 10 c) outfile = open(file = “c:\scores.txt”, “w”)
b) 25 d) outfile = open(file = “c:\\scores.txt”, “w”)
c) Junk value Answer: b
d) Error Explanation: w is used to indicate that file is to be
Answer: b written to.
Explanation: In the code shown above, the value of 3. To open a file c:\scores.txt for appending data,
‘a’ can be changed by using globals() we use ____________
function. The dictionary returned is accessed using a) outfile = open(“c:\\scores.txt”, “a”)
key of the variable ‘a’ and modified to b) outfile = open(“c:\\scores.txt”, “rw”)
25. c) outfile = open(file = “c:\scores.txt”, “w”)
110. ______________ returns a dictionary of the d) outfile = open(file = “c:\\scores.txt”, “w”)
module namespace. Answer: a
________________ returns a dictionary of the Explanation: a is used to indicate that data is to be
current namespace. appended.
133

a) 4. Which of the following statements are true?


locals() a) When you open a file for reading, if the file does
Page

Page 326 of 391 not exist, an error occurs


globals() b) When you open a file for writing, if the file does

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


not exist, a new file is created d) infile.readlines()
c) When you open a file for writing, if the file exists, Answer: c
the existing file is overwritten with the Explanation: Execute in the shell to verify.
new file 9. To read the remaining lines of the file from a file
d) All of the mentioned object infile, we use ____________
Answer: d a) infile.read(2)
Explanation: The program will throw an error. b) infile.read()
5. To read two characters from a file object infile, c) infile.readline()
we use ____________ d) infile.readlines()
a) infile.read(2) Answer: d
b) infile.read() Explanation: Execute in the shell to verify.
c) infile.readline() 10. The readlines() method returns ____________
d) infile.readlines() a) str
Answer: a Page 329 of 391
Explanation: Execute in the shell to verify. b) a list of lines
Page 328 of 391 c) a list of single characters
6. To read the entire remaining contents of the file d) a list of integers
as a string from a file object infile, we use Answer: b
____________ Explanation: Every line is stored in a list and
a) infile.read(2) returned.
b) infile.read() 11. Which are the two built-in functions to read a
c) infile.readline() line of text from standard input, which by
d) infile.readlines() default comes from the keyboard?
Answer: b a) Raw_input & Input
Explanation: read function is used to read all the b) Input & Scan
lines in a file. c) Scan & Scanner
7. What will be the output of the following Python d) Scanner
code? Answer: a
1. f = None Explanation: Python provides two built-in functions
2. for i in range (5): to read a line of text from standard
3. with open("data.txt", "w") as f: input, which by default comes from the keyboard.
4. if i > 2: These functions are:
5. break raw_input and input
6. print(f.closed) 12. What will be the output of the following Python
a) True code?
b) False 1. str = raw_input("Enter your input: ");
c) None 2. print "Received input is : ", str
d) Error a)
Answer: a Enter your input: Hello Python
Explanation: The WITH statement when used with Received input is : Hello Python
open file guarantees that the file object is b)
closed when the with block exits. Enter your input: Hello Python
8. To read the next line of the file from a file object Received input is : Hello
134

infile, we use ____________ c)


a) infile.read(2) Enter your input: Hello Python
Page

b) infile.read() Received input is : Python


c) infile.readline() d) None of the mentioned

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


Answer: a 16. What is the current syntax of rename() a file?
Explanation: The raw_input([prompt]) function a) rename(current_file_name, new_file_name)
reads one line from standard input and b) rename(new_file_name, current_file_name,)
returns it as a string. This would prompt you to c) rename(()(current_file_name, new_file_name))
enter any string and it would display same d) none of the mentioned
string on the screen. When I typed “Hello Python!” Answer: a
13. What will be the output of the following Python Explanation: This is the correct syntax which has
code? shown below.
1. str = input("Enter your input: "); rename(current_file_name, new_file_name)
2. print "Received input is : ", str 17. What is the current syntax of remove() a file?
a) a) remove(file_name)
Enter your input: [x*5 for x in range(2,10,2)] b) remove(new_file_name, current_file_name,)
Received input is : [x*5 for x in range(2,10,2)] c) remove(() , file_name))
b) Page 331 of 391
Enter your input: [x*5 for x in range(2,10,2)] d) none of the mentioned
Received input is : [10, 30, 20, 40] Answer: a
Page 330 of 391 Explanation: remove(file_name)
c) 18. What will be the output of the following Python
Enter your input: [x*5 for x in range(2,10,2)] code?
Received input is : [10, 10, 30, 40] 1. fo = open("foo.txt", "rw+")
d) None of the mentioned 2. print "Name of the file: ", fo.name
Answer: a 3.
Explanation: None. 4. # Assuming file has following 5 lines
14. Which one of the following is not attributes of 5. # This is 1st line
file? 6. # This is 2nd line
a) closed 7. # This is 3rd line
b) softspace 8. # This is 4th line
c) rename 9. # This is 5th line
d) mode 10.
Answer: c 11.for index in range(5):
Explanation: rename is not the attribute of file rest 12. line = fo.next()
all are files attributes. 13. print "Line No %d - %s" % (index, line)
Attribute Description 14.
file.closed 15.# Close opened file
Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was 16.fo.close()
opened.
file.name Returns name of the file. a) Compilation Error
file.softspace Returns false if space explicitly requiredb) with
Syntax Error
print, true otherwise.
15. What is the use of tell() method in python? c) Displays Output
a) tells you the current position within the file d) None of the mentioned
b) tells you the end position within the file Answer: c
c) tells you the file is opened or not Explanation: It displays the output as shown below.
d) none of the mentioned The method next() is used when a file is
Answer: a used as an iterator, typically in a loop, the next()
135

Explanation: The tell() method tells you the current method is called repeatedly. This method
position within the file; in other words, returns the next input line, or raises StopIteration
Page

the next read or write will occur at that many bytes when EOF is hit.
from the beginning of the file. Output:

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


Name of the file: foo.txt that goes to the program. The standard input
Line No 0 - This is 1st line comes from a keyboard. Standard output is
Line No 1 - This is 2nd line where we print our data with the print keyword.
Line No 2 - This is 3rd line Unless redirected, it is the terminal console.
Line No 3 - This is 4th line The standard error is a stream where programs
Line No 4 - This is 5th line write their error messages. It is usually the
19. What is the use of seek() method in files? text terminal.
a) sets the file’s current position at the offset 22. What will be the output of the following Python
b) sets the file’s previous position at the offset code? (If entered name is sanfoundry)
c) sets the file’s current position within the file 1. import sys
Page 332 of 391 2. print 'Enter your name: ',
d) none of the mentioned 3. name = ''
Answer: a 4. while True:
Explanation: Sets the file’s current position at the 5. c = sys.stdin.read(1)
offset. The method seek() sets the file’s 6. if c == '\n':
current position at the offset. 7. break
Following is the syntax for seek() method: Page 333 of 391
fileObject.seek(offset[, whence]) 8. name = name + c
Parameters 9.
offset — This is the position of the read/write 10.print 'Your name is:', name
pointer within the file. a) sanfoundry
whence — This is optional and defaults to 0 which b) sanfoundry, sanfoundry
means absolute file positioning, other c) San
values are 1 which means seek relative to the d) None of the mentioned
current position and 2 means seek relative to Answer: a
the file’s end. Explanation: In order to work with standard I/O
20. What is the use of truncate() method in file? streams, we must import the sys module.
a) truncates the file size The read() method reads one character from the
b) deletes the content of the file standard input. In our example we get a
c) deletes the file size prompt saying “Enter your name”. We enter our
d) none of the mentioned name and press enter. The enter key
Answer: a generates the new line character: \n.
Explanation: The method truncate() truncates the Output:
file size. Following is the syntax for Enter your name: sanfoundry
truncate() method: Your name is: sanfoundry
fileObject.truncate( [ size ]) 23. What will be the output of the following Python
Parameters code?
size — If this optional argument is present, the file 1. import sys
is truncated to (at most) that size. 2. sys.stdout.write(' Hello\n')
21. Which is/are the basic I/O connections in file? 3. sys.stdout.write('Python\n')
a) Standard Input a) Compilation Error
b) Standard Output b) Runtime Error
c) Standard Errors c) Hello Python
136

d) All of the mentioned d)


Answer: d Hello
Page

Explanation: Standard input, standard output and Python


standard error. Standard input is the data Answer: d

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


Explanation: None unpickling.
Output: 27. What is the correct syntax of open() function?
Hello a) file = open(file_name [, access_mode][,
Python buffering])
24. Which of the following mode will refer to binary b) file object = open(file_name [, access_mode][,
data? buffering])
a) r c) file object = open(file_name)
b) w d) none of the mentioned
c) + Answer: b
d) b Explanation: Open() function correct syntax with
Answer:d the parameter details as shown below:
Explanation: Mode Meaning is as explained below: file object = open(file_name [, access_mode][,
r Reading buffering])
w Writing Here is parameters’ detail:
a Appending file_name: The file_name argument is a string value
b Binary data that contains the name of the file that
+ Updating. you want to access.
Page 334 of 391 access_mode: The access_mode determines the
25. What is the pickling? mode in which the file has to be opened, i.e.,
a) It is used for object serialization read, write, append, etc. A complete list of possible
b) It is used for object deserialization values is given below in the table. This is
c) None of the mentioned optional parameter and the default file access
d) All of the mentioned mode is read (r).
Answer: a buffering: If the buffering value is set to 0, no
Explanation: Pickle is the standard mechanism for buffering will take place. If the buffering
object serialization. Pickle uses a simple value is 1, line buffering will be performed while
stack-based virtual machine that records the accessing a file. If you specify the
instructions used to reconstruct the object. This buffering value as an integer greater than 1, then
makes pickle vulnerable to security risks by buffering action will be performed with the
malformed or maliciously constructed data, that indicated buffer size. If negative, the buffer size is
may cause the deserializer to import arbitrary the system default(default behavior).
modules and instantiate any object. 28. What will be the output of the following Python
26. What is unpickling? code?
a) It is used for object serialization Page 335 of 391
b) It is used for object deserialization 1. fo = open("foo.txt", "wb")
c) None of the mentioned 2. print "Name of the file: ", fo.name
d) All of the mentioned 3. fo.flush()
Answer: b 4. fo.close()
Explanation: We have been working with simple a) Compilation Error
textual data. What if we are working with b) Runtime Error
objects rather than simple text? For such situations, c) No Output
we can use the pickle module. This d) Flushes the file when closing them
module serializes Python objects. The Python Answer: d
137

objects are converted into byte streams and Explanation: The method flush() flushes the internal
written to text files. This process is called pickling. buffer. Python automatically flushes the
Page

The inverse operation, reading from a file files when closing them. But you may want to flush
and reconstructing objects is called deserializing or the data before closing any file.

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


29. Correct syntax of file.writelines() is? Answer: b
a) file.writelines(sequence) Explanation: This opens the file for writing. It will
b) fileObject.writelines() create the file if it doesn’t exist, and if it
c) fileObject.writelines(sequence) does, it will overwrite it.
d) none of the mentioned fh = open(“filename_here”, “w”).
Answer: c 33. What is the use of “a” in file handling?
Explanation: The method writelines() writes a a) Read
sequence of strings to the file. The sequence b) Write
can be any iterable object producing strings, c) Append
typically a list of strings. There is no return d) None of the mentioned
value. Answer: c
Syntax Explanation: This opens the fhe file in appending
Following is the syntax for writelines() method: mode. That means, it will be open for
fileObject.writelines( sequence ). writing and everything will be written to the end of
30. Correct syntax of file.readlines() is? the file.
a) fileObject.readlines( sizehint ); fh =open(“filename_here”, “a”).
b) fileObject.readlines(); 34. Which function is used to read all the
c) fileObject.readlines(sequence) characters?
d) none of the mentioned a) Read()
Answer: a b) Readcharacters()
Explanation: The method readlines() reads until EOF c) Readall()
using readline() and returns a list d) Readchar()
containing the lines. If the optional sizehint Answer: a
argument is present, instead of reading up to Explanation: The read function reads all characters
EOF, whole lines totalling approximately sizehint fh = open(“filename”, “r”)
bytes (possibly after rounding up to an content = fh.read().
internal buffer size) are read. 35. Which function is used to read single line from
Syntax file?
Following is the syntax for readlines() method: a) Readline()
fileObject.readlines( sizehint ); b) Readlines()
Parameters c) Readstatement()
sizehint — This is the number of bytes to be read d) Readfullline()
from the file. Answer: b
31. In file handling, what does this terms means “r, Explanation: The readline function reads a single
a”? line from the file fh = open(“filename”,
a) read, append Page 337 of 391
b) append, read “r”)
Page 336 of 391 content = fh.readline().
c) write, append 36. Which function is used to write all the
d) none of the mentioned characters?
Answer: a a) write()
Explanation: r- reading, a-appending. b) writecharacters()
32. What is the use of “w” in file handling? c) writeall()
138

a) Read d) writechar()
b) Write Answer: a
Page

c) Append Explanation: To write a fixed sequence of


d) None of the mentioned characters to a file

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


fh = open(“hello.txt”,”w”) exist, creates a new file for writing.
write(“Hello World”). “wb” Opens a file for writing only in binary format.
37. Which function is used to write a list of string in Overwrites the file if the file exists. If
a file? the file does not exist, creates a new file for writing.
a) writeline() “w+” Opens a file for both writing and reading.
b) writelines() Overwrites the existing file if the file exists.
c) writestatement() If the file does not exist, creates a new file for
d) writefullline() reading and writing.
Answer: a “wb+” Opens a file for both writing and reading in
Explanation: With the writeline function you can binary format. Overwrites the existing
write a list of strings to a file file if the file exists. If the file does not exist, creates
fh = open(“hello.txt”, “w”) a new file for reading and writing
lines_of_text = [“a line of text”, “another line of 41. Which of the following is not a valid mode to
text”, “a third line”] open a file?
fh.writelines(lines_of_text). a) ab
38. Which function is used to close a file in python? b) rw
a) Close() c) r+
b) Stop() d) w+
c) End() Answer: b
d) Closefile() Explanation: Use r+, w+ or a+ to perform both read
Answer: a and write operations using a single file
Explanation: f.close()to close it and free up any object.
system resources taken up by the open file. 42. What is the difference between r+ and w+
39. Is it possible to create a text file in python? modes?
a) Yes a) no difference
b) No b) in r+ the pointer is initially placed at the
c) Machine dependent beginning of the file and the pointer is at the end
d) All of the mentioned for w+
Answer: a c) in w+ the pointer is initially placed at the
Explanation: Yes we can create a file in python. beginning of the file and the pointer is at the end
Creation of file is as shown below. for r+
file = open(“newfile.txt”, “w”) d) depends on the operating system
file.write(“hello world in the new file\n”) Answer: b
file.write(“and another line\n”) Explanation: none.
file.close(). 43. How do you get the name of a file from a file
Page 338 of 391 object (fp)?
40. Which of the following are the modes of both a) fp.name
writing and reading in binary format in b) fp.file(name)
file? c) self.__name__(fp)
a) wb+ d) fp.__name__()
b) w Answer: a
c) wb Explanation: name is an attribute of the file object.
d) w+ Page 339 of 391
139

Answer: a 44. Which of the following is not a valid attribute of


Explanation: Here is the description below a file object (fp)?
Page

“w” Opens a file for writing only. Overwrites the file a) fp.name
if the file exists. If the file does not b) fp.closed

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


c) fp.mode b) file position is set to the end of file
d) fp.size c) file position remains unchanged
Answer: d d) error
Explanation: fp.size has not been implemented. Answer: d
45. How do you close a file object (fp)? Explanation: seek() takes at least one argument.
a) close(fp) MULTIPLE CHOICE QUESTIONS:
b) fclose(fp) 1. What is the use of “a” in file handling?
c) fp.close() a) Read
d) fp.__close__() b) Write
Answer: c c) Append
Explanation: close() is a method of the file object. d) None of the mentioned
46. How do you get the current position within the 2. How do you rename a file?
file? a) f.name = ‘new_name.txt’
a) fp.seek() b) os.rename(old_file, new_name)
b) fp.tell() c) os.set_name(old_file, new_name)
c) fp.loc 3. What is the use of seek() method in files?
d) fp.pos a) sets the file’s current position at the offset
Answer: b b) sets the file’s previous position at the offset
Explanation: It gives the current position as an c) sets the file’s current position within the file
offset from the start of file. d) none of the mentioned
47. How do you rename a file? Correct answer
a) fp.name = ‘new_name.txt’ sets the file’s current position at the offset
b) os.rename(existing_name, new_name) 4. How do you get the name of a file from a file
c) os.rename(fp, new_name) object (f)?
d) os.set_name(existing_name, new_name) a) f.name
Answer: b b) f.file(name)
Explanation: os.rename() is used to rename files. c) self.__name__(f)
48. How do you delete a file? d) f.__name__()
a) del(fp) Correct answer
b) fp.delete() Page 341 of 391
c) os.remove(‘file’) f.name
d) os.delete(‘file’) 5. What is the use of “w” in file handling?
Answer: c a) Read
Explanation: os.remove() is used to delete files. b) Write
49. How do you change the file position to an offset c) Append
value from the start? d) None of the mentioned
a) fp.seek(offset, 0) 6. What is the correct syntax to remove() a file?
Page 340 of 391 a) remove(file_name)
b) fp.seek(offset, 1) b) remove(new_file_name, current_file_name,)
c) fp.seek(offset, 2) c) remove(() , file_name))
d) none of the mentioned d) none of the mentioned
Answer: a Correct answer
Explanation: 0 indicates that the offset is with remove(file_name)
140

respect to the start. 7. To read two characters from a file object f, we


50. What happens if no arguments are passed to use ____________
Page

the seek function? a) f.read(2)


a) file position is set to the start of file b) f.read()

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


c) f.readline() b) f.read()
d) f.readlines() c) f.readline()
Correct answer d) f.readlines()
f.read(2) Correct answer
8. What is the correct syntax of rename() a file? f.readline()
a) rename(current_file_name, new_file_name) 14.What is the use of truncate() method in file?
b) rename(new_file_name, current_file_name,) a) truncates the file size
c) rename(()(current_file_name, new_file_name)) b) deletes the content of the file
d) none of the mentioned c) deletes the file size
9. Which of the following statements are true? d) none of the mentioned
a) When you open a file for reading an error occurs, Correct answer
if the file does not exist truncates the file size
b) When you open a file for writing a new file is 15.Is it possible to create a text file in Python?
created, if the file does not exist Page 343 of 391
c) When you open a file for writing, the existing file a) Yes
is overwritten with the new b) No
file, if the file exists, c) Machine dependent
d) All of the mentioned d) All of the mentioned
10.Which are the two built-in functions to read a Correct answer
line of text from standard input, which Yes
by default comes from the keyboard? 16.Which of the following are the modes of both
a) raw_input & Input writing and reading in binary format in
b) Input & Scan file?
Page 342 of 391 a) wb+
c) Scan & Scanner b) w
d) Scanner c) wb
Correct answer d) w+
raw_input & Input Correct answer
11.What will be the output of the following Python wb+
code? 17.What is the difference between r+ and w+
a) Compilation Error modes?
b) Runtime Error a) No difference
c) No Output b) In case of r+ the pointer is initially placed at the
d) Flushes the file when closing them beginning of the file and the
Correct answer pointer is at the end for w+
Flushes the file when closing them c) In case of w+ the pointer is initially placed at the
12.What happens if no arguments are passed to the beginning of the file and the
seek function? pointer is at the end for r+
a) file position is set to the start of file d) Depends on the operating system
b) file position is set to the end of file Correct answer
c) file position remains unchanged In case of r+ the pointer is initially placed at the
d) error beginning of the file and the
Correct answer pointer is at the end for w+
141

error 18.To open a file c:\text.txt for appending data, we


13.To read the next line of the file from a file object use ___________
Page

f, we use ___________ a) outfile = open(“c:\\test.txt”, “a”)


a) f.read(2) b) outfile = open(“c:\\test.txt”, “rw”)

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


c) outfile = open(file = “c:\test.txt”, “w”) d) f.size
d) outfile = open(file = “c:\\test.txt”, “w”) Correct answer
Correct answer f.size
outfile = open(“c:\\test.txt”, “a”) 25.Which one of the following is not attributes of
19.What will be the output of the following Python file?
code? a) closed
a) Compilation Error b) softspace
b) Runtime Error c) rename
Page 344 of 391 d) mode
c) 26.Which function is used to read single line from
output file?
d) a) readline()
Output b) readlines()
20.Correct syntax of file.readlines() is? c) readstatement()
a) fileObject.readlines( sizehint ); d) readfullline()
b) fileObject.readlines(); 27.Which of the following mode will refer to binary
c) fileObject.readlines(sequence) data?
d) none of the mentioned a) r
21.Command to delete a file. b) w
a) del(fp) c) +
b) fp.delete() d) b
c) os.remove(‘file’) 28.To open a file c:\text.txt for reading, we use
d) os.delete(‘file’) _____________
22.Which function is used to write all the a) f = open(“c:\test.txt”, “r”)
characters? b) f = open(“c:\\test.txt”, “r”)
a) write() c) f = open(file = “c:\test.txt”, “r”)
b) writecharacters() d) f = open(file = “c:\\test.txt”, “r”)
c) writeall() Correct answer
d) writechar() f = open(“c:\\test.txt”, “r”)
Correct answer 29.Change the file position to an offset value from
write() the starting position.
23.What is the correct syntax of open() function? a) fp.seek(offset, 0)
a) file = open(file_name [, access_mode][, b) fp.seek(offset, 1)
buffering]) c) fp.seek(offset, 2)
b) file object = open(file_name [, access_mode][, d) none of the mentioned
buffering]) Correct answer
c) file object = open(file_name) fp.seek(offset, 0)
d) none of the mentioned Page 346 of 391
Correct answer 30.What is the use of tell() method in python?
file object = open(file_name [, access_mode][, a) Inform you the current position within the file
buffering]) b) Inform you the end position within the file
24.Which of the following is not a valid attribute of c) Inform you the file is opened or not
a file object (f)? d) None of the mentioned
142

Page 345 of 391 Correct answer


a) f.name Inform you the current position within the file
Page

b) f.closed 31.How do you close a file object (fp)?


c) f.mode a) close(fp)

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


b) fclose(fp) Correct answer
c) fp.close() writeline()
d) fp.__close__() 38.Which function is used to read all the
Correct answer characters?
fp.close() a) read()
32.Correct syntax of file.writelines() is? b) readcharacters()
a) file.writelines(sequence) c) readall()
b) fileObject.writelines() d) readchar()
c) fileObject.writelines(sequence) Correct answer
d) none of the mentioned Page 348 of 391
33.What will be the output of the following Python read()
code? 39.Which of the following is not a valid mode to
a) w3resource open a file?
b) w3resource , w3resource a) ab
c) w3r b) rw
d) None of the mentioned c) r+
34.What will be the output of the following Python d) w+
code? Correct answer
Page 347 of 391 rw
a) True 40.The readlines() method returns ____________
b) False a) str
c) None b) a list of lines
d) Error c) a list of single characters
Correct answer d) a list of integers
True 41.Which function is used to close a file in Python?
35.In file handling, what does this terms means “r, a) close()
a”? b) stop()
a) read, append c) end()
b) append, read d) closefile()
c) write, append Correct answer
d) none of the mentioned close()
Correct answer 42.How do you get the current position within the
read, append file?
36.To open a file c:\text.txt for writing, we use a) f.seek()
____________ b) f.tell()
a) outfile = open(“c:\test.txt”, “w”) c) f.loc
b) outfile = open(“c:\\test.txt”, “w”) d) f.pos
c) outfile = open(file = “c:\test.txt”, “w”) Correct answer
d) outfile = open(file = “c:\\test.txt”, “w”) f.tell()
Correct answer 43.To read the remaining lines of the file from a file
outfile = open(“c:\\test.txt”, “w”) object f, we use __________
37.Which function is used to write a list of string in a) f.read(2)
a file? b) f.read()
143

a) writeline() c) f.readline()
b) writelines() d) f.readlines()
Page

c) writestatement() Correct answer


d) writefullline() f.readlines()

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


44.To read the entire remaining contents of the file b) f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
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)
use ___________ [6] Which option will be correct for reading file for
a) f.read(2) suman from q-5?
b) f.read() –> Option ) f = open(‘sum_list’,’rb’);
c) f.readline() l1=pickle.load(f)
d) f.readlines() [7] In which of the file mode existing data will be
Correct answer intact in binary file?
f.read() a) ab
Page 350 of 391 b) a
MCQs – FILE HANDLING: c) w
[1] Which of the following is not a correct d) wb
statement for binary files? [8]Which one of the following is correct statement?
a) Easy for carrying data into buffer Page 351 of 391
b) Much faster than other file systems a) import – pickle
c) Characters translation is not required b) pickle import
d) Every line ends with new line character ‘\n’ c) import pickle
[2] Which of the following file mode open a file for d) All of the above
reading and writing both in the binary Data file handling in python – MCQs
file? 1 Every file has its own identity associated with it.
a) r Which is known as –
b) rb a. icon
c) rb+ b. extension
d) rwb c. format
[3] Which of the following file mode opens a file for d. file type
reading and writing both as well as 2 Which of the following is not a known file type?
overwrite the existing file if the file exists otherwise a. .pdf
creates a new file? b. jpg
a) w c. mp3
b) wb+ d. txp
c) wb 3. In f=open(“data.txt”, “r”), r refers to __________.
d) rwb a. File handle
[4] Which of the following file mode opens a file for b. File object
append or read a binary file and moves c. File Mode
the files pointer at the end of the file if the file d Buffer
already exist otherwise create a new file? 4. EOL stands for
a) a a. End Of Line
b) ab b. End Of List
c) ab+ c. End of Lines
d) a+ d. End Of Location
[5] Ms. Suman is working on a binary file and wants 5. Which of the following file types allows to store
to write data from a list to a binary file. large data files in the computer memory?
144

Consider list object as l1, binary file suman_list.dat, a. Text Files


and file object as f. Which of the b. Binary Files
Page

following can be the correct statement for her? c. CSV Files


a) f = open(‘sum_list’,’wb’); pickle.dump(l1,f) d. None of these

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


6. Which of the following file types can be opened a. True
with notepad as well as ms excel? b. False
a. Text Files Ans. b. False
b. Binary Files Q4. Which mode create new file if the file does not
c. CSV Files exist?
d. None of these a. write mode
7. Which of the following is nor a proper file access b. append mode
mode? c. Both of the above
a. close d. None of the above
b. read Ans. c. Both of the above
c. write Q5. Which statement will return one line from a file
Page 352 of 391 (file object is ‘f’)?
d. append a. f.readline( )
8. To read 4th line from text file, which of the b. f.readlines( )
following statement is true? c. f.read( )
a. dt = f.readlines();print(dt[3]) d. f.line( )
b. dt=f.read(4) ;print(dt[3]) Ans. a. f.readline( )
c. dt=f.readline(4);print(dt[3]) Q6. readlines() method return _________
d. All of these a. String
9 Which of the following function flushes the files b. List
implicitly? c. Dictionary
a. flush() d. Tuple
b. close() Ans. b. List
c. open() Q7. EOF stands for _________________
d. fflush() a. End of File
10. Which of the following functions flushes the Page 354 of 391
data before closing the file? b. End off File
a. flush() c. End on File
b. close() d. End or File
c. open() Ans. a. End of File
d. fflush() Q8. Which function is used to read data from Text
Page 353 of 391 File?
Q1. Which statement will read 5 characters from a a. read( )
file(file object ‘f’)? b. writelines( )
a. f.read() c. pickle( )
b. f.read(5) d. dump( )
c. f.reads(5) Ans. a. read( )
d. None of the above Q9. Which of the following will read entire content
Ans. b. f.read(5) of file(file object ‘f’)?
Q2. Which function open file in python? a. f.reads( )
a. open( ) b. f.read( )
b. new( ) c. f.read(all)
c. Open( ) d. f.read( * )
145

d. None of the above Ans. b. f.read( )


Ans. a. open( ) Q10. Which symbol is used for append mode?
Page

Q3. Processing of Text file is faster than binary files. a. ap


(T/F) b. a

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


c. w d. math
d. app Ans. a. pickle
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
read the first line of a text file data.txt? which does not exist?
a. f = open(‘data.txt’); f.read() a. FileNotFoundError
b. f = open(‘data.txt’,’r’); f.read(n) b. FileFoundError
c. myfile = open(‘data.txt’); f.readline() c. FileNotExistError
d. f = open(‘data.txt’); f.readlines() d. None of the above
Ans. c. myfile = open(‘data.txt’); f.readline() Ans. d. None of the above r
Q12. File in python is treated as sequence of Q18. ______________ function returns the strings.
________________ a. read( )
a. Bytes b. readline( )
b. Bites c. Both of the above
c. bits Page 356 of 391
d. None of the above d. None of the above
Ans. a. Bytes Ans. c. Both of the above
Page 355 of 391 Q19. The syntax of seek() is: file_object.seek(offset
Q13. Which function is used to write data in binary [, reference_point])
mode? What is reference_point indicate?
a. write a. reference_point indicates the starting position
b. writelines of the file object
c. pickle b. reference_point indicates the ending position of
d. dump the file object
Ans. d. dump c. reference_point indicates the current position of
Q14. Which function is used to force transfer of the file object
data from buffer to file? d. None of the above.
a. flush( ) Ans. a. reference_point indicates the starting
b. save( ) position of the file object
c. move( ) Q20. Identify the invalid mode from the following.
d. None of the above a. a
Ans. a. flush( ) b. r+
Q15. Let the file pointer is at the end of 3rd line in a c. ar+
text file named “data.txt”. Which of the d. w
following option can be used to read all the Ans. c. ar+
remaining lines? Q21. Which of the following is an invalid mode of
a. f.read( ) file opening?
b. f.read(all) a. read only mode
c. f.readline( ) b. write only mode
d. f.readlines( ) c. read and write mode
Ans. d. f.readlines( ) d. write and append mode
Q16. ____________________ module is used for Ans. d. write and append mode
serializing and de-serializing any Python Q22. readlines( ) function returns all the words of
146

object structure. the file in the form of List. (T/F)


a. pickle a. True
Page

b. unpickle b. False
c. pandas Ans. b. False

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


Q23. What is ‘f’ in the following statement? Page 358 of 391
f=open("Data.txt" , "r") Q29. Which statement will return error?
a. File Name import pickle
b. File Handle f=open("data.dat",'rb')
c. Mode of file d=pickle.load(f)
d. File Handling f.end()
Ans. b. File Handle a. Statement 1
Q24. What is full form of CSV b. Statement 2
a. Comma Separation Value c. Statement 3
b. Comma Separated Value d. Statement 4
Page 357 of 391 Ans. d. Statement 4
c. Common Syntax Value Q30. Which of the following function takes two
d. Comma Separated Variable arguments?
Ans. b. Comma Separated Value a. load( )
Q25. Which statement will open file “data.txt” in b. dump( )
append mode? c. both of the above
a. f = open(“data.txt” , “a”) d. none of the above
b. f = Open(“data.txt” , “ab”) Ans. b. dump( )
c. f = new(“data.txt” , “a”) Q31. Almost all the files in our computer stored as
d. open(“data.txt” , “a”) _______ File.
Ans. a. f = open(“data.txt” , “a”) a. Text
Q26. Fill in the blank b. Binary
import pickle c. CSV
f=open("data.dat",'rb') d. None of the above
d=_____________________.load(f) Ans. b. Binary
f.close() Q32. Binary files are not in human readable format.
a. unpickle (T/F)
b. pickling a. True
c. pickle b. False
d. pick Ans. a. True
Ans. c. pickle Q33. .pdf and .doc are examples of __________
Q27. Which module to be imported to make the files.
following line functional? a. Text
sys.stdout.write("ABC") b. Binary
a. system c. CSV
b. sys d. None of the above
c. stdout Ans. b. Binary
d. stdin Q34. The syntax of seek() is:file_object.seek(offset [,
Ans. b. sys reference_point]) What all values can
Q28. What error is returned by the following be given as a reference point?
statement if the file does not exist? a. 1
f=open("A.txt") b. 2
a. FileNotFoundError Page 359 of 391
147

b. NotFoundError c. 0
c. FileNotFound d. All of the above
Page

d. FoundError Ans. d. All of the above


Ans. a. FileNotFoundError Q35. There is no delimiter to end a line in binary

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


files.(T/F) option for statement 4.
a. True a. f
b. False b. rec
Ans. a. True c. file
Q36. seek( ) method is used for random access to d. stud
the file.(T/F) Ans. a. f
a. True Q41. The syntax of seek() is:file_object.seek(offset [,
b. False reference_point] What is the default
Ans. a. True value of reference_point
Q37. Fill in the blanks in the following code of a. 0
writing data in binary files. Choose the b. 1
answer for statement 1 c. 2
import ___________ # Statement 1 d. 3
rec = [ ] Ans. a. 0
while True: Q42. _______ function returns the current position
rn = int(input("Enter")) of file pointer.
nm = input("Enter") a. get( )
temp = [rn, nm] b. tell( )
rec.append(temp) c. cur( )
ch = input("Enter choice (Y/N)") d. seek( )
if ch.upper == "N": Ans. b. tell( )
break Q43. f.seek(10,0) will move 10 bytes forward from
f = open("stud.dat", "____________") #statement beginning of file.(T/F)
2 a. True
__________ .dump(rec, f) #statement 3 b. False
_______.close( ) # statement 4 Ans. a. True
a. csv Q44. Which statement will move file pointer 10
b. unpickle bytes backward from current position.
c. pickle a. f.seek(-10, 0)
d. load b. f.seek(10, 0)
Ans. c. pickle c. f.seek(-10, 1)
Q38. Refer to the above code and choose the d. None of the above
option for statement2. Ans. c. f.seek(-10, 1)
a. w Page 361 of 391
b. w+ Q45. When we open file in append mode the file
c. wb pointer is at the _________ of the file.
d. write a. end
Ans. c. wb b. beginning
Page 360 of 391 c. anywhere in between the file
Q39. Refer to the above code (Q 38)and choose the d. second line of the file
option for statement 3 Ans. a. end
a. unpickle Q46. When we open file in write mode the file
b. write pointer is at the _______ of the file.
148

c. pickle a. end
d. None of the above b. beginning
Page

Ans. c. pickle c. anywhere in between the file


Q40. Refer to the above code (Q 38)and choose the d. second line of the file

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


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
f.write("Welcome to my Blog") Ans. a. file
f.close() Q52. A _____ file consists of human readable
f=open("data.txt",'r') characters.
d=f.read(5) a. Binary
print(d) # First Print Statement b. Text
f.seek(10) c. Both of the above
d=f.read(3) d. None of the above
print(d) # Second Print Statement Ans. b. Text
f.seek(13) Q53. Which of the following file require specific
d=f.read(5) programs to access its contents?
print(d) # Third Print Statement a. Binary
d=f.tell() b. Text
print(d) # Fourth Print Statement c. CSV
a. Hello d. None of the above
b. Hell Ans. a. Binary
c. ello Q54. Which of the following file can be opened in
d. None of the above any text editor?
Ans. a. Hello a. Binary
Q48. Refer to the above code (Q 47) : Write the b. Text
output of Second Print Statement c. Both of the above
a. om d. None of the above
b. me Page 363 of 391
c. co Ans. b. Text
d. None of the above Q55. Each line of a text file is terminated by a
Ans. b. me special character, called the ________
Page 362 of 391 a. End of File
Q49. Refer to the above code (Q 47) : Write the b. End of Line
output of Third Print Statement c. End of Statement
a. e to m d. End of program
b. e to my Ans. b. End of Line
c. to my Q56. Default EOL character in text file is ________
d. None of the above a. \n
Ans. c. to my b. \N
Q50. Refer to the above code (Q 47) : Write the c. \t
output of Fourth Print Statement d. \l
a. 17 Ans. a. \n
b. 16 Q57. Which of the following file can be created in
c. 19 python?
d. 18 a. Text File
149

Ans. d. 18 b. Binary File


Q51. A _____________ is a named location on a c. CSV File
Page

secondary storage media where data are d. All of the above


permanently stored for later access. Ans. d. All of the above

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


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’
c. Both of the above Q65. Write the output of the following:
d. None of the above >>> f = open("test.txt","w")
Ans. a. File >>> f.close()
Q59. open( ) function takes ____ as parameter. >>> f.closed
a. File name a. True
b. Access mode b. False
c. Both of the above Page 365 of 391
d. None of the above c. Yes
Ans. c. Both of the above d. No
Q60. Identify the correct statement to open a file: Ans. a. True
a. f = open(“D:\\myfolder\\naman.txt”) Q66. Which of the following attribute of file handle
b. f = open(“D:\myfolder\naman.txt”) returns Boolean value?
c. f = open(“D:myfolder#naman.txt”) a. name
d. f = Open(“D:\myfolder\naman.txt”) b. closed
Page 364 of 391 c. mode
Ans. a. f = open(“D:\\myfolder\\naman.txt”) d. None of the above
Q61. Which of the following are the attributes of Ans. b. closed
file handle? Q67. Ravi opened a file in python using open( )
a. closed function but forgot to specify the mode. In
b. name which mode the file will open?
c. mode a. write
d. All of the above b. append
Ans. d. All of the above c. read
Q62. Write the output of the following: d. read and write both
>>> f = open("test.txt","w") Ans. c. read
>>> f.closed Q68. Which of the following is invalid mode of
a. True opening file?
b. False a. r
c. Yes b. rb
d. No c. +r
Ans. b. False d. None of the above
Q63. Write the output of the following: Ans. d. None of the above
>>> f = open("test.txt","w") Q69. Which of the following mode will create a new
>>> f.mode file, if the file does not exist?
a. ‘w’ a. ‘a’
b. ‘r’ b. ‘a+’
c. ‘a’ c. ‘+a’
d. ‘w+’ d. All of the above
Ans. a. ‘w’ Ans. d. All of the above
150

Q64. Write the output of the following: Q70. Which of the following mode will open the file
>>> f = open("test.txt","w") in binary and read-only mode.
Page

>>> f.name a. ‘r’


a. ‘test’ b. ‘rb’

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


c. ‘r+’ already exists, all the contents will be
d. ‘rb+’ overwritten”. Help him to identify the correct
Ans. b. ‘rb’ mode.
Page 366 of 391 a. read mode
Q71. Which of the following mode will opens the b. write mode
file in read, write and binary mode? c. append mode
a. ‘wb+ d. binary and read mode
b. ‘+wb’ Ans. b. write mode
c. Both of the above Q77. Ram opened a file in a certain mode. After
d. None of the above opening the file, he forgot the mode. The
Ans. c. Both of the above interesting facts about that mode are ” If the file
Q72. In the given statement, the file myfile.txt will doesn’t exist, then a new file will be
open in _______________ mode. created” and “After opening file in that mode the
myObject=open(“myfile.txt”, “a+”) file handle will be at the end of the file”
a. append and read Help him to identify the correct mode.
b. append and write a. read mode
c. append and read and binary b. write mode
d. All of the above c. append mode
Ans. a. append and read d. binary and read mode
Q73. Ravi opened the file myfile.txt in append Ans. c. append mode
mode. In this file the file object/file handle Q78. Which of the following function is used to
will be at the __________ close the file?
a. beginning of the file a. close( )
b. end of the file b. end( )
c. second line of the file c. quit( )
d. the end of the first line d. exit( )
Ans. b. end of the file Ans. a. close( )
Q74. Ravi opened the file myfile.txt in write mode. Q79. open( ) function returns a file object called
In this file the file object/file handle will ______________
be at the ______________ a. object handle
a. beginning of the file b. file handle
b. end of the file c. read handle
c. second line of the file d. write handle
d. the end of the first line Ans. b. file handle
Ans. a. beginning of the file Q80. Which of the following is the valid way to
Q75. Ravi opened the file myfile.txt in read mode. open the file?
In this file the file object/file handle will a. with open (file_name, access_mode) as fo:
be at the _______________ b. fo = open (file_name, access_mode)
a. beginning of the file c. Both of the above
b. end of the file d. None of the above
c. second line of the file Ans. c. Both of the above
d. the end of the first line Page 368 of 391
Ans. a. beginning of the file Q81. Rohan opened the file “myfile.txt” by using
151

Page 367 of 391 the following syntax. His friend told him
Q76. Ravi opened a file in a certain mode. After few advantages of the given syntax. Help him to
Page

opening the file, he forgot the mode. One identify the correct advantage.
interesting fact about that mode is ” If the file with open ("myfile.txt", "a") as file_object:

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


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
d. None of the above c. 14
Ans. a. In case the user forgets to close the file d. 15
explicitly the file will closed Ans. c. 14
automatically. Q87. Which of the following error is returned by the
Q82. Mohan wants to open the file to add some given code:
more content in the already existing file. >>> f = open("test.txt","w")
Suggest him the suitable mode to open the file. >>> f.write(345)
a. read mode a. Syntax Error
b. append mode b. TypeError
c. write mode c. StringError
d. All of the above d. Run Time Error
Ans. b. append mode Ans. b. TypeError
Q83. Aman jotted down few features of the “write Q88. Which of the following method is used to clear
mode”. Help him to identify the valid the buffer?
features. a. clear( )
a. If we open an already existing file in write b. buffer( )
mode, the previous data will be erased c. flush( )
b. In write mode, the file object will be positioned d. clean( )
at the beginning of the file. Ans. c. flush( )
c. In write mode, if the file does not exist then the Q89. Which of the following method does not
new file will be created. return the number of characters written in the
d. All of the above file.
Ans. d. All of the above a. write( )
Q84. Ananya jotted down few features of the b. writelines( )
“append mode”. Help her to identify the valid c. Both of the above
features. d. None of the above
a. If we open an existing file in append mode, the Ans. b. writelines( )
previous data will remain there. Q90. Fill in the blank in the given code:
b. In append mode the file object will be >>> fo = open("myfile.txt",'w')
positioned at the end of the file. >>> lines = ["Hello \n", "Writing strings\n", "third
c. In append mode, if the file does not exist then line"]
the new file will be created. >>> fo._____________(lines)
d. All of the above >>>myobject.close()
Ans. d. All of the above a. write( )
Q85. Which of the following methods can be used b. writelines( )
to write data in the file? c. writeline( )
a. write( ) d. None of the above
b. writelines( ) Page 370 of 391
152

c. Both of the above Ans. b. writelines( )


d. None of the above Q91. In order to read the content from the file, we
Page

Ans. c. Both of the above can open file in ___________________


Page 369 of 391 a. “r” mode

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


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 c. FileHandling
a specified number of bytes of data from d. No Output
a data file. Ans. c. FileHandling
a. read( ) Q97. Write the output of the following:
b. read(n) f=open("test.txt","w+")
c. readlines( ) f.write("FileHandling")
d. reading(n) f.seek(0)
Ans. b. read(n) a=f.read(-1)
Q93. Write the output of the following: print(a)
f=open("test.txt","w+") a. File
f.write("File-Handling") b. Handling
a=f.read(5) c. FileHandling
print(a) d. No Output
a. Fileb. File Ans. c. FileHandling
c. File-H Q98. Which of the following method reads one
d. No Output complete line from a file?
Ans. d. No Output a. read( )
Q94. Write the output of the following: b. read(n)
f=open("test.txt","w+") c. readline( )
f.write("File-Handling") d. readlines( )
f.seek(0) Ans. c. readline( )
a=f.read(5) Page 372 of 391
print(a) Q99. Write the output of the following:
a. Fileb. File f=open("test.txt","w+")
c. File-H f.write("File\nHandling")
d. No Output f.seek(0)
Ans. a. File a=f.readline(-1)
Page 371 of 391 print(a)
Q95. Write the output of the following: a. File Handling
f=open("test.txt","w+") b. FileHandling
f.write("FileHandling") c. File
f.seek(5) d. No Output
a=f.read(5) Ans. c. File
print(a) Q100. Write the output of the following:
a. andli f=open("test.txt","w+")
b. Handl f.write("File\nHandling")
c. eHand f.seek(0)
d. No Output a=f.readline(2)
Ans. a. andli print(a)
153

Q96. Write the output of the following: a. File\nHandling


f=open("test.txt","w+") b. FileHandling
Page

f.write("FileHandling") c. Fi
f.seek(0) d. No Output

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


Ans. c. Fi b. tell( )
Q101. Select the correct statement about the code c. disp( )
given below: d. None of the above
>>> myobj=open("myfile.txt", 'r') Ans. b. tell( )
>>> print(myobj.readlines()) Q106. _______ method is used to position the file
a. This code will read one line from the file. object at a particular position in a file.
b. This code will read all the lines from the file. a. tell( )
c. This code will read only last line from the file. b. seek( )
d. None of the above c. put( )
Ans. b. This code will read all the lines from the d. None of the above
file. Ans. b. seek( )
Q102. Write the output of the following: Q107. In reference to the code given below, the file
f=open("test.txt","w+") object will move _______ bytes.
L = ["My name\n", "is\n", "Amit"] file_object.seek(10, 0)
f.writelines(L) a. 0
f.seek(0) b. 10
a=f.readlines() c. 5
print(type(a)) Page 374 of 391
a. <class ‘tuple’> d. 4
b. <class ‘list’> Ans. b. 10
c. <class ‘string’> Q108. Ravi wants to move the file object 5 bytes
Page 373 of 391 from the current position of the file object.
d. None of the above As a friend of Ravi, help him to write the code.
Ans. b. <class ‘list’> a. file_object.seek(5, 1)
Q103. Which of the following function return the b. file_object.seek(1, 5)
data of the file in the form of list? c. file_object.seek(5, 0)
a. read( ) d. file_object.seek(5, 2)
b. read(n) Ans. a. file_object.seek(5, 1)
c. readline( ) Q109. Write the output of the following code:
d. readlines( ) f=open("test.txt","w+")
Ans. d. readlines( ) f.write("My name is Amit\n")
Q104. Sanjeev has written a program which is f.seek(5,0)
showing an error. As a friend of Sanjeev, help a=f.read(5)
him to identify the wrong statement. print(a)
f=open("test.txt","w") #Statement1 a. me i
L = ["My name\n", "is\n", "Amit"] #Statement2 b. ame is
f.writeline(L) #Statement3 c. me is
f.close() #Statement4 d. Error
a. Statement1 Ans. c. me is
b. Statement2 Q111. Write the output of the following:
c. Statement3 f=open("test.txt","r")
d. Statement4 print(f.tell())
Ans. c. Statement3 a. 1
154

Q105. ____________________ function returns an b. 2


integer that specifies the current position c. -1
Page

of the file object in the file. d. 0


a. seek( ) Ans. d. 0

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


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”)
b. 650 Page 376 of 391
c. 065 Q118. Which of the following statement open the
d. 506 file “marker.txt” as a blank file?
Ans. c. 065 a. f = open(“marker.txt”, “r”)
Page 375 of 391 b. f = open(“marker.txt”, “rb”)
Q113. How many functions are used in the given c. f = open(“marker.txt”, “w”)
code? d. None of the above
fileobject=open("practice.txt","r") Ans. c. f = open(“marker.txt”, “w”)
str = fileobject.readline() Q119. Amit has written the following statement. He
while str: is working with ______
print(str) f = open("data", "rb")
str=fileobject.readline() a. Text File
fileobject.close() b. CSV File
a. 3 c. Binary File
b. 4 d. None of the above
c. 5 Ans. c. Binary File
d. 6 Q120. Which of the following option is correct?
Ans. c. 5 a. if we try to write in a text file that does not
Q114. _________ method is used to write the exist, an error occurs
objects in a binary file. b. if we try to read a text file that does not exist,
a. write( ) the file gets created.
b. dump( ) c. if we try to write on a text file that does not
c. load( ) exist, the file gets Created.
d. writer( ) d. None of the value
Ans. b. dump( ) Ans. c. if we try to write on a text file that does not
Q115. _________ method is used to read data from exist, the file gets Created.
a binary file. Q121. Correct syntax of tell( ) function is
a. write( ) _________. #f is file object
b. dump( ) a. f.tell( )
c. load( ) b. tell(f)
d. writer( ) c. f_tell( )
Ans. c. load( ) d. None of the above
Q116. Which module is to be imported for working Ans. a. f.tell( )
in binary file? Q122. The syntax of seek() is: file_object.seek(offset
a. unpickle [, reference_point]).
b. pickle ___________________ value of reference_point
c. pickling indicate end of file
155

d. unpickling a. 0
Ans. b. pickle b. 1
Page

Q117. Which of the following statement open the c. 2


file “marker.txt” so that we can read d. 3

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


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
b. Each line of a text file is terminated by a special a. isAmit
character. b. sAmit
Page 377 of 391 c. Amit
c. Text files are not in Human readable form. d. eisAmit
d. Text files can be opened in Text editor. Ans. b. sAmit
Ans. c. Text files are not in Human readable form. Q129. Which of the following method returns an
Q124. Identify the statement which can not be integer value?
interpret from the given code: a. seek( )
f = open("test.dat", "ab+") b. read( )
a. test.dat is a binary file c. tell( )
b. reading operation can be done on test.dat d. readline( )
c. appending operation can be done on test.dat Ans. c. tell( )
d. test.dat contains records about books Q130. ___________ refers to the process of
Ans. d. test.dat contains records about books converting the structure to a byte stream before
Q125. Which module is to be imported for CSV file? writing it to the file.
a. pickle a. pickling
b. unpickle b. unpickling
c. csv c. reading
d. pandas d. writing
Ans. c. csv Ans. a. pickling
Q126. Write the output of the following code : Q131. Fill in the blank in the given code :
import csv import pickle
f = open(“data.csv”, ‘r’) f = open("data.dat", "rb")
row = csv.reader(f) l = pickle._______(f)
print(row) print(l)
a. It prints the memory address where csv.reader f.close()
object is stored a. dump
b. It prints the first record of data.csv b. load
c. It prints all the records of data.csv c. write
d. None of the above d. list
Ans. a. It prints the memory address where Ans. b. load
csv.reader object is stored Q132. Write the output of the following code:
Q127. _________ function help us to read the csv f = open("data.txt","w")
file. L=["My\n","name\n","is\n","amit"]
a. reader( ) f.writelines(L)
b. read( ) f.close()
c. read(n) f = open("data.txt","r")
156

d. readline( ) print(len(f.read()))
Ans. a. reader( ) a. 13
Page

Q128. Write the output of the second print b. 14


statement of the given code: Page 379 of 391

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


c. 15 number of words in a text file named
d. 16 “data.txt”. He has written the incomplete code.
Ans. c. 15 Help 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
f.writelines(L) print("Number of words are", _________(nw)) #
f.close() Statement 4
f = open("data.txt","r") Identify the suitable code for blank space in the line
print(len(f.readlines())) marked as Statement 1
a. 4 a. “data.txt”
b. 5 b. data.txt
c. 6 c. “data”
d. 7 d. data
Ans. a. 4 Ans. b. data.txt
Q134. Write the output of the following code: Q138. Identify the suitable code for blank space in
f = open("data.txt","w") the line marked as Statement 2(Refer Q.
L=["My\n","name\n","is\n","amit"] 137)
f.writelines(L) a. readlines( )
f.close() b. readline( )
f = open("data.txt","r") c. read( )
print(len(f.readline())) d. None of the above
a. 2 Ans. c. read( )
b. 3 Q139. Identify the suitable code for blank space in
c. 4 the line marked as Statement 3(Refer Q.
d. 5 137)
Ans. b. 3 a. split( )
Q135. Fill in the blank in the given code : b. break( )
import pickle c. words( )
f = open("data.dat", "wb") d. jump( )
L = [1, 2, 3] Ans. a. split( )
pickle._______ Q140. Identify the suitable code for blank space in
f.close() the line marked as Statement 4(Refer Q.
a. dump(f, L) 137)
b. load(f, L) a. length
c. dump(L, f) b. len
d. load(L, f) c. Len
Ans. c. dump(L, f) d. Length
Page 380 of 391 Page 381 of 391
Q136. Which of the following statement will return Ans. b. len
attribute error? Q141. Ananya was writing a program of reading
a. print(len(f.readlines( ).split( ))) #f is file handle data from csv file named “data.csv”. She
b. print(len(f.readline( ).split( ))) #f is file handle writes the incomplete code. As a friend of Ananya
157

C. print(len(f.read( ).split( ))) #f is file handle help her to complete the code.
d. None of the above ________ csv #Statement1
Page

Ans. a. print(len(f.readlines( ).split( ))) f=open("data.csv", '_______') #Statement2


Q137. Ravi is writing a program for counting the d=csv.___________(f) #Statement3

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


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
d. Import Ans. b. data.csv
Ans. a. import Q146. Identify the correct statement for Statement
Q142. Identify the correct option for Statement2 2. (Refer Q. 145)
(Refer Q 141) a. CSV
a. w b. csv
b. a c. file
c. rb d. csv_
d. r Ans. b. csv
Ans. d. r Q147. Identify the correct statement for Statement
Q143. Identify the correct option for Statement3 3. (Refer Q. 145)
(Refer Q 141) a. rollno, name, class
a. readlines b. Roll no, Name, Class
b. readline c. rn, nm, cls
c. read d. field
d. reader Ans. c. rn, nm, cls
Ans. d. reader Page 383 of 391
Q144. Identify the correct option for Statement4 Q148. Chinki is writing a program to copy the data
(Refer Q 141) from “data.csv” to “temp.csv”. However
a. row she is getting some error in executing the following
b. d program due to some missing
c. csv commands. Help her to execute it successfully.
d. i import csv
Ans. a. row f=open(“data.csv”,”r”)
Page 382 of 391 f1=open(“temp.csv”,’__________’) #Statement 1
Q145. Parth is writing a program to add/insert d=csv._________(f)
records in file “data.csv”. He has written the d1=csv.writer(f1) #Statement 2
following code. As a programmer, help him to for i in d:
execute it successfully. ___________.writerow(i) #Statement3
import csv f.close( )
field = [“Roll no” , “Name” , “Class”] f1.close( )
f = open(“_________” , ‘w’) Identify the correct statement for Statement 1.
d=__________.writer(f) #Statement1 a. r
d.writerow(field) #Statement2 b. rb+
ch=’y’
c. wa
while ch==’y’ or ch==’Y’:
d. w
rn=int(input(“Enter Roll number: “))
Ans. d. w
nm = input(“Enter name: “)
158

cls = input(“Enter Class: “) Q149. Identify the correct statement for Statement
rec=[_________] #Statement3 2.(Refer Q148.)
Page

d.writerow(rec) a. read
ch=input(“Enter more record??(Y/N)”) b. reader( )

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


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)
b. d1 f.reads(5)
c. f 2.Which function open file in python?
d. f1 open()
Ans. b. d1 new()
Q151. Simran is writing a function by name 3.Processing of Text file is faster than binary files.
“bookshop” in which she is asking about book (T/F)
name and price from the user and storing the True
details in a file “book.txt”. Function is showing False
some error due to some missing words/commands. 4.Which mode create new file if the file does not
As a programmer help her to write the exist?
correct program. write mode
_________________ bookshop: #Statement 1 append mode
b_name = input("Enter book name:") both
b_price=int(input("Enter book price:")) 5.Which statement will return one line from a file
data = _________________([b_name, b_price]) (file object is 'f')?
#Statement 2 f.readline()
f = open("book.txt","w") f.readlines()
f.write(_____________) #Statement 3 f.read()f.line
Page 384 of 391 6.readlines() method return?
f.close() String
Identify the correct option for Statement 1. List
a. def Dictionary
b. Def 7.EOF stands for ?
c. define End of File
d. Define End on File
Ans. a. def 8.Which function is used to read data from Text
Q152. Identify the correct option for Statement 2. File?
a. int read( )
b. str writelines
c. char pickle
d. float dump
Ans. b. str 9.Which of the following will read entire content of
Q153. Identify the correct option for Statement 3. file(file object 'f')?
a. data f.reads()
159

b. b_name f.read()
c. b_price f.read(all)
Page

d. f 10.Which symbol is used for append mode?

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


ap 20.Identify the invalid mode from the following.
aw a
Page 386 of 391 Page 387 of 391
11.Which statement will return one line from a file r+
(file object is 'f')? ar+
f.readline() w
f.readlines() Page 388 of 391
f.read()f.line Q21. Which of the following is not the mode of file
12.File in python is treated as sequence of opening?
_______? read only mode
Bytes write only mode
Bits read and write mode
13.Which function is used to write data in binary write and append mode
mode? Q22. readlines( ) function returns all the lines of file
write in the form of List. (T/F)
writelines True
Pickle False
dump Q23. What is 'f' in the following statement?
14.Which function is used to force transfer of data f=open("Data.txt" , "r")
from buffer to file? File Name
flush() File Handle
save() Mode of file
15.Which function open file in python? File Handling
open() Q24. What is full form of CSV
new() Comma Separation Value
16.readlines() method return? Comma Separated Value
String Common Syntax Value
List Q25. Which statement will open file "data.txt" in
Dictionary append mode?
17.Which of the following error is returned when f = open("data.txt" , "a")
we try to open a file in read mode which f = open("data.txt" , "ab")
does not exist? f = new("data.txt" , "a")
FileNotFoundError open("data.txt" , "a")
FileFoundError Q26. Fill in the blank
FileNotExistError f=[ ]
18._______ function returns the list of strings. f = ______.load(fileobj)
read() unpickle
readline() pickling
readlines() pickle
19.Which function is used to open file? pick
160

new() Q27. Which module to be imported to make the


create() following line functional?
Page

open() sys.stdout.write("ABC")

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


system pickle
sys csv
stdout Page 390 of 391
stdin Q35. There is no delimiter to end a line in binary
Page 389 of 391 files.(T/F)
Q28. What error is returned by the following False
statement if the file does not exist? True
f=open("A.txt") Q36. seek( ) method is used for random access to
FileNotFoundError the file.(T/F)
NotFoundError True
FileNotFound False
FoundError Q37. Fill in the blanks in the following code of
Q29. Which statement will return error? writing data in binary files. Choose the
import pickle answer for statement 1
f=open("data.dat",'rb') import ___________ # Statement 1
d=pickle.load(f) rec = [ ]
f.end() while True:
Statement 1 rn = int(input("Enter"))
Statement 2 nm = input("Enter")
Statement 3 temp = [rn, nm]
Statement 4 rec.append(temp)
Q30. Which of the following function takes two ch = input("Enter choice (Y/N)")
arguments? if ch.upper == "N":
load( ) break
dump( ) f = open("stud.dat", "____________") #statement 2
Q31. Almost all the files in our computer stored as __________ .dump(rec, f) #statement 3
_______ File. _______.close( ) # statement 4
Text csv
Binary unpickle
CSV pickle
None of the above load
Q32. Binary files are not in human readable format. Q38. Refer to the above code and choose the
(T/F) option for statement 2
True w
False w+
Q33. .pdf and .doc are examples of _______ files. wb
Text Page 391 of 391
Binary write
CSV Q39. Refer to the above code and choose the
Q34. Which module to be imported for working option for statement 3
161

with binary files. unpickle


load write
Page

dump pickle

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


Q40. Refer to the above code and choose the
option for statement 4.
f
rec
filestud

162
Page

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

You might also like