GE8151 Problem Solving and Python Programming MCQ
GE8151 Problem Solving and Python Programming MCQ
PYTHON Answer: a
Explanation: The statement is true. This
PROGRAMMING
M
word algorithm refers to a special method
usable by a computer for the solution to a
problem. The statement of the problem
O
SEMESTER - I specifies in general terms the desired
input/output relationship.
C
3. This characteristic often draws the line
T.
MCQ - Regulations between what is feasible and what is
impossible.
2017
O
a) Performance
b) System Evaluation
b) Evaluation
1. The word ____________comes from the c) Running
name of a Persian mathematician Abu Ja’far d) Input
-R
b) Flow
the input: an already sorted sequence is easier
c) Algorithm
to sort. The running time is given by the size
d) Syntax
of the input, since short sequences are easier
C
c) as programs b) Lists
d) as flowcharts c) Horizontal array
d) Vertical array
Answer: b
Explanation: Representation of algorithms: Answer: a
-As programs Explanation: Linear arrays are the 1-
-As flowcharts Dimensional arrays wherein only one row is
-As pseudo codes. present and the items are inserted.
M
6. When an algorithm is written in the form of 10. A data structure that follows the FIFO
a programming language, it becomes a principle.
O
_________ a) Queue
a) Flowchart b) LL
C
b) Program c) Stack
c) Pseudo code d) Union
T.
d) Syntax
Answer: a
Answer: b Explanation: The answer is Queue. A Queue
O
Explanation: An algorithm becomes a follows the FIFO principle. FIFO stands for
program when it is written in the form of a First In First Out.
programming language. Thus, any program is
an algorithm.
SP
TOPIC 1.2 FLOW CHARTS
G
7. Any algorithm is a program.
a) True 1. The symbol denotes _______
LO
b) False
Answer: b
a) I/O
Explanation: The statement is false. An
.B
b) Flow
algorithm is represented in the form of a
c) Terminal
programming language is called a program.
d) Decision
17
Answer: b
Explanation: In a queue, the items are Answer: b
inserted from the rear end and deleted from Explanation: The statement is false. The
the front end. correct statement would be: In computer
science, flowchart refers to a pictorial
9. Another name for 1-D arrays.
representation of an algorithm.
a) Linear arrays
M
flowchart is nothing but a pictorial a) True
representation of an algorithm. b) False
O
4. Actual instructions in flowcharting are Answer: b
C
represented in __________ Explanation: The statement is false. There
a) Circles should be no set standards on the amount of
T.
b) Boxes details that should be provided in a flowchart.
c) Arrows
d) Lines 8. A detailed flowchart is called ______
O
a) Stack
Answer: b b) Macro
Explanation: The actual instructions are
written in boxes. Boxes are connected by
using arrows to indicate the exact flow of a
SP
c) Micro
d) Union
G
flowchart and the order in which they are to Answer: c
be executed. Explanation: A detailed flowchart or a
LO
a) Better communication
b) Initiation b) Efficient coding
c) Initialization c) Systematic testing
d) I/O d) Improper documentation
-R
Answer: a Answer: d
Explanation: A diamond shape box denotes
SE
6. A box that can represent two different 10. A flowchart that outlines the main
conditions. segments of a program.
a) Rectangle a) Queue
b) Diamond b) Macro
c) Circle c) Micro
d) Parallelogram d) Union
Answer: b a) Process
Explanation: The answer is Macro b) Sequence
Flowchart. A macro flowchart outlines the c) Repetition
important components of a program. It d) Case
therefore shows fewer details.
Answer: a
Explanation: There are basically four
TOPIC 1.3 DESIGNING flowcharting structures:
FLOWCHARTS • Decision
M
• Repetition
1. A ______________ is diagram that depicts • Case
O
the flow of a program. • Sequence.
a) Algorithm
C
b) Hash Table 5. The action performed by a ___________
c) Graph structure must eventually cause the loop to
T.
d) Flowchart terminate.
a) sequence
b) case
O
Answer: d
Explanation: A flowchart is a diagram that c) repetition
d) process
helps us determine the flow of the program.
Other options are irrelevant.
b) False is created.
parallelograms.
a) Input/Output
b) Assignment Answer: a
SE
7. What type of structure is this? shapes. They also show the flow of the
program.
a) sequence
M
b) case a) Decision
c) repetition b) Input/Output
c) Process
O
d) process
d) Module
C
Answer: c
Explanation: This is a repetition structure. Answer: a
Explanation: The answer is decision.
T.
The action performed by a repetition structure
must eventually cause the loop to terminate. Conditions are given in this box and then the
Otherwise, an infinite loop is created. result is checked accordingly if the condition
O
is true or false.
8. What type of a structure is this?
SP
TOPIC 1.4 PSEUDO CODE
a) Dependent
b) Independent
a) sequence c) Case sensitive
.B
b) case d) Capitalized
c) repetition
d) process Answer: b
17
b) arrow Answer: a
c) Process Explanation: The statement is true. It is an
d) box important rule to capitalize the initial
keyword while writing a pseudo code.
Answer: b
Explanation: Arrows are the connectors that 3. Which of the following is not a keyword?
show the relationship between different a) Read
M
4. ______________ is used to show hierarchy c) Tokens
in a pseudo code. d) Functions
O
a) Indentation
b) Curly Braces Answer: b
C
c) Round Brackets Explanation: Variables begin with a
d) Semicolon lowercase. They contain no spaces. They also
T.
involve the consistent use of names.
Answer: a
Explanation: Each design structure uses a 8. Another notation for exponentiation.
O
particular indentation pattern. a) *
Indentation should be considered in the b) **
following cases:
Sequence
Selection
SP
c) ***
d) *^
G
Loop. Answer: b
Explanation: Double asterisk sign is also
LO
5. The statement that tells the computer to get used for exponentiation. The general notation
a value from an input device and store it in a is ^ sign.
memory location.
a) read 9. A symbol used for grouping.
.B
b) write a) ()
c) READ b) {}
17
d) WRITE c) [].
d) ” ”
Answer: c
Explanation: The READ statement is used to Answer: a
-R
take the input. READ being a keyword should Explanation: Parenthesis is used for
be in capital letters. grouping while working with fields. There are
SE
Answer: b
Explanation: Variable names should not start
UNIT II DATA, with a number.
EXPRESSIONS, 5. Why are local variable names beginning
M
STATEMENTS with an underscore discouraged?
a) they are used to indicate a private variables
O
of a class
TOPIC 2.1 VARIABLES b) they confuse the interpreter
C
c) they are used to indicate global variables
1. Is Python case sensitive when dealing with d) they slow down execution
T.
identifiers?
a) yes Answer: a
Explanation: As Python has no concept of
O
b) no
c) machine dependent private variables, leading underscores are
used to indicate variables that must not be
d) none of the mentioned
Answer: a
SP
accessed from outside the class.
identifier? c) nonlocal
a) 31 characters d) pass
b) 63 characters
Answer: a
.B
c) 79 characters
d) none of the mentioned Explanation: eval can be used as a variable.
17
c) __str__ = 1
d) none of the mentioned Explanation: True, False and None are
capitalized while the others are in lower case.
Answer: d
C
Explanation: All the statements will execute 8. Which of the following is true for variable
successfully but at the cost of reduced names in Python?
readability. a) unlimited length
b) all private members must have leading and
4. Which of the following is an invalid trailing underscores
variable? c) underscore and ampersand are the only two
a) my_string_1
M
a) abc = 1,000,000
b) a b c = 1000 2000 3000 3. What is the order of precedence in python?
O
c) a,b,c = 1000, 2000, 3000 i) Parentheses
d) a_b_c = 1,000,000 ii) Exponential
C
iii) Multiplication
Answer: b iv) Division
T.
Explanation: Spaces are not allowed in v) Addition
variable names. vi) Subtraction
O
a) i,ii,iii,iv,v,vi
10. Which of the following cannot be a b) ii,i,iii,iv,v,vi
variable?
a) __init__
b) in
c) it
SP c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
Answer: a
G
d) on Explanation: For order of precedence, just
remember this PEMDAS (similar to
LO
Answer: b BODMAS).
Explanation: in is a keyword.
4. What is the answer to this expression, 22 %
.B
b) X**y Answer: b
c) X^^y Explanation: Modulus operator gives the
d) None of the mentioned remainder. So, 22%3 gives the remainder, that
SE
is, 1.
Answer: b
Explanation: In python, power operator is 5. Mathematical operations can be performed
x**y i.e. 2**3=8. on a string.
C
a) True
2. Which one of these is floor division? b) False
a) /
b) // Answer: b
c) % Explanation: You can’t perform
d) None of the mentioned mathematical operation on string even if the
string is in the form: ‘1234…’.
6. Operators with the same precedence are 10. Which one of the following has the
evaluated in which manner? highest precedence in the expression?
a) Left to Right a) Exponential
b) Right to Left b) Addition
c) Can’t say c) Multiplication
d) None of the mentioned d) Parentheses
Answer: a Answer: d
Explanation: None. Explanation: Just remember: PEMDAS, that
M
is, Parenthesis, Exponentiation, Division,
7. What is the output of this expression, Multiplication, Addition, Subtraction. Note
O
3*1**3? that the precedence order of Division and
a) 27 Multiplication is the same. Likewise, the
C
b) 9 order of Addition and Subtraction is also the
c) 3 same.
T.
d) 1
O
Explanation: First this expression will solve
1**3 because exponential has higher 1. Which of these in not a core data type?
precedence than multiplication, so 1**3 = 1
and 3*1 = 3. Final answer is 3.
SP
a) Lists
b) Dictionary
c) Tuples
G
8. Which one of the following has the same d) Class
precedence level?
LO
d) Addition and Multiplication 2. Given a function that does not return any
value, What value is thrown by default when
17
c) void
precedence level. However, Multiplication d) None
and Division operators are at a higher
SE
M
c) ValueError
4. Which of the following will run without d) TypeError
O
errors?
a) round(45.8) Answer: b
C
b) round(6352.898,2,5) Explanation: Mango is not defined hence
c) round() name error.
T.
d) round(7463.123,2,1)
8. What will be the output of the following
Answer: a Python code snippet?
O
Explanation: Execute help(round) in the
1. def example(a):
shell to get details of the parameters that are
passed into the round function.
a = a*2
G
a) int
b) float 4. return a
LO
c) bool
5. >>>example("hello")
d) dict
a) indentation Error
Answer: a
.B
M
Answer: d
Explanation: Dictionary stores values in 2. >>>grade2 = 90
O
terms of keys and values.
3. >>>average = (grade1 + grade2) / 2
C
11. Which of the following results in a
a) 85.0
SyntaxError?
b) 85.1
T.
a) ‘”Once upon a time…”, she said.’
c) 95.0
b) “He said, ‘Yes!'”
d) 95.1
c) ‘3\’
O
d) ”’That’s okay”’ Answer: a
Answer: c
Explanation: Carefully look at the colons. SP
Explanation: Cause a decimal value of 0 to
appear as output.
2. dick
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ +
3. harry ‘you’)
17
a) Answer: c
Explanation: Execute in the shell.
-R
print('''tom
15. What is the return value of trunc()?
\ndick a) int
b) bool
SE
\nharry''')
c) float
b) print(”’tomdickharry”’) d) None
c) print(‘tom\ndick\nharry’)
C
Answer: a
d)
Explanation: Execute help(math.trunc) to get
print('tom details.
dick
TOPIC 2.4 NUMERIC TYPES
harry') (INT, FLOAT)
M
be represented accurately in binary. The c) x = 19023
round off errors from 0.1 and 0.2 accumulate d) x = 03964
O
and hence there is a difference of 5.5511e-17
between (0.1 + 0.2) and 0.3. Answer: d
C
Explanation: Numbers starting with a 0 are
2. Which of the following is not a complex octal numbers but 9 isn’t allowed in octal
T.
number? numbers.
a) k = 2 + 3j
b) k = complex(2, 3) 7. What is the result of cmp(3, 1)?
O
c) k = 2 + 3l a) 1
d) k = 2 + 3J b) 0
Answer: c
Explanation: l (or L) stands for long.
SP
c) True
d) False
G
Answer: a
3. What is the type of inf? Explanation: cmp(x, y) returns 1 if x > y, 0 if
LO
b) float(‘nan’)
Answer: c c) float(’56’+’78’)
17
b) -4
c) -3 round(-0.5)?
d) +3 a) 1.0
b) 2.0
C
Answer: a c) 0.0
Explanation: ~x is equivalent to -(x+1). d) Value depends on Python version
M
Python 2.7.17 (default, Nov 7 2019, 10:0
7:09) c) 0.75
d) 7
O
>>> round(0.5)
Answer: d
C
1.0 Explanation: ^ is the Binary XOR operator.
T.
>>> round(-0.5)
-1.0
TOPIC 2.5 PRECEDENCE OF
OPERATORS
O
>>>
0
2. What will be the value of the following
>>> round(-0.5) Python expression?
-R
0 4 + 3 % 5
>>> round(2.5)
a) 4
SE
2 b) 7
c) 2
>>> round(3.5) d) 0
C
4
Answer: b
>>> Explanation: The order of precedence is: %,
+. Hence the expression above, on
simplification results in 4 + 3 = 7. Hence the
In the above output, you can see that the result is 7.
round() functions on 0.5 and -0.5 are moving
M
decimal place.
Answer: b
O
Explanation: The above expression is 7. Which of the following is the truncation
evaluated as: 16%15//16, which is equal to division operator?
C
1//16, which results in 0. a) /
b) %
T.
4. Which of the following operators has its c) //
associativity from right to left? d) |
a) +
O
b) // Answer: c
c) % Explanation: // is the operator for truncation
d) **
Answer: d
SP
division. It is called so because it returns only
the integer part of the quotient, truncating the
decimal part. For example: 20//3 = 6.
G
Explanation: All of the operators shown
above have associativity from left to right, 8. What are the values of the following
LO
b) 64, 64, 64
a) 43 c) 512, 512, 512
b) 44 d) 512, 64, 512
-R
c) 22
d) 23 Answer: d
Explanation: Expression 1 is evaluated as:
SE
Hence the result of this expression is 44. operator is from right to left. Hence the result
of the third expression is 512.
6. What is the value of the following
expression? 9. What is the value of the following
expression?
2+4.00, 2**4.0
8/4/2, 8/(4/2)
M
a) 4.7 – 1.5
10. What is the value of the following b) 7.9 * 6.3
O
expression? c) 1.7 % 2
d) 3.4 + 4.6
C
float(22//3+3/3)
Answer: c
T.
a) 8 Explanation: Coercion is the implicit
b) 8.0 (automatic) conversion of operands to a
c) 8.3 common type. Coercion is automatically
O
d) 8.33 performed on mixed-type expressions. The
expression 1.7 % 2 is evaluated as 1.7 % 2.0
Answer: b
Explanation: The expression shown above is
evaluated as: float( 7+1) = float(8) = 8.0.
SP
(that is, automatic conversion of int to float).
c) (1,0)
a) Error
d) (3,1)
b) 1.0
17
c) 1.00 Answer: a
d) 1 Explanation: The expressions are evaluated
as: 4%3 and 6//2 respectively. This results in
-R
Answer: b
the answer (1,3). This is because the
Explanation: The result of the expression
associativity of both of the expressions shown
shown above is 1.0 because print rounds off
above is left to right.
SE
digits.
5. Which among the following list of
2. What will be the value of X in the
operators has the highest precedence?
following Python expression?
C
M
a) 5.0
b) 5 Answer: b
O
c) 4.0 Explanation: The order of precedence is: **,
d) 4 //, +. The expression 4+2**5//10 is evaluated
C
as 4+32//10, which is equal to 4+3 = 7. Hence
Answer: c the result of the expression shown above is 7.
T.
Explanation: The above expression is an
example of explicit conversion. It is evaluated 10. The expression 2**2**3 is evaluates as:
as: float(4+int(2.39)%2) = float(4+2%2) = (2**2)**3.
O
float(4+0) = 4.0. Hence the result of this a) True
expression is 4.0. b) False
a) float(‘10’) a) 8
b) int(‘10’) b) 1
c) float(’10.8’) c) 2
d) 4
C
d) int(’10.8’)
Answer: d Answer: d
Explanation: All of the above examples Explanation: The binary form of 1 is 0001.
show explicit conversion. However the The expression x<<2 implies we are
expression int(’10.8’) results in an error. performing bitwise left shift on x. This shift
yields the value: 0100, which is the binary
form of the number 4.
2. What will be the output of the following 5. To find the decimal value of 1111, that is
Python expression? 15, we can use the function:
a) int(1111,10)
bin(29) b) int(‘1111’,10)
c) int(1111,2)
a) ‘0b10111’ d) int(‘1111’,2)
b) ‘0b11101’
c) ‘0b11111’ Answer: d
d) ‘0b11011’ Explanation: The expression int(‘1111’,2)
M
gives the result 15. The expression int(‘1111’,
Answer: b 10) will give the result 1111.
O
Explanation: The binary form of the number
29 is 11101. Hence the output of this 6. What will be the output of the following
C
expression is ‘0b11101’. Python expression if x=15 and y=12?
T.
3. What will be the value of x in the x & y
following Python expression, if the result of
that expression is 2? a) b1101
O
b) 0b1101
x>>2 c) 12
a) 8
b) 4
SP
d) 1101
Answer: c
c) 2
G
Explanation: The symbol ‘&’ represents
d) 1 bitwise AND. This gives 1 if both the bits are
LO
int(1011)?
d) int(‘1011’)
a) 1011
Answer: c
SE
b) 11
c) 13 Explanation: The expression int(1011,2)
d) 1101 results in an error. Had we written this
expression as int(‘1011’,2), then there would
C
M
a) ‘0bx1000’ Answer: a
O
b) 8 Explanation: The one’s complement of a
c) 1000 value is obtained by simply changing all the
C
d) ‘0b1000’ 1’s to 0’s and all the 0’s to 1’s. Hence the
one’s complement of 110010101 is
T.
Answer: d 001101010.
Explanation: The prefix 0x specifies that the
value is hexadecimal in nature. When we 3. Bitwise _________ gives 1 if either of the
O
convert this hexadecimal value to binary bits is 1 and 0 when both of the bits are 1.
form, we get the result as: ‘0b1000’. a) OR
10. What will be the output of the following
Python expression?
SP
b) AND
c) XOR
d) NOT
G
0x35 | 0x75
Answer: c
LO
d) 118
4. What will be the output of the following
Answer: c Python expression?
17
a) 10 a=a^b
b) 2 print(a,b)
c) 1
d) 0 a) 10 20
b) 10 10
Answer: c c) 20 10
Explanation: Any odd number on being d) 20 20
AND-ed with 1 always gives 1. Any even
number on being AND-ed with this value Answer: c
M
always gives 0. Explanation: The code shown above is used
to swap the contents of two memory locations
O
6. What will be the value of the following using bitwise X0R operator. Hence the output
Python expression? of the code shown above is: 20 10.
C
bin(10-2)+bin(12^4) 9. What is the two’s complement of -44?
T.
a) 1011011
a) 0b10000 b) 11010100
b) 0b10001000 c) 11101011
O
c) 0b1000b1000 d) 10110011
d) 0b10000b1000
Answer: d
Explanation: The output of bin(10-2) =
SP
Answer: b
Explanation: The binary form of -44 is
00101100. The one’s complement of this
G
0b1000 and that of bin(12^4) is ob1000. value is 11010011. On adding one to this we
Hence the output of the above expression is: get: 11010100 (two’s complement).
LO
0b10000b1000.
10. What will be the output of the following
7. Which of the following expressions can be Python expression?
used to multiply a given number ‘a’ by 4?
.B
a) a<<2 ~100?
b) a<<4
a) 101
c) a>>2
17
b) -101
d) a>>4
c) 100
Answer: a d) -100
-R
8. What will be the output of the following Sanfoundry Global Education & Learning
Series – Python.
Python code if a=10 and b =20?
a=10 TOPIC 2.7 BOOLEAN
b=20
a=a^b
b=a^b
M
True
not(3>4)
O
b) not(1&1)
a)
C
False
T.
True True
c) True
O
False b)
d)
False
SP True
False
G
True c)
LO
False False
Answer: d True
Explanation: The Boolean function returns
.B
function bool. Hence the output is false. Explanation: The function not returns true if
the argument amounts to false, and false if the
argument amounts to true. Hence the first
SE
['hello', 'morning'][bool('')]
4. What will be the output of the following
a) error Python code?
b) no output
c) hello ['f', 't'][bool('spam')]
d) morning
a) t {}
b) f
[]
c) No output
d) Error d)
Answer: a {}
Explanation: The line of code can be
translated to state that ‘f’ is printed if the {}
argument passed to the Boolean function
M
amount to zero. Else ‘t’ is printed. The Answer: c
argument given to the Boolean function in the Explanation: The code shown above shows
O
above case is ‘spam’, which does not amount two functions. In both the cases the right
to zero. Hence the output is t. operand is returned. This is because each
C
function is evaluated from left to right. Since
5. What will be the output of the following the left operand is false, it is assumed that the
T.
Python code? right operand must be true and hence the right
operand is returned in each of the above case.
l=[1, 0, 2, 0, 'hello', '', []]
O
list(filter(bool, l))
a) Error
b) [1, 0, 2, 0, ‘hello’, ”, []]
c) [1, 0, 2, ‘hello’, ”, []]
SP
7. What will be the output of the following
Python code?
G
d) [1, 2, ‘hello’] class Truth:
pass
x=Truth()
LO
Answer: d
bool(x)
Explanation: The code shown above returns
a new list containing only those elements of a) pass
the list l which do not amount to zero. Hence b) true
.B
[] or {}
{} or [] the output of the code shown above is true.
a)
Python code?
[]
if (9 < 0) and (0 < -9):
C
{} print("hello")
elif (9 > 0) or False:
b) print("good")
else:
[] print("bad")
[] a) error
b) hello
c)
c) good
d) bad
M
9. Which of the following Boolean
1. What will be the output of the following
O
expressions is not logically equivalent to the
Python code?
other three?
C
a) not(-6<0 or-6>10) x = ['ab', 'cd']
b) -6>=0 and -6<=10 for i in x:
T.
c) not(-6<10 or-6==10) i.upper()
d) not(-6>10 or-6==10) print(x)
O
Answer: d a) [‘ab’, ‘cd’]
Explanation: The expression not(-6<0 or b) [‘AB’, ‘CD’]
-6>10) returns the output False.
The expression -6>=0 and -6<=10 returns the
output False.
SP
c) [None, None]
d) none of the mentioned
G
The expression not(-6<10 or -6==10) returns Answer: a
the output False. Explanation: The function upper() does not
LO
The expression not(-6>10 or -6==10) returns modify a string in place, it returns a new
the output True. string which isn’t being stored anywhere.
10. What will be the output of the following 2. What will be the output of the following
.B
x = ['ab', 'cd']
17
returns true. The and operation between false Explanation: The loop does not terminate as
and true returns false. Hence the output is new elements are being added to the list in
false. each iteration.
Sanfoundry Global Education & Learning 3. What will be the output of the following
Series – Python. Python code?
i = 1 Answer: b
while True: Explanation: 0O11 is an octal number.
if i%3 == 0:
break
print(i) 6. What will be the output of the following
Python code?
i + = 1
i = 5
a) 1 2 while True:
if i%0O9 == 0:
b) 1 2 3
M
break
c) error print(i)
d) none of the mentioned i += 1
O
Answer: c a) 5 6 7 8
C
Explanation: SyntaxError, there shouldn’t be b) 5 6 7 8 9
a space between + and = in +=. c) 5 6 7 8 9 10 11 12 13 14 15 ….
T.
d) error
4. What will be the output of the following
Python code? Answer: d
O
Explanation: 9 isn’t allowed in an octal
i = 1 number.
while True:
if i%0O7 == 0:
break
print(i)
SP
7. What will be the output of the following
Python code?
G
i += 1
i = 1
LO
a) 1 2 3 4 5 6 while True:
if i%2 == 0:
b) 1 2 3 4 5 6 7
break
c) error print(i)
d) none of the mentioned i += 2
.B
Answer: a a) 1
Explanation: Control exits the loop when i
17
b) 1 2
becomes 7. c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
5. What will be the output of the following
-R
while True:
if i%0O11 == 0:
break 8. What will be the output of the following
print(i) Python code?
C
i += 1
i = 2
a) 5 6 7 8 9 10 while True:
if i%3 == 0:
b) 5 6 7 8 break
c) 5 6 print(i)
d) error i += 2
a) 2 4 6 8 10 … i = 0
b) 2 4 while i < 5:
print(i)
c) 2 3 i += 1
d) error if i == 3:
break
Answer: b else:
Explanation: The numbers 2 and 4 are print(0)
printed. The next value of i is 6 which is
divisible by 3 and hence control exits the a) 0 1 2 0
M
loop. b) 0 1 2
c) error
O
9. What will be the output of the following d) none of the mentioned
Python code?
C
Answer: b
i = 1 Explanation: The else part is not executed if
T.
while False: control breaks out of the loop.
if i%2 == 0:
break 2. What will be the output of the following
O
print(i)
i += 2
Python code?
a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
SP
i = 0
while i < 3:
print(i)
i += 1
G
d) none of the mentioned else:
print(0)
LO
Answer: d
Explanation: Control does not enter the loop a) 0 1 2 3 0
because of False. b) 0 1 2 0
c) 0 1 2
.B
b) False x = "abcdef"
c) None while i in x:
d) none of the mentioned print(i, end=" ")
C
Answer: d a) a b c d e f
Explanation: SyntaxError, True is a keyword b) abcdef
and it’s value cannot be changed. c) i i i i i i …
d) error
1. What will be the output of the following
Python code? Answer: d
Explanation: NameError, i is not defined.
4. What will be the output of the following evaluate to True. But also here we use a
Python code? citation marks on “i”, so, here i treated as a
string, not like a variable.
x = "abcdef"
i = "i" 7. What will be the output of the following
while i in x:
print(i, end=" ")
Python code?
x = "abcdef"
a) no output i = "a"
M
b) i i i i i i … while i in x:
c) a b c d e f x = x[:-1]
d) abcdef print(i, end = " ")
O
Answer: a a) i i i i i i
C
Explanation: “i” is not in “abcdef”. b) a a a a a a
c) a a a a a
T.
5. What will be the output of the following d) none of the mentioned
Python code?
Answer: b
O
x = "abcdef" Explanation: The string x is being shortened
i = "a" by one character in each iteration.
while i in x:
print(i, end = " ") SP
8. What will be the output of the following
Python code?
a) no output
G
b) i i i i i i … x = "abcdef"
c) a a a a a a …
LO
i = "a"
d) a b c d e f while i in x[:-1]:
print(i, end = " ")
Answer: c
.B
d) a
6. What will be the output of the following
Python code? Answer: c
-R
b) i i i i i i … i = "a"
c) a a a a a a … while i in x:
d) a b c d e f x = x[1:]
print(i, end = " ")
Answer: b
Explanation: Here i i i i i … printed a) a a a a a a
continuously because as the value of i or x b) a
isn’t changing, the condition will always
c) no output c) a B C D
d) error d) error
Answer: b Answer: b
Explanation: The string x is being shortened Explanation: The instance of the string
by one character in each iteration. returned by upper() is being printed.
10. What will be the output of the following 3. What will be the output of the following
Python code? Python code?
M
x = "abcdef" x = 'abcd'
O
i = "a" for i in range(x):
while i in x[1:]: print(i)
print(i, end = " ")
C
a) a b c d
a) a a a a a a b) 0 1 2 3
T.
b) a c) error
c) no output d) none of the mentioned
O
d) error
Answer: c
Answer: c
Explanation: i is not in x[1:].
b) 0 1 2 3
a) a B C D c) error
b) a b c d d) 1 2 3 4
17
c) A B C D
d) error Answer: b
Explanation: i takes values 0, 1, 2 and 3.
-R
Answer: b
Explanation: Changes do not happen in- 5. What will be the output of the following
place, rather a new instance of the string is Python code?
SE
returned.
x = 'abcd'
2. What will be the output of the following for i in range(len(x)):
Python code? print(i.upper())
C
x = 'abcd' a) a b c d
for i in x: b) 0 1 2 3
print(i.upper()) c) error
d) 1 2 3 4
a) a b c d
b) A B C D
Answer: c Answer: c
Explanation: Objects of type int have no Explanation: Objects of type int aren’t
attribute upper(). subscriptable. However, if the statement was
x[i], an error would not have been thrown.
6. What will be the output of the following
Python code snippet? 9. What will be the output of the following
Python code snippet?
x = 'abcd'
for i in range(len(x)): x = 'abcd'
M
i.upper() for i in range(len(x)):
print (x) x = 'a'
print(x)
O
a) a b c d
b) 0 1 2 3 a) a
C
c) error b) abcd abcd abcd
d) none of the mentioned c) a a a a
T.
d) none of the mentioned
Answer: c
O
Explanation: Objects of type int have no Answer: c
attribute upper(). Explanation: range() is computed only at the
b) ABCD a) a
c) error b) abcd abcd abcd abcd
d) none of the mentioned c) a a a a
17
place, rather a new instance of the string is Explanation: abcd a a a is the output as x is
returned. modified only after ‘abcd’ has been printed
once.
SE
a) abcd a) 1 2 3
b) ABCD b) 123
c) error c) error
d) none of the mentioned d) none of the mentioned
M
print(i) c) 0 a 1 b 2 c
d) none of the mentioned
a) 0 1 2
O
b) a b c Answer: b
c) 0 a 1 b 2 c Explanation: Loops over the keys and prints
C
d) none of the mentioned the values.
T.
Answer: a 6. What will be the output of the following
Explanation: Loops over the keys of the Python code?
O
dictionary.
d = {0: 'a', 1: 'b', 2: 'c'}
3. What will be the output of the following
Python code?
a) 0 1 2
G
for x, y in d: b) a b c
print(x, y) c) 0 a 1 b 2 c
LO
print(d[x])
4. What will be the output of the following
Python code? a) 0 1 2
SE
a) 0 1 2 Answer: d
b) a b c Explanation: Causes a KeyError.
c) 0 a 1 b 2 c
d) none of the mentioned 8. What will be the output of the following
Python code?
Answer: c
Explanation: Loops over key, value pairs. d = {0, 1, 2}
for x in d.values():
print(x) a) 0
b) no output
a) 0 1 2 c) error
b) None None None d) none of the mentioned
c) error
d) none of the mentioned Answer: b
Explanation: range(0) is empty.
Answer: c
Explanation: Objects of type set have no 1. What will be the output of the following
M
attribute values. Python code?
O
9. What will be the output of the following for i in range(2.0):
Python code? print(i)
C
d = {0, 1, 2} a) 0.0 1.0
b) 0 1
T.
for x in d:
print(x) c) error
d) none of the mentioned
a) 0 1 2
O
b) {0, 1, 2} {0, 1, 2} {0, 1, 2} Answer: c
c) error
d) none of the mentioned
Answer: a
SP
Explanation: Object of type float cannot be
interpreted as an integer.
for i in range(int(2.0)):
10. What will be the output of the following print(i)
Python code?
a) 0.0 1.0
.B
d = {0, 1, 2} b) 0 1
for x in d: c) error
print(d.add(x))
17
Answer: c
Python code?
Explanation: Variable x takes the values 0, 1
and 2. set.add() returns None which is for i in range(float('inf')):
printed.
C
print (i)
11. What will be the output of the following a) 0.0 0.1 0.2 0.3 …
Python code? b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
for i in range(0): d) none of the mentioned
print(i)
M
Explanation: [::-1] reverses the string.
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 … 8. What will be the output of the following
O
c) 0.0 1.0 2.0 3.0 … Python code snippet?
d) none of the mentioned
C
for i in '':
Answer: d print (i)
T.
Explanation: OverflowError, cannot convert
a) None
float infinity to integer.
b) (nothing is printed)
O
5. What will be the output of the following c) error
d) none of the mentioned
Python code snippet?
for i in ''.join(reversed(list('abcd'))):
c) 3 4
print (i) d) 0 1 2 3
SE
a) a b c d Answer: c
b) d c b a Explanation: Variable x is incremented and
c) error printed twice.
C
a) 0 1 2 3 4 … x = (i for i in range(3))
b) 0 -2 for i in x:
print(i)
c) 0
d) error a) 0 1 2
b) error
Answer: b
c) 0 1 2 0 1 2
Explanation: The loop is entered twice.
d) none of the mentioned
1. What will be the output of the following
M
Answer: a
Python code?
Explanation: The first statement creates a
generator object.
O
for i in range(10):
if i == 5:
break 4. What will be the output of the following
C
else: Python code?
print(i)
T.
else: x = (i for i in range(3))
print("Here") for i in x:
print(i)
O
a) 0 1 2 3 4 Here for i in x:
b) 0 1 2 3 4 5 Here print(i)
c) 0 1 2 3 4
d) 1 2 3 4 5 SP
a) 0 1 2
b) error
G
Answer: c c) 0 1 2 0 1 2
Explanation: The else part is executed if d) none of the mentioned
LO
break
else: string = "my name is x"
print(i) for i in string:
else: print (i, end=", ")
-R
print("Here")
a) m, y, , n, a, m, e, , i, s, , x,
a) 0 1 2 3 4 Here b) m, y, , n, a, m, e, , i, s, , x
SE
Answer: a
Answer: a Explanation: Variable i takes the value of
Explanation: The else part is executed if one character at a time.
control doesn’t break out of the loop.
6. What will be the output of the following
3. What will be the output of the following Python code?
Python code?
M
Answer: c
Explanation: Variable i takes the value of
one word at a time. Answer: c
O
Explanation: SyntaxError, not in isn’t
7. What will be the output of the following allowed in for loops.
C
Python code snippet?
10. What will be the output of the following
T.
a = [0, 1, 2, 3] Python code snippet?
for a[-1] in a:
print(a[-1]) string = "my name is x"
O
for i in ' '.join(string.split()):
a) 0 1 2 3 print (i, end=", ")
b) 0 1 2 2
c) 3 3 3 3
d) error
SP
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
G
c) my, name, is, x,
Answer: b d) error
LO
a = [0, 1, 2, 3]
TOPIC 3.2 PYTHON STRINGS
17
for a[0] in a:
print(a[0]) 1. What will be the output of the following
Python statement?
-R
a) 0 1 2 3
b) 0 1 2 2 1. >>>"a"+"bc"
c) 3 3 3 3
SE
d) error a) a
b) bc
Answer: a c) bca
Explanation: The value of a[0] changes in d) abc
C
1. >>>"abcd"[2:] Answer: c
Explanation: + is used to concatenate and *
a) a is used to multiply strings.
b) ab
c) cd 6. What will be the output of the following
d) dc Python code?
M
string. a) a new line and hello
b) \nhello
O
3. The output of executing string.ascii_letters c) the letter r and then hello
can also be achieved by: d) error
C
a) string.ascii_lowercase_string.digits
b) Answer: b
T.
string.ascii_lowercase+string.ascii_uppercase Explanation: When prefixed with the letter
c) string.letters ‘r’ or ‘R’ a string literal becomes a raw string
d) string.lowercase_string.uppercase and the escape sequences such as \n are not
O
converted.
Answer: b
Explanation: Execute in shell and check.
with strings? b)
a) + 97
b) *
c) – 98
d) All of the mentioned
c) x\97
d) \x97\x98
M
c) 22 None
2. >>>str1[::-1]
d) Error is generated
O
a) dlrowolleh
Answer: d
C
b) hello
c) world Explanation: self.o1 was never created.
T.
d) helloworld
2. What will be the output of the following
Python code?
Answer: a
O
Explanation: Execute in shell to verify.
1. class tester:
10. What will be the output of the following
Python code? SP 2.
3.
def __init__(self, id):
self.id = str(id)
G
print(0xA + 0xB + 0xC)
4. id="224"
a) 0xA0xB0xC
LO
b) Error 5.
c) 0x22
6. >>>temp = tester(12)
d) 33
.B
7. >>>print(temp.id)
Answer: d
Explanation: 0xA and 0xB and 0xC are a) 224
17
3. self.o1 = param
1. >>>example = "snow world"
4.
2. >>>print("%s" % example[4:7])
5. class child(father):
a) wo
6. def __init__(self, param): b) world
c) sn 1. >>>example = "helle"
d) rl
2. >>>example.find("e")
Answer: a
Explanation: Execute in the shell and verify. a) Error
b) -1
4. What will be the output of the following c) 1
Python code? d) 0
M
1. >>>example = "snow world" Answer: c
Explanation: Returns lowest index.
2. >>>example[3] = 's'
O
8. What will be the output of the following
3. >>>print example
C
Python code?
a) snow
T.
1. >>>example = "helle"
b) snow world
c) Error 2. >>>example.rfind("e")
O
d) snos world
a) -1
Answer: c
Explanation: Strings cannot be modified.
c) t 1. >>>example="helloworld"
d) y
17
2. >>>example[::-1].startswith("d")
Answer: d
Explanation: Max returns the character with a) dlrowolleh
the highest ascii value. b) True
-R
c) -1
6. Given a string example=”hello” what is the d) None
SE
output of example.count(‘l’)?
a) 2 Answer: b
b) 1 Explanation: Starts with checks if the given
c) None string starts with the parameter that is passed.
C
d) 0
10. To concatenate two strings to a third what
Answer: a statements are applicable?
Explanation: l occurs twice in hello. a) s3 = s1 . s2
b) s3 = s1.add(s2)
7. What will be the output of the following c) s3 = s1.__add__(s2)
Python code? d) s3 = s1 * s2
Answer: c Answer: d
Explanation: __add__ is another method that Explanation: Execute help(string.strip) to
can be used for concatenation. find details.
1. What will be the output of the following 5. The format function, when applied on a
Python statement? string returns ___________
a) Error
1. >>>chr(ord('A')) b) int
c) bool
M
a) A d) str
b) B
O
c) a Answer: d
d) Error Explanation: Format function returns a
C
string.
Answer: a
T.
Explanation: Execute in shell to verify. 6. What will be the output of the “hello”
+1+2+3?
2. What will be the output of the following a) hello123
O
Python statement? b) hello
c) Error
1. >>>print(chr(ord('b')+1))
a) a
SP
d) hello6
Answer: c
G
b) b Explanation: Cannot concatenate str and int
c) c objects.
LO
d) A
7. What will be the output of the following
Answer: c Python code?
Explanation: Execute in the shell to verify.
.B
a) print(“hello\example\test.txt”)
b) print(“hello\example\test.txt”) 3. >>>print("B", end = ' ')
c) print(“hello\”example\”test.txt”)
-R
b) A, B, C, D
Explanation: \is used to indicate that the next
c) D C B A
\ is not an escape sequence.
d) D, C, B, A will be displayed on four lines
C
M
command do we execute?
Answer: d
a) s.__len__()
Explanation: Execute in the shell to verify.
O
b) len(s)
9. What will be displayed by print(ord(‘b’) – c) size(s)
C
ord(‘a’))? d) s.size()
a) 0
T.
Answer: a
b) 1
Explanation: Execute in shell to verify.
c) -1
O
d) 2 4. If a class defines the __str__(self) method,
for an object obj for the class, you can use
Answer: b
Explanation: ASCII value of b is one more
than a. Hence the output of this code is 98-97,
SP
which command to invoke the __str__
method.
a) obj.__str__()
G
which is equal to 1.
b) str(obj)
c) print obj
10. Say s=”hello” what will be the return
LO
c) str
d) String 5. To check whether string s1 contains
17
d) si.in(s2)
1. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
Answer: a
SE
b) Heelo
Explanation: s2 in s1 works in the same way
c) Heleo
as calling the special function __contains__ .
d) None
C
M
)
3. self.__count = count
O
a) Peter Pan
4.
b) John Pan
C
5. c1 = Count(2) c) Peter Smith
d) John Smith
T.
6. c2 = Count(2)
Answer: b
7. print(id(c1) == id(c2), end = " ") Explanation: Execute in the shell to verify.
O
8. 9. What function do you use to read a string?
9. s1 = "Good"
10. s2 = "Good"
SP
a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
G
d) eval(enter(“Enter a string”))
11. print(id(s1) == id(s2))
LO
Answer: a
a) True False Explanation: Execute in shell to verify.
b) True True
c) False True 10. Suppose x is 345.3546, what is format(x,
.B
Answer: b
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?
SE
i, lastName):
3. self.firstName = firstName
a) abc def
b) ABC DEF
4. self.mi = mi c) Abc def
d) Abc Def
5. self.lastName = lastName
6.
M
a) abc. def Answer: b
O
b) ABC. DEF Explanation: Padding is done towards the
c) Abc. def left-hand-side first when the final string is of
C
d) Abc. Def odd length. Extra spaces are present since we
haven’t overridden the value of sep.
T.
Answer: c
Explanation: The first letter of the string is 6. What will be the output of the following
converted to uppercase and the others are Python code?
O
converted to lowercase.
print('*', "abcdef".center(7), '*', sep=
3. What will be the output of the following
Python code? SP
'')
a) * abcdef *
b) * abcdef *
G
print("abcdef".center())
c) *abcdef *
a) cd d) * abcdef*
LO
b) abcdef
c) error Answer: d
d) none of the mentioned Explanation: Padding is done towards the
.B
a) cd b) * abcde *
b) abcdef c) *abcde *
c) error d) * abcde*
C
M
must be a character, not an int. a) 2
b) 0
O
9. What will be the output of the following c) 1
Python code? d) none of the mentioned
C
print("abcdef".center(7, '1')) Answer: a
T.
Explanation: Counts the number of times the
a) 1abcdef substring ‘yy’ is present in the given string,
b) abcdef1 starting from position 1.
O
c) abcdef
d) error 3. What will be the output of the following
Answer: a
Explanation: The character ‘1’ is used for
SP
Python code?
print("xyyzxyzxzxyy".count('yy', 2))
padding instead of a space.
G
a) 2
10. What will be the output of the following b) 0
LO
Python code? c) 1
d) none of the mentioned
print("abcdef".center(10, '12'))
.B
Answer: c
a) 12abcdef12 Explanation: Counts the number of times the
b) abcdef1212 substring ‘yy’ is present in the given string,
17
Python code?
Explanation: The fill character must be
exactly one character long. print("xyyzxyzxzxyy".count('xyy', 0, 100)
SE
)
1. What will be the output of the following
Python code? a) 2
b) 0
C
print("xyyzxyzxzxyy".count('yy')) c) 1
d) error
a) 2
b) 0 Answer: a
c) error Explanation: An error will not occur if the
d) none of the mentioned end value is greater than the length of the
string itself.
M
Python code?
Answer: b
O
Explanation: Counts the number of times the print("xyyzxyzxzxyy".endswith("xyy"))
substring ‘xyy’ is present in the given string,
C
starting from position 2 and ending at a) 1
position 11. b) True
T.
c) 3
6. What will be the output of the following d) 2
Python code?
O
Answer: b
print("xyyzxyzxzxyy".count('xyy', -10, -1 Explanation: The function returns True if the
))
a) 2
b) 0
SP
given string ends with the specified substring.
print("xyyzxyzxzxyy".endswith("xyy", 0, 2
))
Answer: b
Explanation: Counts the number of times the a) 0
.B
Answer: c a) ab cd ef
Explanation: A bytes object is returned by b) abcdef
encode. c) ab\tcd\tef
d) ab cd ef
8. What is the default value of encoding in
encode()? Answer: a
a) ascii Explanation: Each \t is converted to 8 blank
M
c) ab\tcd\tef string at which the substring can be found is
d) ab cd ef returned.
O
Answer: d 6. What will be the output of the following
C
Explanation: Each \t is converted to 4 blank Python code?
spaces.
T.
print("ccdcddcd".find("c"))
3. What will be the output of the following
Python code? a) 4
O
b) 0
print("ab\tcd\tef".expandtabs('+')) c) Error
a) ab+cd+ef
b) ab++++++++cd++++++++ef
SP
d) True
Answer: b
c) ab cd ef Explanation: The first position in the given
G
d) none of the mentioned string at which the substring can be found is
returned.
LO
Answer: d
Explanation: TypeError, an integer should be 7. What will be the output of the following
passed as an argument. Python code?
.B
4. What will be the output of the following print("Hello {0} and {1}".format('foo',
Python code? 'bin'))
17
Explanation: The function find() returns the 8. What will be the output of the following
position of the sunstring in the given string Python code?
whereas the in keyword returns a value of
Boolean type. print("Hello {1} and {0}".format('bin',
'foo'))
5. What will be the output of the following
Python code? a) Hello foo and bin
b) Hello bin and foo
M
b) Hello ‘foo’ and foo
print("Hello {} and {}".format('foo', 'bi c) Hello foo and ‘bin’
d) Error
O
n'))
C
b) Hello {} and {} Explanation: !r causes the characters ‘ or ” to
c) Error be printed as well.
T.
d) Hello and
3. What will be the output of the following
O
Answer: a Python code?
Explanation: It is the same as Hello {0} and
{1}.
'foo', 'bin')))
1. What will be the output of the following
Python code? a) Hello foo and bin
SE
Answer: a a) 1,112,223,334
M
Explanation: The arguments passed to the b) 111,222,333,4
function format can be integers also. c) 1112223334
O
d) Error
6. What will be the output of the following
Python code snippet?
C
Answer: d
Explanation: $ is an invalid format code.
T.
print('The sum of {0:b} and {1:x} is {2:
o}'.format(2, 10, 12)) 10. What will be the output of the following
Python code snippet?
a) The sum of 2 and 10 is 12
O
b) The sum of 10 and a is 14 print('{:#}'.format(1112223334))
c) The sum of 10 and a is c
d) Error
Answer: b
SP
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
G
Explanation: 2 is converted to binary, 10 to d) Error
hexadecimal and 12 to octal.
LO
Answer: c
7. What will be the output of the following Explanation: The number is printed as it is.
Python code snippet?
.B
print('{0:.2}'.format(1/3))
b) 111,222,333,4
c) 1112223334 a) 0.333333
d) Error b) 0.33
-R
c) 0.333333:.2
Answer: a d) Error
Explanation: A comma is added after every
SE
M
Python code?
Answer: b
O
print('ab12'.isalnum()) Explanation: Space is not a letter.
C
a) True 7. What will be the output of the following
b) False Python code snippet?
T.
c) None
d) Error print('0xa'.isdigit())
O
Answer: a a) True
Explanation: The string has only letters and b) False
digits.
Answer: b
G
Python code?
Explanation: Hexadecimal digits aren’t
considered as digits (a-f).
LO
print('ab,12'.isalnum())
c) None
d) Error print(''.isdigit())
17
Answer: b a) True
Explanation: The character , is not a letter or b) False
a digit. c) None
d) Error
-R
Answer: a a) True
Explanation: The string has only letters. b) False
c) None
d) Error
Answer: a c) None
Explanation: It is a valid identifier. d) Error
M
b) False print('11'.isnumeric())
c) None
a) True
O
d) Error
b) False
C
Answer: a c) None
Explanation: It is a valid identifier. d) Error
T.
1. What will be the output of the following Answer: a
Python code snippet? Explanation: All the character are numeric.
O
print('for'.isidentifier()) 5. What will be the output of the following
a) True
b) False
SP
Python code snippet?
print('1.1'.isnumeric())
c) None
G
d) Error a) True
b) False
LO
Answer: a c) None
Explanation: Even keywords are considered d) Error
as valid identifiers.
.B
Answer: b
2. What will be the output of the following Explanation: The character . is not a numeric
Python code snippet? character.
17
b) False
Answer: a c) None
Explanation: There are no uppercase letters. d) Error
C
M
8. What will be the output of the following Answer: a
O
Python code snippet? Explanation: It is in the form of a title.
C
print('\t'.isspace()) 2. What will be the output of the following
Python code?
a) True
T.
b) False print('GYMK'.lower())
c) None
O
d) Error a) n
b) gymk
Answer: a
Explanation: Tab Spaces are considered as
spaces.
SP
c) rn
d) r
Answer: b
G
9. What will be the output of the following Explanation: Uppercase letters are converted
Python code snippet? to lowercase. The other characters are left
LO
unchanged.
print('HelloWorld'.istitle())
3. What will be the output of the following
a) True
.B
Python code?
b) False
c) None print('''
17
d) Error \tfoo'''.lstrip())
Answer: b a) \tfoo
Explanation: The letter W is uppercased. b) foo
-R
c) foo
10. What will be the output of the following d) none of the mentioned
Python code snippet?
SE
Answer: b
print('Hello World'.istitle()) Explanation: All leading whitespace is
removed.
C
a) True
b) False 4. What will be the output of the following
c) None Python code?
d) Error
print('xyyzxxyxyy'.lstrip('xyy'))
Answer: a
Explanation: It is in title form. a) error
b) zxxyxyy
M
b) (‘abef’)
print('xyxxyyzxxy'.lstrip('xyy')) c) (‘ab’, ‘cd’, ‘ef’)
O
d) 2
a) zxxy
C
b) xyxxyyzxxy Answer: c
c) xyxzxxy Explanation: The string is split into three
T.
d) none of the mentioned parts by partition.
O
Explanation: All combinations of the Python code?
characters passed as an argument are removed
from the left hand side.
print('cba'.maketrans('abc', '123'))
b) {65: 49, 66: 50, 67: 51} Explanation: The last item is a null string.
c) {97: 49}
d) 1 1. What will be the output of the following
Python code snippet?
Answer: b
Explanation: maketrans() is a static method print('cd'.partition('cd'))
a) (‘cd’) Answer: a
b) (”) Explanation: The first substring is not
c) (‘cd’, ”, ”) present in the given string and hence nothing
d) (”, ‘cd’, ”) is replaced.
M
2. What will be the output of the following a) ab1ef2
O
Python code snippet? b) abcefd
c) ab1efd
C
print('abef'.partition('cd')) d) ab12ed2
T.
a) (‘abef’) Answer: b
b) (‘abef’, ‘cd’, ”) Explanation: The first substring is not
c) (‘abef’, ”, ”) present in the given string and hence nothing
O
d) error is replaced.
Answer: c
Explanation: The separator is not present in
the string hence the second and the third
SP
6. What will be the output of the following
Python code snippet?
G
elements of the tuple are null strings. print('xyyxyyxyxyxxy'.replace('xy', '12',
0))
LO
d) xyyxyyxyxyx12
a) ab12ef12
b) abcdef12 Answer: a
17
print('xyyxyyxyxyxxy'.replace('xy', '12',
substring. 100))
b) 12y12y1212x12
print('abef'.replace('cd', '12'))
c) none of the mentioned
d) error
a) abef
b) 12 Answer: b
c) error Explanation: The first 100 occurrences of the
d) none of the mentioned given substring are replaced.
M
2. What will be the output of the following
Answer: b Python code snippet?
O
Explanation: The given string is split and a
list of substrings is returned. print('ab\ncd\nef'.splitlines())
C
9. What will be the output of the following a) [‘ab’, ‘cd’, ‘ef’]
T.
Python code snippet? b) [‘ab\n’, ‘cd\n’, ‘ef\n’]
c) [‘ab\n’, ‘cd\n’, ‘ef’]
print('abcdefcdghcd'.split('cd', 0)) d) [‘ab’, ‘cd’, ‘ef\n’]
O
a) [‘abcdefcdghcd’] Answer: a
b) ‘abcdefcdghcd’
c) error
d) none of the mentioned
SP
Explanation: It is similar to calling
split(‘\n’).
G
3. What will be the output of the following
Answer: a Python code snippet?
Explanation: The given string is split at 0
LO
M
c) Ab Cd-Ef Explanation: The function translate expects a
d) None of the mentioned dictionary of integers. Use maketrans()
O
instead of doing the above.
Answer: c
9. What will be the output of the following
C
Explanation: The first letter of every word is
capitalized. Special symbols terminate a Python code snippet?
T.
word.
print('ab'.zfill(5))
6. What will be the output of the following
O
Python code snippet? a) 000ab
b) 00ab0
print('abcd'.translate('a'.maketrans('ab
c', 'bcd')))
a) bcde
SP
c) 0ab00
d) ab000
Answer: a
G
b) abcd Explanation: The string is padded with zeros
c) error on the left hand side. It is useful for
LO
9: 100})) d) +++99
a) bcde Answer: c
SE
Answer: d Answer: c
Explanation: The function seed is a function Explanation: The function all returns false if
M
which is present in the random module. The any one of the elements of the iterable is zero
functions sqrt and factorial are a part of the and true if all the elements of the iterable are
O
math module. The print function is a built-in non zero. Hence the output of this function
function which prints a value directly to the will be false.
C
system output.
5. What will be the output of the following
T.
2. What will be the output of the following Python expression?
Python expression?
round(4.5676,2)?
O
round(4.576)
a) 4.5
a) 4.5
b) 5
c) 4
SP
b) 4.6
c) 4.57
d) 4.56
G
d) 4.6
Answer: c
Explanation: The function round is used to
LO
Answer: b
Explanation: This is a built-in function round off the given decimal number to the
which rounds a number to give precision in specified decimal places. In this case, the
decimal digits. In the above case, since the number should be rounded off to two decimal
.B
number of decimal places has not been places. Hence the output will be 4.57.
specified, the decimal number is rounded off
6. What will be the output of the following
17
a) (x**y)**z a) Error
b) (x**y) / z b) True
c) (x**y) % z
SE
c) False
d) (x**y)*z d) 4>2
Answer: c Answer: b
C
Explanation: The built-in function pow() can Explanation: The built-in function any()
accept two or three arguments. When it takes returns true if any or more of the elements of
in two arguments, they are evaluated as x**y. the iterable is true (non zero), If all the
When it takes in three arguments, they are elements are zero, it returns false.
evaluated as (x**y)%z.
7. What will be the output of the following
4. What will be the output of the following Python function?
Python function?
M
Explanation: The abs() function prints the used to find the maximum value from among
absolute value of the argument passed. For -3, -4 and false. Since false amounts to the
O
example: abs(-5)=5. Hence, in this case we value zero, hence we are left with min(0, 2, 7)
get abs(5.0)=5.0. Hence the output is 0 (false).
C
8. What will be the output of the following 1. What will be the output of the following
T.
Python function? Python functions?
sum(2,4,6) chr(‘97’)
O
sum([1,2,3]) chr(97)
a) Error, 6
b) 12, Error
c) 12, 6
d) Error, Error
SP
a)
a
G
Error
Answer: a
LO
b)
Explanation: The first function will result in
an error because the function sum() is used to ‘a’
find the sum of iterable numbers. Hence the
.B
Python function?
Error
all(3,0,4.2)
a
-R
a) True
b) False d)
c) Error
SE
Error
d) 0
Error
Answer: c
C
a)
(2.00, 0.50)
2. What will be the output of the following
(2.00, 0.00)
Python function?
complex(1+2j)
b)
(2, 0.5)
a) Error
M
b) 1 (2, 0)
c) 2j
O
d) 1+2j c)
C
Answer: d (2.0, 0.5)
Explanation: The built-in function complex()
(2.0, 0.0)
T.
returns the argument in a complex form.
Hence the output of the function shown above
d)
will be 1+2j.
O
(2, 0.5)
3. What is the output of the function
complex()?
a) 0j
b) 0+0j
SP
(2)
Answer: c
Explanation: See python documentation for
G
c) 0
d) Error the function divmod.
LO
Answer: a
Explanation: The complex function returns
0j if both of the arguments are omitted, that 6. The function complex(‘2-3j’) is valid but
.B
is, if the function is in the form of complex() the function complex(‘2 – 3j’) is invalid.
or complex(0), then the output will be 0j. a) True
b) False
17
b) (a//b, a%b) the string must not contain any blank spaces
c) (a//b, a*b) around the + or – operator. Hence the
d) (a/b, a%b) function complex(‘2 – 3j’) will result in an
SE
error.
Answer: b
Explanation: The function divmod(a,b) is 7. What will be the output of the following
Python function?
C
Answer: c Error
Explanation: The built-in function
2003
enumerate() accepts an iterable as an
argument. The function shown in the above Answer: b
case returns containing pairs of the numbers Explanation: The output of the first function
given, starting from 0. Hence the output will will be 0.001 and that of the second function
be: [(0, 2), (1,3)]. will be 2000.0. The first function created a
floating point number up to 3 decimal places
8. What will be the output of the following
M
and the second function adds 3 zeros after the
Python functions? given number.
O
x=3
eval('x^2')
C
a) Error 10. Which of the following functions does not
necessarily accept only iterables as
T.
b) 1
c) 9 arguments?
d) 6 a) enumerate()
O
b) all()
Answer: b c) chr()
Explanation: The function eval is use to
evaluate the expression that it takes as an
argument. In the above case, the eval()
SP
d) max()
Answer: c
Explanation: The functions enumerate(), all()
G
function is used to perform XOR operation
between 3 and 2. Hence the output is 1. and max() accept iterables as arguments
whereas the function chr() throws an error on
LO
9. What will be the output of the following receiving an iterable as an argument. Also
Python functions? note that the function chr() accepts only
integer values.
.B
float('1e-003')
float('2e+003') 1. Which of the following functions accepts
only integers as arguments?
17
a) a) ord()
3.00
b) min()
c) chr()
-R
300 d) any()
b) Answer: c
SE
b) list(reverse[(l)]) c)
c) reversed(l)
d) list(reversed(l)) A
Error
Answer: d
Explanation: The built-in function reversed() d)
can be used to reverse the elements of a list.
This function accepts only an iterable as an Error
argument. To print the output in the form of a
M
list, we use: list(reversed(l)). The output will Error
be: [4,3,2].
Answer: b
O
3. What will be the output of the following Explanation: The built-in function ord() is
C
Python function? used to return the ASCII value of the alphabet
passed to it as an argument. Hence the first
T.
float(' -12345\n') function results in an error and the output of
the second function is 65.
(Note that the number of blank spaces before
O
the number is 5)
a) -12345.0 (5 blank spaces before the
number)
b) -12345.0
c) Error
SP
5. What will be the output of the following
Python function?
G
d) -12345.000000000…. (infinite decimal float(‘-infinity’)
float(‘inf’)
places)
LO
a)
Answer: b
Explanation: The function float() will –inf
remove all the blank spaces and convert the
.B
inf
ord(65)
ord(‘A’)
c)
SE
a)
Error
A Error
C
65
d)
b)
Error
Error Junk value
65 Answer: a
Explanation: The output of the first function
will be –inf and that of the second function throw errors. However the function ord(‘ ‘)
will be inf. does not throw an error because in this case,
we are actually passing a blank space as an
argument. The output of ord(‘ ‘) is 32 (ASCII
value corresponding to blank space).
6. Which of the following functions will not
result in an error when no arguments are 9. What will be the output of the following
passed to it? Python function?
a) min()
M
b) divmod() len(["hello",2, 4, 6])
c) all()
O
d) float() a) 4
b) 3
C
Answer: d c) Error
Explanation: The built-in functions min(), d) 6
T.
max(), divmod(), ord(), any(), all() etc throw
an error when no arguments are passed to Answer: a
them. However there are some built-in Explanation: The function len() returns the
O
functions like float(), complex() etc which do length of the number of elements in the
not throw an error when no arguments are iterable. Therefore the output of the function
passed to them. The output of float() is 0.0.
oct(7)
hex(15)
oct(‘7’)
a) f a)
b) 0xF
.B
c) 0Xf Error
d) 0xf
17
07
Answer: d
Explanation: The function hex() is used to b)
convert the given argument into its
-R
0o7
hexadecimal representation, in lower case.
Hence the output of the function hex(15) is Error
0xf.
SE
c)
8. Which of the following functions does not
throw an error? 0o7
C
a) ord()
b) ord(‘ ‘) Error
c) ord(”)
d)
d) ord(“”)
07
Answer: b
Explanation: The function ord() accepts a 0o7
character. Hence ord(), ord(”) and ord(“”)
'Hello World!'
M
c)
TOPIC 3.3.2 USER DEFINED
O
FUNCTIONS Hello
Hello
C
1. Which of the following is the use of
function in python? d) None of the mentioned
T.
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity Answer: a
O
for your application Explanation: Functions are defined using the
c) you can’t also create your own functions def keyword. After this keyword comes an
d) All of the mentioned
Answer: a
SP
identifier name for the function, followed by
a pair of parentheses which may enclose
some names of variables, and by the final
colon that ends the line. Next follows the
Explanation: Functions are reusable pieces
G
of programs. They allow you to give a name block of statements that are part of this
to a block of statements, allowing you to run function.
LO
c) Def
d) Function 4.
5. sayHello() # call the function
-R
Answer: c
Explanation: None.
6. sayHello() # call the function agai
n
SE
2. print('Hello World!')
1. def printMax(a, b):
2. if a > b:
3. sayHello()
4. sayHello() 3. print(a, 'is maximum')
4. elif a == b:
a)
M
c) 4 is maximum Answer: a
d) None of the mentioned Explanation: The first time that we print the
O
value of the name x with the first line in the
Answer: c function’s body, Python uses the value of the
C
Explanation: Here, we define a function parameter declared in the main block, above
called printMax that uses two parameters the function definition.
T.
called a and b. We find out the greater Next, we assign the value 2 to x. The name x
number using a simple if..else statement and is local to our function. So, when we change
O
then print the bigger number. the value of x in the function, the x defined in
the main block remains unaffected.
5. What will be the output of the following
Python code?
1. x = 50
SP
With the last print function call, we display
the value of x as defined in the main block,
thereby confirming that it is actually
unaffected by the local assignment within the
G
previously called function.
2. def func(x):
LO
1. x = 50
5. print('Changed local x to', x)
2. def func():
17
6. func(x)
3. global x
7. print('x is now', x)
4. print('x is', x)
-R
a)
5. x = 2
x is 50
6.
SE
b)
a)
x is 50
x is 50
Changed local x to 2
Changed global x to 2
x is now 2
Value of x is 50
b) d)
x is 50 Hello
Value of x is 2 Answer: a
Explanation: For some functions, you may
c) want to make some parameters optional and
M
use default values in case the user does not
x is 50
want to provide values for them. This is done
with the help of default argument values. You
O
Changed global x to 50
can specify default argument values for
Value of x is 50 parameters by appending to the parameter
C
name in the function definition the
d) None of the mentioned assignment operator (=) followed by the
T.
default value.
Answer: b The function named say is used to print a
Explanation: The global statement is used to
O
string as many times as specified. If we don’t
declare that x is a global variable – hence, supply a value, then by default, the string is
when we assign a value to x inside the
function, that change is reflected when we use
the value of x in the main block.
SP
printed just once. We achieve this by
specifying a default argument value of 1 to
the parameter times.
G
In the first usage of say, we supply only the
7. What will be the output of the following
string and it prints the string once. In the
Python code?
LO
3. say('Hello')
8. What will be the output of the following
17
3.
b)
4. func(3, 7)
C
Hello
5. func(25, c = 24)
World 5
6. func(c = 50, a = 100)
c)
a)
Hello
a is 7 and b is 3 and c is 10
World,World,World,World,World
M
a is 50 and b is 100 and c is 5
3. return x
c)
O
4. elif x == y:
a is 3 and b is 7 and c is 10
C
5. return 'The numbers are equ
a is 25 and b is 5 and c is 24 al'
T.
a is 100 and b is 5 and c is 50 6. else:
O
d) None of the mentioned 7. return y
8.
Answer: c
Explanation: If you have some functions
with many parameters and you want to
SP 9. print(maximum(2, 3))
G
specify only some of them, then you can give a) 2
values for such parameters by naming them – b) 3
LO
this is called keyword arguments – we use the c) The numbers are equal
name (keyword) instead of the position d) None of the mentioned
(which we have been using all along) to
specify the arguments to the function. Answer: b
.B
The function named func has one parameter Explanation: The maximum function returns
without a default argument value, followed the maximum of the parameters, in this case
by two parameters with default argument the numbers supplied to the function. It uses a
17
gets the value 3, the parameter b gets the 10. Which of the following is a feature of
value 7 and c gets the default value of 10. DocString?
a) Provide a convenient way of associating
SE
In the second usage func(25, c=24), the documentation with Python modules,
variable a gets the value of 25 due to the functions, classes, and methods
position of the argument. Then, the parameter b) All functions should have a docstring
C
c gets the value of 24 due to naming i.e. c) Docstrings can be accessed by the __doc__
keyword arguments. The variable b gets the attribute on objects
default value of 5. d) All of the mentioned
are an important tool that you should make 5. Which of the following is the use of id()
use of since it helps to document the program function in python?
better and makes it easier to understand. a) Id returns the identity of the object
b) Every object doesn’t have a unique id
1. Which are the advantages of functions in c) All of the mentioned
python? d) None of the mentioned
a) Reducing duplication of code
b) Decomposing complex problems into Answer: a
simpler pieces Explanation: Each object in Python has a
M
c) Improving clarity of the code unique id. The id() function returns the
d) All of the mentioned object’s id.
O
Answer: d 6. Which of the following refers to
C
Explanation: None. mathematical function?
a) sqrt
T.
2. What are the two main types of functions? b) rhombus
a) Custom function c) add
b) Built-in function & User defined function d) rhombus
O
c) User function
d) System function Answer: a
Answer: b
Explanation: Built-in functions and user
SP
Explanation: Functions that are always
available for usage, functions that are
contained within external modules, which
G
defined ones. The built-in functions are part must be imported and functions defined by a
of the Python language. Examples are: dir(), programmer with the def keyword.
LO
len() or abs(). The user defined functions are Eg: math import sqrt
functions created with the def keyword. A sqrt() function is imported from the math
module.
3. Where is function defined?
.B
c) Another function
d) All of the mentioned 1. def cube(x):
Answer: d 2. return x * x * x
-R
4. print x
4. What is called when a function is defined
inside a class? a) 9
a) Module b) 3
C
b) Class c) 27
c) Another function d) 30
d) Method
Answer: c
Answer: d Explanation: A function is created to do a
Explanation: None. specific task. Often there is a result from such
a task. The return keyword is used to return
M
32
2. return c * 9/5 + 32
O
b)
3. print C2F(100)
C
9
4. print C2F(0)
27
T.
a)
c)
212
O
567
32
b) SP
98
2. r = 1 5. for i in args:
3. for i in range(y): 6. r += i
4. r = r * x 7. return r
8. print sum.__doc__
M
a) 48
b) b) 14
c) 64
O
6
d) None of the mentioned
C
100
Answer: a
c) Explanation: The lambda keyword creates an
T.
anonymous function. The x is a parameter,
123 that is passed to the lambda function. The
O
parameter is followed by a colon character.
12345
The code next to the colon is the expression
d) None of the mentioned
Answer: a
SP
that is executed, when the lambda function is
called. The lambda function is assigned to the
z variable.
G
Explanation: We use the * operator to The lambda function is executed. The number
indicate, that the function will accept 8 is passed to the anonymous function and it
LO
arbitrary number of arguments. The sum() returns 48 as the result. Note that z is not a
function will return the sum of all arguments. name for this function. It is only a variable to
The first string in the function body is called which the anonymous function was assigned.
the function documentation string. It is used
.B
to document the function. The string must be 3. What will be the output of the following
in triple quotes. Python code?
17
a) lambda a) 15
b) pi b) 555
c) anonymous
SE
c) 125
d) none of the mentioned d) None of the mentioned
Answer: a Answer: c
C
Answer: b 5.
Explanation: lambda definition does not
include a return statement. it always contains 6. who = writer()
an expression which is returned. Also note
7. who('Arthur')
that we can put a lambda definition anywhere
a function is expected. We don’t have to a) Arthur Sir
assign it to a variable at all. b) Sir Arthur
c) Arthur
5. Lambda is a statement.
M
d) None of the mentioned
a) True
b) False Answer: b
O
Explanation: None.
Answer: b
C
Explanation: lambda is an anonymous 9. What will be the output of the following
function in Python. Hence this statement is Python code?
T.
false.
1. L = [lambda x: x ** 2,
6. Lambda contains block of statements.
O
a) True 2. lambda x: x ** 3,
b) False
Answer: b
Explanation: None.
SP 3.
4.
lambda x: x ** 4]
G
5. for f in L:
7. What will be the output of the following
LO
a) 432 81
17
b) 24000
c) 430 343
d) No output
b)
-R
Answer: a 6
Explanation: None.
SE
9
8. What will be the output of the following
Python code? 12
C
1. def writer(): c)
2. title = 'Sir' 9
M
y) d) An exception is thrown
2. min(101*99, 102*98)
O
Answer: c
a) 9997 Explanation: Any change made in to an
C
b) 9999 immutable data type in a function isn’t
c) 9996 reflected outside the function.
T.
d) None of the mentioned
4. What will be the output of the following
Python code?
O
Answer: c
Explanation: None.
def a(b):
c = [1, 2, 3, 4]
a) A static variable a(c)
G
b) A global variable print(len(c))
c) A local variable
LO
a) 4
d) An automatic variable
b) 5
Answer: b c) 1
d) An exception is thrown
.B
referred to as?
5. What will be the output of the following
a) A global variable
Python code?
b) A volatile variable
SE
10 a) Integer
b) Tuple
56
c) Dictionary
b) d) An exception is thrown
45 Answer: b
Explanation: The parameter two is a variable
56 parameter and consists of (2,3,4). Hence the
data type is tuple.
M
c)
8. If a function doesn’t have a return
O
10 statement, which of the following does the
20 function return?
C
a) int
d) Syntax Error b) null
T.
c) None
Answer: a d) An exception is thrown without the return
statement
O
Explanation: The statement “global b”
allows the global value of b to be accessed
Answer: c
and changed. Whereas the variable a is local
and hence the change isn’t reflected outside
the function.
SP
Explanation: A function can exist without a
return statement and returns None if the
function doesn’t have a return statement.
G
6. What will be the output of the following
Python code? 9. What will be the output of the following
LO
Python code?
def change(i = 1, j = 2):
i = i + j def display(b, n):
j = j + 1 while n > 0:
.B
print(i, j) print(b,end="")
change(j = 1, i = 2) n=n-1
display('z',3)
17
c) 3 3 c) An exception is executed
d) 3 2 d) Infinite loop
SE
Answer: d Answer: a
Explanation: The values given during Explanation: The loop runs three times and
function call is taken into consideration, that ‘z’ is printed each time.
is, i=2 and j=1.
C
a) String Answer: b
b) Tuple Explanation: Lists are passed by reference.
c) Dictionary
d) An exception is thrown 4. How are keyword arguments specified in
the function heading?
Answer: c a) one-star followed by a valid identifier
Explanation: b combines the remaining b) one underscore followed by a valid
parameters into a dictionary. identifier
c) two stars followed by a valid identifier
M
d) two underscores followed by a valid
TOPIC 3.3 ARGUMENTS AND identifier
O
PARAMETERS
Answer: c
C
1. What is the type of each element in Explanation: Refer documentation.
sys.argv?
T.
a) set 5. How many keyword arguments can be
b) list passed to a function in a single function call?
a) zero
O
c) tuple
d) string b) one
c) zero or more
Answer: d
Explanation: It is a list of strings.
SP
d) one or more
Answer: c
G
2. What is the length of sys.argv? Explanation: Zero keyword arguments may
a) number of arguments be passed if all the arguments have default
LO
Answer: b
def foo(fname, val):
Explanation: The first argument is the name
print(fname(val))
17
a) 3 1
3. What will be the output of the following b) 1 3
Python code? c) error
SE
foo(q)
print(q) names as arguments to other functions.
M
Explanation: It is possible to read the value
of a global variable directly.
Answer: b
O
8. What will be the output of the following Explanation: When a list is a default value,
Python code? the same list will be reused.
C
1. What will be the output of the following
T.
def foo():
total += 1 Python code?
return total
total = 0 def foo(k):
O
print(foo()) k = [1]
q = [0]
a) 0
b) 1
c) error
SP
foo(q)
print(q)
a) [0]
G
d) none of the mentioned
b) [1]
c) [1, 0]
LO
Answer: c
Explanation: It is not possible to change the d) [0, 1]
value of a global variable without explicitly
Answer: a
specifying it.
.B
a) True identifier
c) two stars followed by a valid identifier
b) False
d) two underscores followed by a valid
c) None
identifier
C
d) Error
Answer: a
Answer: b
Explanation: A new object is created in the Explanation: Refer documentation.
function. 3. Which module in the python standard
library parses options received from the
10. What will be the output of the following
Python code? command line?
M
4. What is the type of sys.argv? def foo(x):
x[0] = ['def']
a) set
x[1] = ['abc']
O
b) list return id(x)
c) tuple q = ['abc', 'def']
C
d) string print(id(q) == foo(q))
T.
Answer: b a) True
Explanation: It is a list of elements. b) False
c) None
O
5. What is the value stored in sys.argv[0]? d) Error
a) null
b) you cannot access it
c) the program’s name
d) the first argument
SP
Answer: a
Explanation: The same object is modified in
the function.
G
Answer: c 9. Where are the arguments received from the
LO
x.append(x.append(i))
Explanation: Refer documentation. return x
for i in range(3):
7. How are required arguments specified in y = foo(i)
C
GLOBAL SCOPE a) 13
b) 10
1. What will be the output of the following c) 2
Python code? d) 5
M
def f1(): Answer: a
O
x=15 Explanation: The value passed to the
print(x)
function san() is 12. This value is
C
x=12
f1() incremented by one and printed. Hence the
output of the code shown above is 13.
T.
a) Error
b) 12 4. What will be the output of the following
O
c) 15 Python code?
d) 1512
def f1():
Answer: c
Explanation: In the code shown above, x=15
SP global x
x+=1
print(x)
is a local variable whereas x=12 is a global
G
x=12
variable. Preference is given to local variable print("x")
over global variable. Hence the output of the
LO
Python code?
13
def f1():
x
17
x=100
print(x)
x=+1 d) x
f1()
-R
Answer: d
a) Error Explanation: In the code shown above, the
b) 100 variable ‘x’ is declared as global within the
SE
13
Explanation: The variable x is a local x
variable. It is first printed and then modified.
Hence the output of this code is 100. 5. What will be the output of the following
Python code?
3. What will be the output of the following
Python code? def f1(x):
global x
x+=1 a = "world"
print(x) f()
f1(15) print(a)
print("hello")
a)
a) error
b) hello hello
c) 16
hello
d)
M
world
16
b)
O
hello
Answer: a world
C
Explanation: The code shown above will
hello
T.
result in an error because ‘x’ is a global
variable. Had it been a local variable, the hello
output would be: 16
O
hello c)
world
G
Python code? world
LO
x=12 d)
def f1(a,b=x):
print(a,b) world
x=15
f1(4)
.B
hello
a) Error world
b) 12 4
17
c) 4 12 Answer: b
d) 4 15 Explanation: Since the variable ‘a’ has been
explicitly specified as a global variable, the
-R
return b error
print(f1(2,[3,4]))
b)
a) [3,2,4]
b) [2,3,4] inner
c) Error
error
d) [3,4,2]
c)
Answer: d
M
Explanation: In the code shown above, the outer
integer 2 is appended to the list [3,4]. Hence
O
the output of the code is [3,4,2]. Both the inner
variables a and b are local variables.
d) error
C
9. What will be the output of the following
Answer: a
T.
Python code?
Explanation: The error will be caused due to
def f(p, q, r): the statement f1(1) because the function is
O
global s nested. If f1(1) had been called inside the
p = 10
function, the output would have been
q = 20
r = 30
s = 40
print(p,q,r,s)
SP
different and there would be no error.
a) 1 2 3 4 def f1():
b) 5 10 15 4 global x
c) 10 20 30 40 x = 4
def f2(a,b):
.B
d) 5 10 15 40 global x
return a+b+x
Answer: c f1()
17
def f(x):
print("outer") Answer: b
def f1(a): Explanation: In the code shown above, the
C
print("inner")
print(a,x)
variable ‘x’ has been declared as a global
f(3) variable under both the functions f1 and f2.
f1(1) The value returned is a+b+x = 1+2+4 = 7.
x=100 Answer: c
def f1(): Explanation: Both the functions, that is,
global x
x=90
globals() and locals() return value of the data
def f2(): structure dictionary.
global x
x=80 2. What will be the output of the following
print(x) Python code?
a) 100 x=1
M
b) 90 def cg():
c) 80 global x
x=x+1
O
d) Error
cg()
x
C
Answer: a
Explanation: The output of the code shown a) 2
T.
above is 100. This is because the variable ‘x’ b) 1
has been declared as global within the c) 0
functions f1 and f2. d) Error
O
13. Read the following Python code carefully Answer: a
and point out the global variables?
y, z = 1, 2
SP
Explanation: Since ‘x’ has been declared a
global variable, it can be modified very easily
within the function. Hence the output is 2.
G
def f():
global x
x = y+z 3. On assigning a value to a variable inside a
LO
f("bitter")
locals()?
a) list a) error
b) set b)
c) dictionary
d) tuple butter
error
M
Explanation: The output of the code shown
above will be ‘bitter’, followed by an error. Answer: d
The error is because the operand ‘+’ is Explanation: In the code shown above, when
O
unsupported on the types used above. we call the function f, a new namespace is
created. The assignment x=4 is performed in
C
5. What happens if a local variable exists with the local namespace and does not affect the
the same name as the global variable you global namespace. Hence the output is 1.
T.
want to access?
a) Error 8. ______________ returns a dictionary of
O
b) The local variable is shadowed the module namespace.
c) Undefined behavior ________________ returns a dictionary of
d) The global variable is shadowed
Answer: d
SP
the current namespace.
a)
locals()
Explanation: If a local variable exists with
G
the same name as the local variable that you
globals()
want to access, then the global variable is
LO
a=10 c)
globals()['a']=25
print(a) globals()
-R
a) 10 locals()
b) 25
c) Junk value d)
SE
d) Error
globals()
Answer: b globals()
C
Sanfoundry Global Education & Learning 4. Fill in the line of the following Python
Series – Python. code for calculating the factorial of a number.
def fact(num):
TOPIC 3.5 RECURSION if num == 0:
return 1
else:
1. Which is the most appropriate definition return _____________________
for recursion?
a) A function that calls itself a) num*fact(num-1)
M
b) A function execution instance that calls b) (num-1)*(num-2)
another execution instance of the same c) num*(num-1)
O
function d) fact(num)*fact(num-1)
c) A class method that calls another class
C
method Answer: a
d) An in-built method that is automatically Explanation: Suppose n=5 then, 5*4*3*2*1
T.
called is returned which is the factorial of 5.
O
Explanation: The appropriate definition for a Python code?
recursive function is a function execution
instance that calls another execution instance
of the same function either directly or
indirectly.
SP
def test(i,j):
if(i==0):
return j
G
else:
return test(i-1,i+j)
2. Only problems that are recursively defined print(test(4,7))
LO
Answer: b d) 17
Explanation: There are many other problems
17
non-recursive function
b) Recursive functions usually take more 6. What will be the output of the following
Python code?
SE
if(b==0):
understand return l
dig=b%2
Answer: c l.append(dig)
Explanation: The speed of a program using convert(b//2)
convert(6)
recursion is slower than the speed of its non- l.reverse()
recursive equivalent. for i in l:
print(i,end="")
M
7. What is tail recursion? Answer: d
a) A recursive function that has two base Explanation: A recursive function needn’t
O
cases have a return value.
b) A function where the recursive functions
C
leads to an infinite loop 10. What will be the output of the following
c) A recursive function where the function Python code?
T.
doesn’t return anything and just prints the
values def fun(n):
if (n > 100):
d) A function where the recursive call is the
O
return n - 5
last thing executed by the function return fun(fun(n+11));
Answer: d
Explanation: A recursive function is tail
recursive when recursive call is executed by
SP
print(fun(45))
a) 50
G
the function in the last. b) 100
c) 74
LO
return 0
else:
code keeps executing until the value of n
return n*a(n - 1) becomes greater than 100, after which n-5 is
17
M
recursion?
a) Making the code look clean
O
b) A complex task can be broken into sub-
problems UNIT IV LISTS, TUPLES,
C
c) Recursive calls take up less memory
d) Sequence generation is easier than a nested
DICTIONARIES
T.
iteration
TOPIC 4.1 LISTS ( LIST
Answer: c
O
Explanation: Recursive calls take up a lot of
OPERATIONS, LIST SLICES,
memory and time as memory is taken up each LIST METHODS, LIST LOOP,
time the function is called.
problems using recursion than non-recursive 1. Which of the following commands will
equivalent create a list?
b) Recursive functions are easy to debug a) list1 = list()
c) Recursive calls take up a lot of memory b) list1 = []
.B
Answer: b Answer: d
Explanation: Recursive functions may be Explanation: Execute in the shell to verify
hard to debug as the logic behind recursion
-R
if n == 0:
return 0
Answer: a
elif n == 1:
return 1 Explanation: Execute in the shell to verify.
else:
return a(n-1)+a(n-2) 3. Suppose listExample is [‘h’,’e’,’l’,’l’,’o’],
for i in range(0,4): what is len(listExample)?
print(a(i),end=" ") a) 5
M
a) 2445 Explanation: Slicing is allowed in lists just
b) 133 as in the case of strings.
O
c) 12454
d) 123 9. Suppose list1 is [2, 33, 222, 14, 25], What
C
is list1[-1]?
Answer: c a) Error
T.
Explanation: Max returns the maximum b) None
element in the list. c) 25
d) 2
O
5. Suppose list1 is [3, 5, 25, 1, 3], what is
min(list1)? Answer: c
a) 3
b) 5
c) 25
SP
Explanation: -1 corresponds to the last index
in the list.
G
d) 1 10. Suppose list1 is [2, 33, 222, 14, 25], What
is list1[:-1]?
LO
do we use?
a) list1.shuffle() b) Daman
b) shuffle(list1) c) Error
c) random.shuffle(list1) d) n
d) random.shuffleList(list1)
Answer: d
Answer: c Explanation: Execute in the shell to verify.
Explanation: Execute in the shell to verify.
M
4. b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
O
5. names2[0] = 'Alice' d) [0.0, 0.5, 1.0, 1.5, 2.0]
6. names3[1] = 'Bob'
C
Answer: c
7. Explanation: Execute in the shell to verify.
T.
8. sum = 0 5. What will be the output of the following
Python code?
O
9. for ls in (names1, names2, names3):
1. >>>list1 = [11, 2, 23]
10.
11.
if ls[0] == 'Alice':
sum += 1
SP 2. >>>list2 = [11, 2, 2]
3. >>>list1 < list2 is
G
12. if ls[1] == 'Bob':
a) True
LO
13. sum += 10
b) False
14. c) Error
d) None
.B
b) 12 one.
c) 21
d) 22 6. To add a new element to a list we use
-R
which command?
Answer: b a) list1.add(5)
Explanation: When assigning names1 to b) list1.append(5)
SE
copy of names1 which can be modified Explanation: We use the function append to
independently. add an element to the list.
3. Suppose list1 is [1, 3, 2], What is list1 * 2? 7. To insert 5 to the third position in list1, we
a) [2, 6, 4] use which command?
b) [1, 3, 2, 1, 3] a) list1.insert(3, 5)
b) list1.insert(2, 5)
M
b) list1.remove(hello) 3. Suppose listExample is [3, 4, 5, 20, 5, 25,
c) list1.removeAll(“hello”) 1, 3], what is list1 after listExample.pop(1)?
O
d) list1.removeOne(“hello”) a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
C
Answer: a c) [3, 5, 20, 5, 25, 1, 3]
Explanation: Execute in the shell to verify. d) [1, 3, 4, 5, 20, 5, 25]
T.
9. Suppose list1 is [3, 4, 5, 20, 5], what is Answer: c
list1.index(5)? Explanation: pop() removes the element at
O
a) 0 the position specified in the parameter.
b) 1
c) 4
d) 2 SP
4. Suppose listExample is [3, 4, 5, 20, 5, 25,
1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
G
Answer: d b) [1, 3, 3, 4, 5, 5, 20, 25]
Explanation: Execute help(list.index) to get c) [3, 5, 20, 5, 25, 1, 3]
LO
Answer: a Answer: c
Explanation: Execute in the shell to verify. Explanation: Execute in the shell to verify.
7. What will be the output of the following 9. What will be the output of the following
M
Python code? Python code?
O
1. myList = [1, 5, 5, 5, 5, 1] 1. >>>list1 = [1, 3]
C
2. max = myList[0] 2. >>>list2 = list1
3. indexOfMax = 0 3. >>>list1[0] = 4
T.
4. for i in range(1, len(myList)): 4. >>>print(list2)
O
5. if myList[i] > max: a) [1, 3]
b) [4, 3]
6.
7.
max = myList[i]
indexOfMax = i
SP
c) [1, 4]
d) [1, 3, 4]
G
8. Answer: b
Explanation: Lists should be copied by
LO
c) 3
d) 4 1. def f(values):
17
Answer: a 2. values[0] = 44
Explanation: First time the highest number is
encountered is at index 1. 3.
-R
4. v = [1, 2, 3]
8. What will be the output of the following
Python code? 5. f(v)
SE
a) [1, 44]
b) [1, 2, 3, 44]
3. myList[i - 1] = myList[i]
c) [44, 2, 3]
4. d) [1, 2, 3]
1. What will be the output of the following 1. names1 = ['Amir', 'Bala', 'Charlie'
Python code? ]
M
a) None
5. f(1) b) a
O
c) b
6. f(2) d) c
C
7. v = f(3) Answer: d
T.
8. print(v) Explanation: List Comprehension are a
shorthand for creating new lists.
O
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3] 4. What will be the output of the following
Python code?
c) [1, 2, 3]
d) 1 2 3
Answer: c
SP 1. numbers = [1, 2, 3, 4]
G
2.
Explanation: Execute in the shell to verify
3. numbers.append([5,6,7,8])
LO
2. a) 4
b) 5
17
3. if 'amir' in names1: c) 8
d) 12
4. print(1)
-R
5. else: Answer: b
Explanation: A list is passed in append so the
6. print(2) length is 5.
SE
c) 2 a) Lists
d) Error b) Dictionary
c) Set
Answer: c d) All of the mentioned
Explanation: Execute in the shell to verify.
Answer: d
3. What will be the output of the following Explanation: In can be used in all data
Python code? structures.
M
8. print(increment_items(values, 2))
a) 2 9. print(values)
O
b) 4
c) 5 a)
C
d) 8
None
T.
Answer: d
Explanation: + appends all the elements [3, 4, 5]
O
individually into a new list.
b)
7. What will be the output of the following
Python code?
1. def addItem(listParam):
SP None
[1, 2, 3]
G
c)
2. listParam += [1]
LO
[3, 4, 5]
3.
[1, 2, 3]
4. mylist = [1, 2, 3, 4]
.B
d)
5. addItem(mylist)
[3, 4, 5]
17
6. print(len(mylist))
None
a) 1
b) 4 Answer: a
-R
Answer: c
Explanation: + will append the element to 9. What will be the output of the following
the list. Python code?
C
M
a) Return a list containing every third item Explanation: Execute in the shell to verify.
from L starting at index 0
O
b) Return an empty list 2. How many elements are in m?
c) Return a list containing every third index
C
from L starting at index 0 1. m = [[x, y] for x in range(0, 4) fo
r y in range(0, 4)]
d) Return a list containing the items from L
T.
starting from index 0, omitting every third a) 8
item b) 12
O
c) 16
Answer: a
d) 32
Explanation: Run the code to get a better
understanding with many arguments.
oli'), 'celery')
2.
3. print(veggies)
3. v = values[0][0]
17
‘asparagus’]
7. v = values[row][column]
d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’,
‘asparagus’] 8.
C
Answer: a 9. print(v)
Explanation: Execute in the shell to verify.
a) 3
1. What will be the output of the following b) 5
Python code? c) 6
d) 33
M
2.
6. What will be the output of the following
3. v = values[0][0] Python code?
O
4. for lst in values: 1. matrix = [[1, 2, 3, 4],
C
5. for element in lst: 2. [4, 5, 6, 7],
T.
6. if v > element: 3. [8, 9, 10, 11],
O
7. v = element 4. [12, 13, 14, 15]]
8. 5.
c) 5
d) 6 b) 4 5 6 7
c) 1 3 8 12
Answer: a d) 2 5 9 13
.B
Python code?
7. What will be the output of the following
1. values = [[3, 4, 5, 1 ], [33, 6, 1, Python code?
-R
2]]
1. def m(list):
2.
2.
SE
v = list[0]
3. for row in values:
3. for e in list:
4. row.sort()
4.
C
if v < e: v = e
5. for element in row:
5. return v
6. print(element, end = " ")
6.
7. print()
7. values = [[3, 4, 5, 1], [33, 6, 1,
a) The program prints two rows 3 4 5 1 2]]
followed by 33 6 1 2
8. 9.
9. for row in values: 10. return v
a) 3 33 12. print(ttt(data[0]))
b) 1 1
c) 5 6 a) 1
b) 2
M
d) 5 33
c) 4
Answer: d d) 5
O
Explanation: Execute in the shell to verify.
Answer: c
C
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?
T.
10. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?
O
[7, 8]]]
1. points = [[1, 2], [3, 1.5], [0.5,
2. 0.5]]
3. print(data[1][0][0]) SP 2. points.sort()
3. print(points)
G
a) 1
b) 2
a) [[1, 2], [3, 1.5], [0.5, 0.5]]
LO
c) 4
d) 5 b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
Answer: d d) [[0.5, 0.5], [3, 1.5], [1, 2]]
.B
Python code?
1. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?
-R
[7, 8]]]
a=[10,23,56,[78]]
2. b=list(a)
a[3][0]=95
SE
5. b) [10,23,56,[78]]
c) [10,23,56,[95]]
6. for row in m: d) [10,34,56,[78]]
7. for element in row:
Answer: c
8. if v < element: v = elem Explanation: The above copy is a type of
ent
M
)))) a=list(s.partition("@"))
print(a)
a) b=list(s.split("@",3))
O
print(b)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)]
C
a)
[(2,4),(‘b’,’c’),(‘yy’,’xx’)]
T.
[‘a’,’b’,’c’,’d’]
b)
[‘a’,’b’,’c’,’d’]
O
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’
‘)] b)
[(2, 'b', 'yy'), (4, 'c', 'xx')]
c) Syntax error
SP
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
[‘a’,’b’,’c’,’d’]
G
d)
c)
LO
tuples. [‘a’,’@’,’@d’]
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
-R
Answer: c
3. What will be the output of the following Explanation: The partition function only
Python code? splits for the first parameter along with the
SE
import copy
separator while split function splits for the
a=[10,23,56,[78]] number of times given in the second
b=copy.deepcopy(a) argument but without the separator.
C
a[3][0]=95
a[1]=34
print(b)
5. What will be the output of the following
a) [10,34,56,[95]]
Python code?
b) [10,23,56,[78]]
c) [10,23,56,[95]] a=[1,2,3,4]
d) [10,34,56,[78]] b=[sum(a[0:x+1]) for x in range(0,len(a))
] print(a)
print(b)
a) Syntax error
a) 10 b) [[7], [7], [7]]
b) [1,3,5,7] c) [[7], [], []]
c) 4 d) [[],7, [], []]
d) [1,3,6,10]
Answer: b
Answer: d Explanation: The first line of the code
M
Explanation: The above code returns the creates multiple reference copies of sublist.
cumulative sum of elements in a list. Hence when 7 is appended, it gets appended
O
to all the sublists.
6. What will be the output of the following
Python code?
C
9. What will be the output of the following
Python code?
T.
a="hello"
b=list((x.upper(),len(x)) for x in a) b=[2,3,4,5]
print(b) a=list(filter(lambda x:x%2,b))
O
print(a)
a) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
b) [(‘HELLO’, 5)] a) [2,4]
c) [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
d) Syntax error
SP
b) [ ]
c) [3,5]
d) Invalid arguments for filter function
G
Answer: a
Explanation: Variable x iterates over each Answer: c
LO
letter in string a hence the length of each Explanation: The filter function gives value
letter is 1. from the list b for which the condition is true,
that is, x%2==1.
7. What will be the output of the following
.B
a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a)) lst=[3,4,6,1,2]
] lst[1:2]=[7,8]
print(b) print(lst)
-R
a) 10 a) [3, 7, 8, 6, 1, 2]
b) [1,3,5,7] b) Syntax error
SE
c) 4 c) [3,[7,8],6,1,2]
d) [1,3,6,10] d) [3,4,6,7,8]
Answer: d Answer: a
C
Explanation: The above code returns the Explanation: In the piece of code, slice
cumulative sum of elements in a list. assignment has been implemented. The sliced
list is replaced by the assigned elements in the
8. What will be the output of the following
list. Type in python shell to verify.
Python code?
a=[[]]*3
1. What will be the output of the following
a[1].append(7) Python code?
a=[1,2,3] a.extend([45,67])
b=a.append(4) print(a)
print(a)
print(b) a) [13, 56, 17, [87], 45, 67]
b) [13, 56, 17, 87, 45, 67]
a) c) [13, 56, 17, 87,[ 45, 67]]
d) [13, 56, 17, [87], [45, 67]]
[1,2,3,4]
[1,2,3,4] Answer: a
M
Explanation: The append function simply
b) adds its arguments to the list as it is while
O
extend function extends its arguments and
[1, 2, 3, 4] later appends it.
C
None
4. What is the output of the following piece of
T.
c) Syntax error code?
d) a=list((45,)*4)
O
print((45)*4)
[1,2,3] print(a)
[1,2,3,4]
Answer: b
SP
a)
180
Explanation: Append function on lists
G
doesn’t return anything. Thus the value of b is [(45),(45),(45),(45)]
None.
LO
b)
(45,45,45,45)
.B
>>> a=[14,52,7]
>>>> b=a.copy()
>>> b is a 180
-R
[45,45,45,45]
a) True
b) False d) Syntax error
SE
Answer: b Answer: c
Explanation: List b is just a copy of the Explanation: (45) is an int while (45,) is a
original list. Any copy made in list b will not tuple of one element. Thus when a tuple is
C
M
6. What will be the output of the following Answer: d
Python code? Explanation: unpack(*x) unpacks the list
O
into the separate variables. Now, a=1 and
word1="Apple"
d=4. Thus 5 gets printed.
C
word2="Apple"
list1=[1,2,3]
list2=[1,2,3] 8. What will be the output of the following
T.
print(word1 is word2) Python code?
print(list1 is list2)
O
places = ['Bangalore', 'Mumbai', 'Delhi']
a) <br class="blank" />places1 = places
places2 = places[:]
True
True
SP
<br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
print(places)
G
b) a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
LO
Answer: b
c)
Explanation: places1 is an alias of the list
False places. Hence, any change made to places1 is
17
False
x=[[1],[2]]
Answer: d print(" ".join(list(map(str,x))))
Explanation: In the above case, both the lists
C
a) [1] [2]
are equivalent but not identical as they have
b) [49] [50]
different objects.
c) Syntax error
d) [[1]] [[2]]
Answer: a
7. What will be the output of the following
Explanation: The elements 1 and 2 are first
Python code?
M
a) 561 1
b) 5
O
c) 12 [1,2,3]
d) Syntax error
C
c)
Answer: c
T.
Explanation: First, map converts the number 3
to string and then places the individual digits
[1,2,3]
O
in a list. Then, sum finds the sum of the digits
in the list. The code basically finds the sum of d)
digits in the number.
a) 5 5 1 2 3
b) 5 1 2 3 4
17
c) 2 3 4 5 1
13. What will be the output of the following
d) 2 3 4 5 5
Python code?
-R
Answer: d a = [1, 5, 7, 9, 9, 1]
Explanation: The items having indexes from <br class="blank" />b=a[0]
1 to 4 are shifted forward by one index due to <br class="blank" />x= 0
SE
the first for-loop and the item of index four is for x in range(1, len(a)):
printed again because of the second for-loop. if a[x] > b:
b = a[x]
b= x
12. What will be the output of the following
C
print(b)
Python code?
a) 5
def change(var, lst):
var = 1
b) 3
lst[0] = 44 c) 4
k = 3 d) 0
a = [1, 2, 3]
change(k, a)
Answer: c Answer: c
Explanation: The above piece of code Explanation: print(i) is executed if the given
basically prints the index of the largest character is not a vowel.
element in the list.
2. What is the output of print(k) in the
14. What will be the output of the following following Python code snippet?
Python code?
k = [print(i) for i in my_string if i not
a=["Apple","Ball","Cobra"] in "aeiou"]
M
<br class="blank" />a.sort(key=len) print(k)
print(a)
a) all characters of my_string that aren’t
O
a) [‘Apple’, ‘Ball’, ‘Cobra’] vowels
b) [‘Ball’, ‘Apple’, ‘Cobra’] b) a list of Nones
C
c) [‘Cobra’, ‘Apple’, ‘Ball’] c) list of Trues
d) Invalid syntax for sort() d) list of Falses
T.
Answer: b Answer: b
O
Explanation: The syntax isn’t invalid and the Explanation: print() returns None.
list is sorted according to the length of the
strings in the list since key is given as len.
b) Exception is thrown (‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1),
c) One Two Three (‘D’, 1)]
c) [(‘HELLO WORLD’, 11)]
17
built-in function which returns (0,lst[0]), Explanation: We are iterating over each letter
(1,lst[1]) and so on where lst is a list(iterator). in the string.
SE
1. What will be the output of the following 4. Which of the following is the correct
Python code snippet? expansion of list_1 = [expr(i) for i in list_0 if
func(i)]?
C
M
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
d) none of the mentioned ‘cf’]
O
Answer: c Answer: d
C
Explanation: We have to create an empty list, Explanation: If it were to be executed as a
loop over the contents of the existing list and nested for loop, i would be the outer loop and
T.
check if a condition is satisfied before j the inner loop.
performing some operation and adding it to
the new list. 8. What will be the output of the following
O
Python code snippet?
5. What will be the output of the following
Python code snippet?
Answer: a a) [0, 2, 2, 4]
Explanation: We are iterating over each letter b) [1, 1, 3, 3]
in the string. c) error
d) none of the mentioned
7. What will be the output of the following
Python code snippet? Answer: c
Explanation: Syntax error.
M
1. What will be the output of the following For example if we have a list l=[-65, 2, 7, -99,
O
Python code? -4, 3]
>>> [x for x in l if x<0]
C
l=[1,2,3,4,5] The output would be: [-65, -99, -4].
[x&1 for x in l]
T.
4. What will be the output of the following
a) [1, 1, 1, 1, 1]
Python code?
b) [1, 0, 1, 0, 1]
O
c) [1, 0, 0, 0, 0] s=["pune", "mumbai", "delhi"]
d) [0, 1, 0, 1, 0] [(w.upper(), len(w)) for w in s]
Answer: b
Explanation: In the code shown above, each
SP
a) Error
b) [‘PUNE’, 4, ‘MUMBAI’, 6, ‘DELHI’, 5]
G
of the numbers of the list, that is, 1, 2, 3, 4 c) [PUNE, 4, MUMBAI, 6, DELHI, 5]
and 5 are AND-ed with 1 and the result is d) [(‘PUNE’, 4), (‘MUMBAI’, 6), (‘DELHI’,
LO
l2=[4,5,6]
[x*y for x in l1 for y in l2] length of the word. Hence the output of the
code is: [(‘PUNE’, 4), (‘MUMBAI’, 6),
a) [4, 8, 12, 5, 10, 15, 6, 12, 18] (‘DELHI’, 5)].
-R
l1=[2,4,6]
Answer: c l2=[-2,-4,-6]
Explanation: The code shown above returns for i in zip(l1, l2):
C
M
(6, -6) a) Error
b) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
c)
O
d) [-4, -16, -36]
1 4 7
C
Answer: c
Explanation: The output of the code shown 2 5 8
T.
will be:
(2, -2) 3 6 9
(4, -4)
O
(6, -6) d)
This format is due to the statement print(i).
(2 5 8)
G
(3 6 9)
l1=[10, 20, 30]
LO
d) [0, 0, 0]
Answer: d
Explanation: The code shown above returns 9. What will be the output of the following
-R
Answer: a Answer: c
Explanation: The list comprehension to print Explanation: The list comprehension shown
M
l3=[7,8,9]
for x, y, z in zip(l1, l2, l3): Python code?
print(x, y, z)
O
[ord(ch) for ch in 'abc']
a)
C
a) [97, 98, 99]
1 4 7 b) [‘97’, ‘98’, ‘99’]
T.
c) [65, 66, 67]
2 5 8 d) Error
O
3 6 9
Answer: a
b) Explanation: The list comprehension shown
(1 4 7)
SP
above returns the ASCII value of each
alphabet of the string ‘abc’. Hence the output
is: [97, 98, 99]. Had the string been ‘ABC’,
G
(2 5 8) the output would be: [65, 66, 67].
LO
(3 6 9)
3. What will be the output of the following
Python code?
c) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
d) Error t=32.00
.B
[round((x-32)*5/9) for x in t]
Answer: a
Explanation: The output of the code shown a) [0]
17
above is: b) 0
147 c) [0.00]
258 d) Error
-R
369
This is due to the statement: print(x, y,z). Answer: d
Explanation: The value of t in the code
SE
1. Read the information given below carefully shown above is equal to 32.00, which is a
and write a list comprehension such that the floating point value. ‘Float’ objects are not
output is: [‘e’, ‘o’] iterable. Hence the code results in an error.
C
M
for i in range(1, 101): 8. What is the list comprehension equivalent
if int(i*0.5)==i*0.5: for?
O
print(i)
{x : x is a whole number less than 20, x
a) [i for i in range(1, 100) if int(i*0.5)==
C
is even} (including zero)
(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)== a) [x for x in range(1, 20) if (x%2==0)]
T.
(i*0.5)] b) [x for x in range(0, 20) if (x//2==0)]
c) [i for i in range(1, 101) if int(i*0.5)= c) [x for x in range(1, 20) if (x//2==0)]
O
(i*0.5)] d) [x for x in range(0, 20) if (x%2==0)]
d) [i for i in range(1, 100) if int(i*0.5)=
(i*0.5)]
Answer: b
SP
Answer: d
Explanation: The required list
comprehension will print a whole number,
Explanation: The code shown above prints
G
less than 20, provided that the number is
the value ‘i’ only if it satisfies the condition: even. Since the output list should contain zero
LO
int(i*0.5) is equal to (i*0.5). Hence the as well, the answer to this question is: [x for x
required list comprehension is: [i for i in in range(0, 20) if (x%2==0)].
range(1, 101) if int(i*0.5)==(i*0.5)].
9. What will be the output of the following
.B
M
Answer: b
Explanation: The code shown above returns Python code?
a new list containing only strings which do
O
A = [[1, 2, 3],
not have any punctuation in them. The only [4, 5, 6],
string from the list which does not contain
C
[7, 8, 9]]
any punctuation is ‘good’. Hence the output A[1]
T.
of the code shown above is [‘good’].
a) [4, 5, 6]
1. Which of the following matrices will throw b) [3, 6, 9]
O
an error in Python? c) [1, 4, 7]
a) d) [1, 2, 3]
A = [[1, 2, 3],
[4, 5, 6],
SP
Answer: a
Explanation: We can index the rows and
columns using normal index operations. The
G
[7, 8, 9]]
statement A[1] represents the second row,
that is, the middle row. Hence the output of
LO
(8, 9, 10)]
Answer: c
d) Explanation: The output that is required is 6,
C
M
Explanation: To get a particular column as 7. What will be the output of the following
output, we can simple iterate across the rows Python code?
O
and pull out the desired column, or iterate
through positions in rows and index as we go. A = [[1, 2, 3],
C
Hence the output of the code shown above is: [4, 5, 6],
[2, 5, 8]. [7, 8, 9]]
T.
[[col + 10 for col in row] for row in A]
5. What will be the output of the following
Python code? a) [[11, 12, 13], [14, 15, 16], [17, 18, 19]]
O
A = [[1, 2, 3],
b) Error
c) [11, 12, 13], [14, 15, 16], [17, 18, 19]
[4,
[7,
[A[i][i]
5, 6],
8, 9]]
for i in range(len(A))]
SP
d) [11, 12, 13, 14, 15, 16, 17, 18, 19]
Answer: a
G
a) [1, 5, 9] Explanation: The code shown above shows a
b) [3, 5, 7] list comprehension which adds 10 to each
LO
Explanation: We can also perform tasks like 8. What will be the output of the following
pulling out a diagonal. The expression shown Python code?
17
b) [4, 5, 6]
Python code? c) [3, 5, 7]
l=[[1, 2, 3], [4, 5, 6]]
d) [2, 5, 8]
C
for i in range(len(l)):
for j in range(len(l[i])): Answer: c
l[i][j]+=10 Explanation: This expression scales the
l common index to fetch A[0][2], A[1][1], etc.
We assume the matrix has the same number
a) No output of rows and columns.
b) Error
9. What will be the output of the following is: [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20,
Python code? 30, 40, 50, 60, 70, 80, 90].
A = [[1, 2, 3], 11. What will be the output of the following
[4, 5, 6], Python code?
[7, 8, 9]]
B = [[3, 3, 3],
A = [[1, 2, 3],
[4, 4, 4],
[4, 5, 6],
[5, 5, 5]]
[7, 8, 9]]
[B[row][col]*A[row][col] for row in range
M
B = [[3, 3, 3],
(3) for col in range(3)]
[4, 4, 4],
[5, 5, 5]]
O
a) [3, 6, 9, 16, 20, 24, 35, 40, 45] [[col1 * col2 for (col1, col2) in zip(row
b) Error 1, row2)] for (row1, row2) in zip(A, B)]
C
c) [0, 30, 60, 120, 160, 200, 300, 350, 400]
d) 0 a) [0, 30, 60, 120, 160, 200, 300, 350, 400]
T.
b) [[3, 6, 9], [16, 20, 24], [35, 40, 45]]
Answer: a c) No output
Explanation: In the code shown above, we d) Error
O
have used list comprehension to combine
values of multiple matrices. We have Answer: b
multiplied the elements of the matrix B with
that of the matrix A, in the range(3). Hence
the output of this code is: [3, 6, 9, 16, 20, 24,
SP
Explanation: The list comprehension shown
above results in the output: [[3, 6, 9], [16, 20,
24], [35, 40, 45]].
G
35, 40, 45].
12. What will be the output of the following
LO
for row in A:
for col in row: zip(A, B)
r.append(col+10)
r a) Address of the zip object
-R
M
c) {1, 2, 3}
5. What will be the output of the following
d) {}
Python code?
O
Answer: b
1. >>>t = (1, 2, 4, 3, 8, 9)
Explanation: Tuples are represented with
C
round brackets. 2. >>>[t[i] for i in range(0, len(t),
T.
2)]
2. Suppose t = (1, 2, 4, 3), which of the
following is incorrect? a) [2, 3, 9]
O
a) print(t[3]) b) [1, 2, 4, 3, 8, 9]
b) t[3] = 45 c) [1, 4, 8]
c) print(max(t))
d) print(len(t)) SP
d) (1, 4, 8)
Answer: c
Answer: b Explanation: Execute in the shell to verify.
G
Explanation: Values cannot be modified in
the case of tuple, that is, tuple is immutable. 6. What will be the output of the following
LO
Python code?
3. What will be the output of the following
Python code? 1. d = {"john":40, "peter":45}
.B
1. >>>t=(1,2,4,3) 2. d["john"]
17
2. >>>t[1:3] a) 40
b) 45
a) (1, 2) c) “john”
b) (1, 2, 4) d) “peter”
-R
c) (2, 4)
d) (2, 4, 3) Answer: a
Explanation: Execute in the shell to verify.
SE
Answer: c
Explanation: Slicing in tuples takes place 7. What will be the output of the following
just as it does in strings. Python code?
C
c) (1, 1, 2, 2) 3. numberGames[(4,2,1)] = 10
d) [1, 1, 2, 2]
4. numberGames[(1,2)] = 12
Answer: a
5. sum = 0
Explanation: * operator concatenates tuple.
6. for k in numberGames:
8. What will be the output of the following
Python code? 7. sum += numberGames[k]
M
1. >>>t1 = (1, 2, 4, 3) 8. print len(numberGames) + sum
2. >>>t2 = (1, 2, 3, 4)
O
a) 30
b) 24
3. >>>t1 < t2
C
c) 33
d) 12
a) True
T.
b) False Answer: c
c) Error Explanation: Tuples can be used for keys
O
d) None into dictionary. The tuples can have mixed
length and the order of the items in the tuple
Answer: b
Explanation: Elements are compared one by
one in this case.
SP
is considered when comparing the equality of
the keys.
G
1. What is the data type of (1)?
9. What will be the output of the following
a) Tuple
Python code?
LO
b) Integer
1. >>>my_tuple = (1, 2, 3, 4) c) List
d) Both tuple and integer
2. >>>my_tuple.append( (5, 6, 7) )
.B
Answer: b
3. >>>print len(my_tuple) Explanation: A tuple of one element must be
created as (1,).
17
a) 1
b) 2 2. If a=(1,2,3,4), a[1:-1] is _________
c) 5 a) Error, tuple slicing doesn’t exist
-R
d) Error b) [2,3]
c) (2,3,4)
Answer: d d) (2,3)
SE
returns (2,3).
10. What will be the output of the following
Python code? 3. What will be the output of the following
Python code?
1. numberGames = {}
>>> a=(1,2,(4,5))
2. numberGames[(1,2,4)] = 8 >>> b=(1,2,(3,4))
>>> a<b
a) False c) 12
b) True d) 9
c) Error, < operator is not valid for tuples
d) Error, < operator is valid for tuples but not Answer: c
if there are sub-tuples Explanation: In the above case, 3 is the
starting value to which the sum of the tuple is
Answer: a added to.
Explanation: Since the first element in the
sub-tuple of a is larger that the first element 7. Is the following Python code valid?
M
in the subtuple of b, False is printed.
>>> a=(1,2,3,4)
O
>>> del a
4. What will be the output of the following
Python code?
a) No because tuple is immutable
C
>>> a=("Check")*3 b) Yes, first element in the tuple is deleted
c) Yes, the entire tuple is deleted
T.
>>> a
d) No, invalid syntax for del method
a) (‘Check’,’Check’,’Check’)
O
b) * Operator not valid for tuples Answer: c
c) (‘CheckCheckCheck’) Explanation: The command del a deletes the
d) Syntax error
Answer: c
SP
entire tuple.
element.
d) Invalid type
5. What will be the output of the following
Python code? Answer: b
.B
>>> a=(0,1,2,3,4)
d) Error as tuple is immutable >>> b=slice(0,2)
>>> a[b]
SE
Answer: d
Explanation: ‘tuple’ object doesn’t support a) Invalid syntax for slicing
item deletion. b) [0,2]
c) (0,1)
C
M
Answer: a >>> a,b=1,2,3
Explanation: Zip function combines
O
individual elements of two iterables into a) Yes, this is an example of tuple unpacking.
tuples. Execute in Python shell to verify.
C
a=1 and b=2
b) Yes, this is an example of tuple unpacking.
1. Is the following Python code valid?
T.
a=(1,2) and b=3
c) No, too many values to unpack
>>> a,b,c=1,2,3
d) Yes, this is an example of tuple unpacking.
O
>>> a,b,c
a=1 and b=(2,3)
a) Yes, [1,2,3] is printed
b) No, invalid syntax
c) Yes, (1,2,3) is printed
d) 1 is printed
SP
Answer: c
Explanation: For unpacking to happen, the
number of values of the right hand side must
G
be equal to the number of variables on the left
Answer: c hand side.
LO
a = ('check',)
>>> c
n = 2
for i in range(int(n)):
a = (a,) a) (4,6)
b) (1,2,3,4)
-R
print(a)
c) Error as tuples are immutable
a) Error, tuples are immutable d) None
SE
b)
Answer: b
(('check',),) Explanation: In the above piece of code, the
values of the tuples aren’t being changed.
C
((('check',),),)
Both the tuples are simply concatenated.
c) ((‘check’,)’check’,)
5. What will be the output of the following
d)
Python code?
(('check',)’check’,)
>>> a,b=6,7
((('check',)’check’,)’check’,) >>> a,b=b,a
>>> a,b
M
c) None
6. What will be the output of the following
d) Error, tuple has no attribute sort
Python code?
O
>>> import collections
Answer: d
Explanation: A tuple is immutable thus it
C
>>> a=collections.namedtuple('a',['i','j'
]) doesn’t have a sort attribute.
>>> obj=a(i=4,j=7)
T.
>>> obj 10. Is the following Python code valid?
a) a(i=4, j=7)
O
>>> a=(1,2,3)
b) obj(i=4, j=7) >>> b=a.update(4,)
c) (4,7)
d) An exception is thrown
Answer: a
SP
a) Yes, a=(1,2,3,4) and b=(1,2,3,4)
b) Yes, a=(1,2,3) and b=(1,2,3,4)
c) No because tuples are immutable
G
Explanation: The above piece of code d) No because wrong syntax for update()
illustrates the concept of named tuples. method
LO
>>> a
>>> a=2,3,4,5
>>> a a) [(1, 2), (2, 4), (3, 9)]
SE
b) [(2,4),(1,2),(3,9)]
a) Yes, 2 is printed c) Error because tuples are immutable
b) Yes, [2,3,4,5] is printed d) Error, tuple has no sort attribute
c) No, too many values to unpack
C
M
specifying keys and values. 5. What will be the output of the following
Python code snippet?
O
2. What will be the output of the following
Python code snippet? 1. d1 = {"john":40, "peter":45}
C
1. d = {"john":40, "peter":45} 2. d2 = {"john":466, "peter":45}
T.
3. d1 > d2
a) “john”, 40, 45, and “peter”
b) “john” and “peter”
O
a) True
c) 40 and 45
b) False
d) d = (40:”john”, 45:”peter”)
Answer: b
Explanation: Dictionaries appear in the form
SP
c) Error
d) None
Answer: c
G
of keys and values.
Explanation: Arithmetic > operator cannot
be used with dictionaries.
LO
2. d["john"]
a) True
b) False a) 40
c) None b) 45
-R
d) Error c) “john”
d) “peter”
Answer: a
SE
M
d) d.len()
2. Which of the following is not a declaration
O
Answer: b of the dictionary?
Explanation: Execute in the shell to verify. a) {1: ‘A’, 2: ‘B’}
C
b) dict([[1,”A”],[2,”B”]])
9. What will be the output of the following c) {1,”A”,2”B”}
T.
Python code snippet? d) { }
O
Explanation: Option c is a set, not a
2. print(list(d.keys())) dictionary.
a) [“john”, “peter”]
b) [“john”:40, “peter”:45]
SP
3. What will be the output of the following
Python code snippet?
G
c) (“john”, “peter”)
d) (“john”:40, “peter”:45) a={1:"A",2:"B",3:"C"}
LO
Python raises a KeyError exception and j iterate over the keys and values of the
b) It is executed fine and no exception is dictionary respectively.
raised, and it returns None
SE
c) Since “susan” is not a key in the set, 4. What will be the output of the following
Python raises a KeyError exception Python code snippet?
d) Since “susan” is not a key in the set, a={1:"A",2:"B",3:"C"}
C
Answer: c a) 1
Explanation: Execute in the shell to verify. b) A
c) 4
1. Which of these about a dictionary is false? d) Invalid syntax for get method
a) The values of a dictionary can be accessed
using keys
Answer: b c) Error
Explanation: The get() method returns the d) [1,3,6,10]
value of the key if the key is present in the
dictionary and the default value(second Answer: a
parameter) if the key isn’t present in the Explanation: setdefault() will set
dictionary. dict[key]=default if key is not already in the
dictionary.
5. What will be the output of the following
Python code snippet? 8. What will be the output of the following
M
Python code?
a={1:"A",2:"B",3:"C"}
O
print(a.get(5,4)) a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a) Error, invalid syntax a.update(b)
C
b) A print(a)
T.
c) 5
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
d) 4
b) Method update() doesn’t exist for
O
Answer: d dictionaries
Explanation: The get() method returns the c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
default value(second parameter) if the key
isn’t present in the dictionary. SP
d) {4: ‘D’, 5: ‘E’}
Answer: c
Explanation: update() method adds
G
6. What will be the output of the following
Python code snippet? dictionary b’s key-value pairs to dictionary a.
Execute in python shell to verify.
LO
a={1:"A",2:"B",3:"C"}
print(a.setdefault(3)) 9. What will be the output of the following
Python code?
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
.B
b) C a={1:"A",2:"B",3:"C"}
c) {1: 3, 2: 3, 3: 3} b=a.copy()
17
b[2]="D"
d) No method called setdefault() exists for print(a)
dictionary
a) Error, copy() method doesn’t exist for
Answer: b
-R
dictionaries
Explanation: setdefault() is similar to get() b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
but will set dict[key]=default if key is not c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
SE
M
Answer: d
Explanation: The clear() method clears all
14. What will be the output of the following
the key-value pairs in the dictionary.
O
Python code?
11. Which of the following isn’t true about
C
a={1:"A",2:"B",3:"C"}
dictionary keys? for i in a:
a) More than one key isn’t allowed
T.
print(i,end=" ")
b) Keys must be immutable
c) Keys must be integers a) 1 2 3
O
d) When duplicate keys encountered, the last b) ‘A’ ‘B’ ‘C’
assignment wins c) 1 ‘A’ 2 ‘B’ 3 ‘C’
Answer: c
Explanation: Keys of a dictionary may be
SP
d) Error, it should be: for i in a.items():
Answer: a
any data type that is immutable. Explanation: The variable i iterates over the
G
keys of the dictionary and hence the keys are
12. What will be the output of the following printed.
LO
Python code?
15. What will be the output of the following
a={1:5,2:3,3:4} Python code?
.B
a.pop(3)
print(a) >>> a={1:"A",2:"B",3:"C"}
>>> a.items()
17
a) {1: 5}
b) {1: 5, 2: 3} a) Syntax error
c) Error, syntax error for pop() method b) dict_items([(‘A’), (‘B’), (‘C’)])
d) {1: 5, 3: 4} c) dict_items([(1,2,3)])
-R
value pair for the key mentioned in the pop() Explanation: The method items() returns list
method. of tuples with each tuple having a key-value
pair.
C
M
Python code snippet? keys present since the key ‘Apple’ is
repeated. Thus, the length of the dictionary is
O
>>> a={1:"A",2:"B",3:"C"} 2.
>>> del a
C
5. What will be the output of the following
a) method del doesn’t exist for the dictionary
Python code snippet?
b) del deletes the values in the dictionary
T.
c) del deletes the entire dictionary a = {}
d) del deletes the keys in the dictionary a[1] = 1
O
a['1'] = 2
Answer: c a[1]=a[1]+1
Explanation: del deletes the entire dictionary
and any further attempt to access it will throw
an error.
SP
count = 0
for i in a:
count += a[i]
print(count)
G
3. If a is a dictionary with some key-value a) 1
pairs, what does a.popitem() do?
LO
b) 2
a) Removes an arbitrary element c) 4
b) Removes all the key-value pairs d) Error, the keys can’t be a mixture of letters
c) Removes the key-value pair for the key and numbers
.B
given as an argument
d) Invalid method for dictionary Answer: c
Explanation: The above piece of code
17
letters = {}
total={} comb = {}
def insert(items): numbers[1] = 56
if items in total: numbers[3] = 7
C
M
Answer: c
test = {1:'A', 2:'B', 3:'C'}
Explanation: The value of key 1 is 4 since 1
O
test = {}
print(len(test)) and 1.0 are the same. Then, the function
count() gives the sum of all the values of the
C
a) 0 keys (2+4).
b) None
T.
c) 3 10. What will be the output of the following
d) An exception is thrown Python code snippet?
O
Answer: a a={}
a['a']=1
Explanation: In the second line of code, the
dictionary becomes an empty dictionary.
Thus, length=0.
SP
a['b']=[2,3,4]
print(a)
G
a) Exception is thrown
8. What will be the output of the following b) {‘b’: [2], ‘a’: 1}
Python code snippet?
LO
a) 0
b) 2 11. What will be the output of the following
c) Error as the key-value pair of 1:’A’ is Python code snippet?
-R
already deleted
d) 1 >>>import collections
>>> a=collections.Counter([1,1,2,3,3,4,4,
SE
Answer: b 4])
>>> a
Explanation: After the key-value pair of
1:’A’ is deleted, the key-value pair of 1:’D’ is a) {1,2,3,4}
added.
C
b) Counter({4, 1, 3, 2})
c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
9. What will be the output of the following
d) {4: 3, 1: 2, 3: 2, 2: 1}
Python code snippet?
a = {}
Answer: c
a[1] = 1 Explanation: The statement
a['1'] = 2 a=collections.OrderedDict() generates a
a[1.0]=4 dictionary with the number as the key and the
M
>>> b=collections.Counter([3,4,4,5,5,5])
a) Counter({4: 3, 2: 2, 3: 1}) >>> a&b
b) {3:1}
O
c) {4:3} a) Counter({3: 12, 4: 1, 5: 1})
d) [(4, 3)] b) Counter({3: 1, 4: 1, 5: 1})
C
c) Counter({4: 2})
Answer: d d) Counter({5: 1})
T.
Explanation: The most_common() method
returns the n number key-value pairs where Answer: b
O
the value is the most recurring. Explanation: a&b returns the pair of keys
and the lowest recurring value.
13. What will be the output of the following
Python code snippet?
>>>import collections
SP
1. The following Python code is invalid.
class demo(dict):
G
>>> b=collections.Counter([2,2,3,4,4,4]) def __test__(self,key):
>>> b.most_common(1) return []
LO
a = demo()
a) Counter({4: 3, 2: 2, 3: 1}) a['test'] = 7
print(a)
b) {3:1}
c) {4:3} a) True
.B
Answer: b
Explanation: The most_common() method Explanation: The output of the code is:
returns the n number key-value pairs where {‘test’:7}.
the value is the most recurring.
-R
count={}
>>> import collections count[(1,2,4)] = 5
>>> a=collections.Counter([2,2,3,3,3,4]) count[(4,2,1)] = 7
>>> b=collections.Counter([2,2,3,4,4]) count[(1,2)] = 6
C
Answer: c Answer: d
Explanation: Tuples can be made keys of a Explanation: Dictionary comprehension is
dictionary. Length of the dictionary is 3 as the implemented in the above piece of code.
value of the key (4,2,1) is modified to 2. The
value of the variable tot is 5+6+2=13. 6. What will be the output of the following
Python code?
M
3. What will be the output of the following
Python code? >>> a={}
O
>>> a.fromkeys([1,2,3],"check")
a={}
a) Syntax error
C
a[2]=1
a[1]=[2,3,4] b) {1:”check”,2:”check”,3:”check”}
print(a[1][1]) c) “check”
T.
d) {1:None,2:None,3:None}
a) [2,3,4]
O
b) 3 Answer: b
c) 2 Explanation: The dictionary takes values of
d) An exception is thrown
Answer: b
Explanation: Now, a={1:[2,3,4],2:1} . a[1]
SP
keys from the list and initializes it to the
default value (value given in the second
parameter). Execute in Python shell to verify.
G
[1] refers to second element having key 1. 7. What will be the output of the following
Python code?
LO
>>> sorted(a) a) { }
b) False
a) [‘A’,’B’,’C’]
17
c) True
b) [‘B’,’C’,’A’] d) An exception is thrown
c) [5,7,9]
d) [9,5,7] Answer: c
-R
dictionary is empty.
in the dictionary.
8. If b is a dictionary, what does any(b) do?
5. What will be the output of the following a) Returns True if any key of the dictionary is
C
Answer: a Answer: a
Explanation: Method any() returns True if Explanation: The values of a dictionary can
any key of the dictionary is true and False if be accessed through the keys only if the keys
the dictionary is empty. exist in the dictionary.
9. What will be the output of the following 12. What will be the output of the following
Python code? Python code?
M
>>> b=dict(zip(a.values(),a.keys())) >>> a=dict()
>>> b >>> a=collections.defaultdict(int)
>>> a[1]
O
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown a) 1
C
c) {‘a’: ‘b’: ‘c’: } b) 0
d) {1: ‘a’, 2: ‘b’, 3: ‘c’} c) An exception is thrown
T.
d) ‘ ‘
Answer: d
O
Explanation: The above piece of code inverts Answer: b
the key-value pairs in the dictionary. Explanation: The statement
Answer: b
Explanation: Dictionary comprehension and a) An exception is thrown since the dictionary
string concatenation is implemented in the is empty
-R
Python code?
Answer: b
>>> a=dict() Explanation: The statement
C
M
Answer: d 2. To open a file c:\scores.txt for writing, we
Explanation: The statement use ____________
O
a=collections.defaultdict(lambda: x) gives the a) outfile = open(“c:\scores.txt”, “w”)
default value of x even if the keys don’t exist b) outfile = open(“c:\scores.txt”, “w”)
C
in the dictionary. c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\scores.txt”, “w”)
T.
15. What will be the output of the following
Python code? Answer: b
Explanation: w is used to indicate that file is
O
>>> import collections to be written to.
>>> a=collections.OrderedDict((str(x),x)
for
>>>
x in range(3))
a SP
3. To open a file c:\scores.txt for appending
data, we use ____________
a) outfile = open(“c:\scores.txt”, “a”)
G
a) {‘2’:2, ‘0’:0, ‘1’:1}
b) outfile = open(“c:\scores.txt”, “rw”)
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
c) outfile = open(file = “c:\scores.txt”, “w”)
LO
c) An exception is thrown
d) outfile = open(file = “c:\scores.txt”, “w”)
d) ‘ ‘
Answer: a
Answer: b
Explanation: a is used to indicate that data is
.B
a) infile.read(2) c) infile.readline()
b) infile.read() d) infile.readlines()
c) infile.readline()
d) infile.readlines() Answer: c
Explanation: Execute in the shell to verify.
Answer: a
Explanation: Execute in the shell to verify. 9. To read the remaining lines of the file from
a file object infile, we use ____________
6. To read the entire remaining contents of the a) infile.read(2)
M
file as a string from a file object infile, we use b) infile.read()
____________ c) infile.readline()
O
a) infile.read(2) d) infile.readlines()
b) infile.read()
C
c) infile.readline() Answer: d
d) infile.readlines() Explanation: Execute in the shell to verify.
T.
Answer: b 10. The readlines() method returns
Explanation: read function is used to read all ____________
O
the lines in a file. a) str
b) a list of lines
7. What will be the output of the following
Python code? SP
c) a list of single characters
d) a list of integers
G
1. f = None Answer: b
Explanation: Every line is stored in a list and
LO
a) True
Answer: a
b) False
Explanation: Python provides two built-in
c) None
functions to read a line of text from standard
SE
M
Received input is : Hello 4. Which one of the following is not attributes
of file?
O
c)
a) closed
b) softspace
C
Enter your input: Hello Python
c) rename
Received input is : Python d) mode
T.
d) None of the mentioned Answer: c
O
Explanation: rename is not the attribute of
Answer: a file rest all are files attributes.
Explanation: The raw_input([prompt])
function reads one line from standard input
and returns it as a string. This would prompt
you to enter any string and it would display
SP
Attribute
file.closed
Description
Received input is : [10, 30, 20, 40] 6. What is the current syntax of rename() a
file?
c) a) rename(current_file_name,
new_file_name)
b) rename(new_file_name, 14.
current_file_name,)
c) rename(()(current_file_name, 15. # Close opened file
new_file_name)) 16. fo.close()
d) none of the mentioned
a) Compilation Error
Answer: a
b) Syntax Error
Explanation: This is the correct syntax which
c) Displays Output
has shown below.
M
d) None of the mentioned
rename(current_file_name, new_file_name)
Answer: c
O
7. What is the current syntax of remove() a
Explanation: It displays the output as shown
file?
below. The method next() is used when a file
C
a) remove(file_name)
is used as an iterator, typically in a loop, the
b) remove(new_file_name, next() method is called repeatedly. This
T.
current_file_name,)
method returns the next input line, or raises
c) remove(() , file_name))
StopIteration when EOF is hit.
d) none of the mentioned
O
Output:
Answer: a
Explanation: remove(file_name)
1. fo = open("foo.txt", "rw+")
2. print "Name of the file: ", fo.name
Line No 2 - This is 3rd line
.B
3.
4. # Assuming file has following 5 lin
17
Following is the syntax for seek() method: 2. What will be the output of the following
fileObject.seek(offset[, whence]) Python code? (If entered name is sanfoundry)
M
values are 1 which means seek relative to the
current position and 2 means seek relative to 5. c = sys.stdin.read(1)
O
the file’s end.
6. if c == '\n':
C
10. What is the use of truncate() method in
file? 7. break
T.
a) truncates the file size 8. name = name + c
b) deletes the content of the file
c) deletes the file size 9.
O
d) none of the mentioned
10. print 'Your name is:', name
Answer: a
Explanation: The method truncate() truncates
the file size. Following is the syntax for
SP
a) sanfoundry
b) sanfoundry, sanfoundry
G
truncate() method: c) San
fileObject.truncate( [ size ]) d) None of the mentioned
LO
Parameters Answer: a
size — If this optional argument is present, Explanation: In order to work with standard
the file is truncated to (at most) that size. I/O streams, we must import the sys module.
.B
file?
a) Standard Input our name and press enter. The enter key
b) Standard Output generates the new line character: \n.
c) Standard Errors Output:
-R
Explanation: Standard input, standard output 3. What will be the output of the following
and standard error. Standard input is the data Python code?
that goes to the program. The standard input
C
Answer: d Answer: b
Explanation: None Explanation: We have been working with
simple textual data. What if we are working
M
Output:
Hello with objects rather than simple text? For such
Python situations, we can use the pickle module. This
O
module serializes Python objects. The Python
objects are converted into byte streams and
C
written to text files. This process is called
4. Which of the following mode will refer to pickling. The inverse operation, reading from
T.
binary data? a file and reconstructing objects is called
a) r deserializing or unpickling.
O
b) w
c) + 7. What is the correct syntax of open()
function?
d) b
Answer:d
SP
a) file = open(file_name [, access_mode][,
buffering])
b) file object = open(file_name [,
Explanation: Mode Meaning is as explained
G
below: access_mode][, buffering])
r Reading c) file object = open(file_name)
LO
d) All of the mentioned value that contains the name of the file that
you want to access.
Answer: a access_mode: The access_mode determines
SE
Explanation: Pickle is the standard the mode in which the file has to be opened,
mechanism for object serialization. Pickle i.e., read, write, append, etc. A complete list
uses a simple stack-based virtual machine that of possible values is given below in the table.
records the instructions used to reconstruct This is optional parameter and the default file
C
the object. This makes pickle vulnerable to access mode is read (r).
security risks by malformed or maliciously buffering: If the buffering value is set to 0, no
constructed data, that may cause the buffering will take place. If the buffering
deserializer to import arbitrary modules and value is 1, line buffering will be performed
instantiate any object. while accessing a file. If you specify the
buffering value as an integer greater than 1,
then buffering action will be performed with
M
2. print "Name of the file: ", fo.name
Following is the syntax for readlines()
3. fo.flush() method:
O
fileObject.readlines( sizehint );
4. fo.close() Parameters
C
sizehint — This is the number of bytes to be
a) Compilation Error read from the file.
T.
b) Runtime Error
c) No Output 1. In file handling, what does this terms
O
d) Flushes the file when closing them means “r, a”?
a) read, append
Answer: d
Explanation: The method flush() flushes the
internal buffer. Python automatically flushes
the files when closing them. But you may
SP
b) append, read
c) write, append
d) none of the mentioned
G
want to flush the data before closing any file. Answer: a
Explanation: r- reading, a-appending.
LO
c) fileObject.writelines(sequence) b) Write
d) none of the mentioned c) Append
d) None of the mentioned
17
Answer: c
Explanation: The method writelines() writes Answer: b
a sequence of strings to the file. The sequence Explanation: This opens the file for writing.
-R
can be any iterable object producing strings, It will create the file if it doesn’t exist, and if
typically a list of strings. There is no return it does, it will overwrite it.
value. fh = open(“filename_here”, “w”).
SE
Syntax
Following is the syntax for writelines() 3. What is the use of “a” in file handling?
method: a) Read
fileObject.writelines( sequence ). b) Write
C
c) Append
10. Correct syntax of file.readlines() is? d) None of the mentioned
a) fileObject.readlines( sizehint );
b) fileObject.readlines(); Answer: c
c) fileObject.readlines(sequence) Explanation: This opens the fhe file in
d) none of the mentioned appending mode. That means, it will be open
for writing and everything will be written to
M
python?
Answer: a a) Close()
O
Explanation: The read function reads all b) Stop()
characters fh = open(“filename”, “r”) c) End()
C
content = fh.read(). d) Closefile()
T.
5. Which function is used to read single line Answer: a
from file? Explanation: f.close()to close it and free up
a) Readline() any system resources taken up by the open
O
b) Readlines() file.
c) Readstatement()
d) Readfullline()
Answer: b
SP
9. Is it possible to create a text file in python?
a) Yes
b) No
G
Explanation: The readline function reads a c) Machine dependent
single line from the file fh = open(“filename”, d) All of the mentioned
LO
“r”)
content = fh.readline(). Answer: a
Explanation: Yes we can create a file in
6. Which function is used to write all the python. Creation of file is as shown below.
.B
M
existing file if the file exists. If the file does Answer: d
not exist, creates a new file for reading and Explanation: fp.size has not been
O
writing. implemented.
C
1. Which of the following is not a valid mode 5. How do you close a file object (fp)?
to open a file? a) close(fp)
T.
a) ab b) fclose(fp)
b) rw c) fp.close()
d) fp.__close__()
O
c) r+
d) w+
Answer: c
Answer: b
Explanation: Use r+, w+ or a+ to perform
both read and write operations using a single
SP
Explanation: close() is a method of the file
object.
G
file object. 6. How do you get the current position within
the file?
LO
c) in w+ the pointer is initially placed at the Explanation: It gives the current position as
beginning of the file and the pointer is at the an offset from the start of file.
end for r+
7. How do you rename a file?
-R
Explanation: none.
d) os.set_name(existing_name, new_name)
3. How do you get the name of a file from a
file object (fp)? Answer: b
C
M
d) none of the mentioned
class foo:
def __init__(self, x):
O
Answer: a self.x = x
Explanation: 0 indicates that the offset is def __less__(self, other):
C
with respect to the start. if self.x > other.x:
return False
T.
10. What happens if no arguments are passed else:
return True
to the seek function?
a) file position is set to the start of file
O
c)
b) file position is set to the end of file
c) file position remains unchanged
d) error
Answer: d
SP
class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
G
if self.x < other.x:
Explanation: seek() takes at least one return True
argument. else:
LO
return False
1. Which function is called when the
following Python code is executed? d)
.B
Answer: d Answer: c
SE
Explanation: Both str(f) and format(f) call Explanation: __lt__ overloads the <
f.__str__(). operator>.
print True?
3. Which function overloads the + operator?
a = foo(2) a) __add__()
b = foo(3) b) __plus__()
print(a < b)
c) __sum__()
a) d) none of the mentioned
Answer: a Answer: a
Explanation: Refer documentation. Explanation: The function __add__() is
called first since it is within the bracket. The
4. Which operator is overloaded by function __str__() is then called on the object
__invert__()? that we received after adding A and B.
a) !
b) ~ 9. Which operator is overloaded by the
c) ^ __or__() function?
d) – a) ||
M
b) |
Answer: b c) //
O
Explanation: __invert__() overloads ~. d) /
C
5. Which function overloads the == operator? Answer: b
a) __eq__() Explanation: The function __or__()
T.
b) __equ__() overloads the bitwise OR operator |.
c) __isequal__()
d) none of the mentioned 10. Which function overloads the // operator?
O
a) __div__()
Answer: a b) __ceildiv__()
Explanation: The other two do not exist.
c) !=
d) none of the mentioned
TOPIC 5.2 EXCEPTION
Answer: d HANDLING
.B
Answer: d
Explanation: __rshift__() overloads the >> Explanation: There has to be at least one
operator. except statement.
C
8. Let A and B be objects of class Foo. Which 2. When will the else part of try-except-else
functions are called when print(A + B) is be executed?
executed? a) always
a) __add__(), __str__() b) when an exception occurs
b) __str__(), __add__() c) when no exception occurs
c) __sum__(), __str__() d) when an exception occurs in to except
d) __str__(), __sum__() block
M
# Do something
finally: executed.
# Do something
O
7. What will be the output of the following
a) no, there is no such thing as finally Python code?
C
b) no, finally cannot be used with except
c) no, finally must come before except def foo():
T.
d) yes try:
return 1
finally:
Answer: b
O
return 2
Explanation: Refer documentation. k = foo()
print(k)
4. Is the following Python code valid?
try:
SP
a) 1
b) 2
G
# Do something c) 3
except:
# Do something d) error, there is more than one return
LO
b) no, else cannot be used with except even there is a return statement in the try
c) no, else must come before except block.
17
d) yes
8. What will be the output of the following
Answer: d Python code?
Explanation: Refer documentation.
-R
def foo():
5. Can one block of except statements handle try:
print(1)
multiple exception?
SE
finally:
a) yes, like except TypeError, SyntaxError print(2)
[,…] foo()
b) yes, like except [TypeError, SyntaxError]
C
c) no a) 1 2
d) none of the mentioned b) 1
c) 2
Answer: a d) none of the mentioned
Explanation: Each type of exception can be
specified directly. There is no need to put it in Answer: a
a list. Explanation: No error occurs in the try block
9. What will be the output of the following 2. What will be the output of the following
Python code? Python code?
try: x=10
if '1' != 1: y=8
raise "someError" assert x>y, 'X too small'
M
else:
print("someError has not occurre a) Assertion Error
d") b) 10 8
O
except "someError":
print ("someError has occurred") c) No output
d) 108
C
a) someError has occurred
Answer: c
T.
b) someError has not occurred
c) invalid code Explanation: The code shown above results
d) none of the mentioned in an error if and only if x<y. However, in the
O
above case, since x>y, there is no error. Since
Answer: c there is no print statement, hence there is no
Explanation: A new exception class must
inherit from a BaseException. There is no
such inheritance here.
SP
output.
a) we get a True
def f(x):
b) we get a False yield x+1
c) an TypeError occurs g=f(8)
d) a ValueError occurs print(next(g))
.B
Answer: b a) 8
Explanation: It simply evaluates to False and b) 9
17
M
f(x, 4)
d) No output finally:
print('after f')
O
Answer: d print('after f?')
Explanation: The code shown above will not a()
C
yield any output. This is because when we try
to yield 9, and there is no next(g), the a) No output
T.
iteration stops. Hence there is no output. b) after f?
c) error
5. What will be the output of the following d) after f
O
Python code?
Answer: c
def f(x):
yield x+1
print("test")
SP
Explanation: This code shown above will
result in an error simply because ‘f’ is not
defined. ‘try’ and ‘finally’ are keywords used
G
yield x+2
in exception handling.
g=f(10)
print(next(g))
LO
for i in range(5):
yield i
11
g=f(8)
17
print(list(g))
test
12 a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
-R
c) c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
11
SE
Answer: a
test
Explanation: The output of the code shown
d) 11 above is a list containing whole numbers in
C
l2=[4, 5, 6] a=False
l=itertools.chain(l1, l2) while not a:
print(next(l1)) try:
f_n = input("Enter file name")
a) ‘list’ object is not iterator i_f = open(f_n, 'r')
b) ‘tuple’ object is not iterator except:
print("Input file not found")
c) ‘list’ object is iterator
d) ‘tuple’ object is iterator a) No error
b) Assertion error
M
Answer: b
c) Input output error
Explanation: The error raised in the code
d) Name error
shown above is that: ‘tuple’ object is not
O
iterator. Had we given l2 as argument to next, Answer: a
the error would have been: ‘list’ object is not
C
Explanation: In the code shown above, if the
iterator. input file in not found, then the statement:
T.
“Input file not found” is printed on the screen.
9. Which of the following is not an exception
The user is then prompted to reenter the file
handling keyword in Python?
name. Error is not thrown.
O
a) try
b) except 2. What will be the output of the following
c) accept
d) finally SP
Python code?
lst = [1, 2, 3]
Answer: c
G
lst[3]
Explanation: The keywords ‘try’, ‘except’
a) NameError
LO
list is 2.
b) class <‘iteration’>
c) class <’range’> 3. What will be the output of the following
SE
results in a name error. This is because the ctorial you want to find"))
name ‘t’ is not defined. print(math.factorial(num))
M
a) NameError Explanation: The first code results in a
b) IndexError ValueError. This is because when we enter the
O
c) ValueError input as -6, we are trying to find the factorial
d) TypeError of a negative number, which is not possible.
C
The second code results in a NameError. This
Answer: d is because we have not imported the math
T.
Explanation: The line of code shown above module. Hence the name ‘math’ is undefined.
will result in a type error. This is because the
operand ‘+’ is not supported when we 7. What will be the output of the following
O
combine the data types ‘int’ and ‘str’. Sine Python code?
this is exactly what we have done in the code
shown above, a type error is thrown.
int('65.43') a) ValueError
b) Invalid
a) ImportError c) 6
b) ValueError d) ValueError(“Invalid”)
.B
c) TypeError
d) NameError Answer: c
Explanation: In the code shown above, since
17
there is an invalid literal for int() with base the value had been above 12 and less than 1, a
10: ’65.43’. ValueError would have been thrown.
SE
6. Compare the following two Python codes 8. What will be the output of the following
shown below and state the output if the input Python code if the input entered is 6?
entered in each case is -6?
C
valid = False
CODE 1 while not valid:
import math try:
num=int(input("Enter a number of whose fa n=int(input("Enter a number"))
ctorial you want to find")) while n%2==0:
print(math.factorial(num)) print("Bye")
valid = True
CODE 2 except ValueError:
num=int(input("Enter a number of whose fa print("Invalid")
M
number has been given as input. If an odd c) AssignmentError
number had been given as input, then there d) ValueError
O
would have been no output.
Answer: c
C
9. Identify the type of error in the following Explanation: NameError, IOError and
Python codes? ValueError are standard exceptions in Python
T.
whereas Assignment error is not a standard
Print(“Good Morning”) exception in Python.
print(“Good night)
O
12. Syntax errors are also known as parsing
a) Syntax, Syntax
errors.
b) Semantic, Syntax
c) Semantic, Semantic
d) Syntax, Semantic
SP
a) True
b) False
G
Answer: a
Answer: b Explanation: Syntax errors are known as
LO
b) a special function
10. Which of the following statements is true?
c) a standard module
a) The standard exceptions are automatically d) a module
imported into Python programs
-R
Answer: d Answer: c
Explanation: IOError exceptions are raised Explanation: The total size of the program
as a result of an error in opening or closing a remains the same regardless of whether
particular file. modules are used or not. Modules simply
divide the program.
15. Which of the following blocks will be
executed whether an exception is thrown or 3. Program code making use of a given
not? module is called a ______ of the module.
a) except a) Client
M
b) else b) Docstring
c) finally c) Interface
O
d) assert d) Modularity
C
Answer: c Answer: a
Explanation: The statements in the finally Explanation: Program code making use of a
T.
block will always be executed, whether an given module is called the client of the
exception is thrown or not. This clause is module. There may be multiple clients for a
used to close the resources used in a code. module.
O
4. ______ is a string literal denoted by triple
TOPIC 5.3 MODULES AND
PACKAGES SP
quotes for providing the specifications of
certain program elements.
a) Interface
G
1. Which of these definitions correctly b) Modularity
describes a module? c) Client
LO
Answer: b
Explanation: The term “module” refers to the b) Only the details of the program are
implementation of specific functionality to be addressed
SE
6. In top-down design every module is broken become part of the same scope. Since both
into same number of submodules. the modules have the same function name,
a) True there is a name clash.
b) False
9. Which of the following isn’t true about
Answer: b main modules?
Explanation: In top-down design every a) When a python file is directly executed, it
module can even be broken down into is considered main module of a program
different number of submodules. b) Main modules may import any number of
M
modules
7. All modular designs are because of a top- c) Special name given to main modules is:
O
down design process. __main__
a) True d) Other main modules can import main
C
b) False modules
T.
Answer: b Answer: d
Explanation: The details of the program can Explanation: Main modules are not meant to
be addressed before the overall design too. be imported into other modules.
O
Hence, all modular designs are not because of
a top-down design process. 10. Which of the following is not a valid
def change(a):
b=[x*2 for x in a]
print(b) Answer: b
#mod2 Explanation: During a Python program
execution, there are as many as three
.B
def change(a):
b=[x*x for x in a] namespaces – built-in namespace, global
print(b)
namespace and local namespace.
from mod1 import change
17
[1,4,9]
Answer: a
d) There is a name clash Explanation: In the “import modulename”
form of import, the namespace of imported
Answer: d module becomes available to, but not part of,
Explanation: A name clash is when two the importing module.
different entities with the same identifier
12. Which of the following is false about from math import factorial
“from-import” form of import? print(math.factorial(5))
a) The syntax is: from modulename import
identifier a) 120
b) This form of import prevents name clash b) Nothing is printed
c) The namespace of imported module c) Error, method factorial doesn’t exist in
becomes part of importing module math module
d) Error, the statement should be:
d) The identifiers in module are accessed
print(factorial(5))
directly as: identifier
M
Answer: d
Answer: b
O
Explanation: In the “from-import” form of
Explanation: In the “from-import” form of
import, the imported identifiers (in this case
import, there may be name clashes because
C
factorial()) aren’t specified along with the
names of the imported identifiers aren’t
module name.
specified along with the module name.
T.
15. What is the order of namespaces in which
13. Which of the statements about modules is
Python looks for an identifier?
false?
O
a) Python first searches the global namespace,
a) In the “from-import” form of import,
then the local namespace and finally the built-
identifiers beginning with two underscores
are private and aren’t imported
b) dir() built-in function monitors the items in
the namespace of the main module
SP
in namespace
b) Python first searches the local namespace,
then the global namespace and finally the
G
built-in namespace
c) In the “from-import” form of import, all
c) Python first searches the built-in
identifiers regardless of whether they are
LO
is automatically produced
finally the global namespace
Answer: c
17
Answer: b
Explanation: In the “from-import” form of
Explanation: Python first searches for the
import, identifiers beginning with two
local, then the global and finally the built-in
underscores are private and aren’t imported.
namespace.
-R