GE8151 Problem Solving and Python Programming MCQ
GE8151 Problem Solving and Python Programming MCQ
net
ww
w.E
a syE
ngi
nee
rin
g.n
et
PYTHON Answer: a
Explanation: The statement is true. This
PROGRAMMING word algorithm refers to a special method
usable by a computer for the solution to a
problem. The statement of the problem
SEMESTER - I specifies in general terms the desired
input/output relationship.
wMCQ
ww- 2017
Regulations 3. This characteristic often draws the line
between what is feasible and what is
impossible.
. E
DepartmentaofsCSE
a) Performance
b) System Evaluation
c) Modularity
yE d) Reliability
Answer: a
ngi Explanation: Algorithms help us to
understand scalability. Performance often
UNIT I ALGORITHMIC
PROBLEM SOLVING
nee draws the line between what is feasible and
what is impossible.
rin
4. The time that depends on the input: an
already sorted sequence that is easier to sort.
TOPIC 1.1 ALGORITHMS a) Process
b) Evaluation g.n
1. The word ____________comes from the
name of a Persian mathematician Abu Ja’far
Mohammed ibn-i Musa al Khowarizmi.
c) Running
d) Input
Answer: c
et
a) Flowchart Explanation: The running time depends on
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
to sort than the longer ones. Generally, we
Answer: c
seek upper bounds on the running time,
Explanation: The word algorithm comes
because it is reliable.
from the name of a Persian mathematician
Abu Ja’far Mohammed ibn-i Musa al 5. Which of the following is incorrect?
Khowarizmi. Algorithms can be represented:
a) as pseudo codes
b) as syntax
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.
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.
_________ a) Queue
a) Flowchart b) LL
b) Program c) Stack
ww
c) Pseudo code
d) Syntax
d) Union
w.E
Answer: b
Explanation: An algorithm becomes a
Answer: a
Explanation: The answer is Queue. A Queue
follows the FIFO principle. FIFO stands for
asy
program when it is written in the form of a
programming language. Thus, any program is
an algorithm.
First In First Out.
a) True
b) False gin 1. The symbol denotes _______
Answer: b
Explanation: The statement is false. Anee
algorithm is represented in the form of a
a) I/O
b) Flow
c) Terminal rin
programming language is called a program.
Any program is an algorithm but the reverse
is not true.
d) Decision
g.n
8. A system wherein items are added from
one and removed from the other end.
Answer: c
et
Explanation: The symbol denotes a terminal.
It is used for indication of start and stop
nodes of a program.
a) Stack
b) Queue 2. In computer science, algorithm refers to a
c) Linked List pictorial representation of a flowchart.
d) Array a) True
b) False
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
ww
a) Circles
b) Boxes
should be no set standards on the amount of
details that should be provided in a flowchart.
w.E
c) Arrows
d) Lines 8. A detailed flowchart is called ______
a) Stack
Answer: b
asy
Explanation: The actual instructions are
written in boxes. Boxes are connected by
b) Macro
c) Micro
d) Union
En
using arrows to indicate the exact flow of a
flowchart and the order in which they are to Answer: c
be executed.
gin Explanation: A detailed flowchart or a
flowchart with more details is called as micro
5. The following box denotes?
ee flowchart. It represents all the components of
the algorithm that is followed.
rin
9. Which of the following is not an advantage
a) Decision
b) Initiation
of a flowchart?
a) Better communication
b) Efficient coding
g.n
c) Initialization
d) I/O
Answer: a
c) Systematic testing
d) Improper documentation et
Answer: d
Explanation: A diamond shape box denotes Explanation: Flowcharts provide a proper
the decision making statements. It jumps to a documentation. It also provides systematic
truth value or a false value. debugging.
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
• Repetition
1. A ______________ is diagram that depicts • Case
the flow of a program. • Sequence.
a) Algorithm
5. The action performed by a ___________
ww
b) Hash Table
c) Graph
d) Flowchart
structure must eventually cause the loop to
terminate.
w.E
Answer: d
Explanation: A flowchart is a diagram that
a) sequence
b) case
c) repetition
asy
helps us determine the flow of the program.
Other options are irrelevant.
d) process
Answer: c
En
2. Terminals are represented by diagonals in a
flowchart.
Explanation: The action performed by a
repetition structure must eventually cause the
a) True
b) False gin loop to terminate. Otherwise, an infinite loop
is created.
Answer: b
Explanation: The statement is false.
Terminals are represented by rounded
ee 6. The following symbol denotes:
rin
rectangles. They indicate the starting or
ending point in a flowchart. a) Module
b) Terminal
g.n
3. The operation represented by
parallelograms.
a) Input/Output
c) Process
d) i/o operation et
b) Assignment Answer: a
c) Comparison Explanation: This symbol is that of a
d) Conditions module. The terminal is denoted by a rounded
rectangle. I/O operation by a parallelogram
Answer: a and process by a rectangle.
Explanation: The input/output operations are
represented by parallelograms. They
generally are used to display messages during
input and output part of a program.
7. What type of structure is this? shapes. They also show the flow of the
program.
a) sequence
b) case a) Decision
c) repetition b) Input/Output
d) process c) Process
d) Module
Answer: c
ww
Explanation: This is a repetition structure.
The action performed by a repetition structure
must eventually cause the loop to terminate.
Answer: a
Explanation: The answer is decision.
Conditions are given in this box and then the
w.E
Otherwise, an infinite loop is created.
gin code.
a) Dependent
a) sequence
b) case
c) repetition
ee b) Independent
c) Case sensitive
d) Capitalized
rin
d) process Answer: b
g.n
Explanation: The statement’s language
Answer: b
Explanation: This is a case structure. Certain
cases are given along with a default case in
the case structure.
et
should be independent. Other rules are to
write only one statement per line and end
multiline structures.
ww
d) Semicolon lowercase. They contain no spaces. They also
involve the consistent use of names.
w.E
Answer: a
Explanation: Each design structure uses a
particular indentation pattern.
8. Another notation for exponentiation.
a) *
following cases:
Sequence asy
Indentation should be considered in the b) **
c) ***
d) *^
Selection
Loop. En Answer: b
gin
5. The statement that tells the computer to get
Explanation: Double asterisk sign is also
used for exponentiation. The general notation
memory location.
a) read
b) write
ee
a value from an input device and store it in a is ^ sign.
a) () rin
9. A symbol used for grouping.
c) READ
d) WRITE
b) {}
c) [].
d) ” ”
g.n
Answer: c
Explanation: The READ statement is used to
take the input. READ being a keyword should
Answer: a et
Explanation: Parenthesis is used for
be in capital letters. grouping while working with fields. There are
other symbols like *, +, -, **, etc.
6. _____________ are identified by their
addresses, we give them names (field names / 10. A statement used to close the IF block.
variable names) using words. a) ELSE
a) Memory variables b) ELSEIF
b) Memory Locations c) END
c) Memory Addresses d) ENDIF
d) Data variables
Answer: d
Answer: b Explanation: The answer is ENDIF. It is used
Explanation: Memory locations are
Answer: b
Explanation: Variable names should not start
UNIT II DATA, with a number.
EXPRESSIONS, 5. Why are local variable names beginning
STATEMENTS with an underscore discouraged?
a) they are used to indicate a private variables
of a class
TOPIC 2.1 VARIABLES b) they confuse the interpreter
c) they are used to indicate global variables
ww
1. Is Python case sensitive when dealing with
identifiers?
d) they slow down execution
w.E
a) yes
b) no
c) machine dependent
Answer: a
Explanation: As Python has no concept of
private variables, leading underscores are
d) none of the mentioned
Answer: a
asy used to indicate variables that must not be
accessed from outside the class.
En
Explanation: Case is always significant. 6. Which of the following is not a keyword?
a) eval
gin
2. What is the maximum possible length of an
identifier?
b) assert
c) nonlocal
a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
ee d) pass
Answer: a
rin
Explanation: eval can be used as a variable.
Answer: d
a) lower case g.n
7. All keywords in Python are in _________
Explanation: Identifiers can be of any length.
w.E
variable names.
Answer: b et
Explanation: Modulus operator gives the
d) None of the mentioned remainder. So, 22%3 gives the remainder, that
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.
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
ww
c) 3 same.
T.
d) 1
w.E
Answer: c TOPIC 2.3 DATA TYPES
O
Explanation: First this expression will solve
asy
1**3 because exponential has higher
precedence than multiplication, so 1**3 = 1
and 3*1 = 3. Final answer is 3.
1. Which of these in not a core data type?
SP
a) Lists
b) Dictionary
En c) Tuples
G
8. Which one of the following has the same d) Class
precedence level?
gin
LO
ee
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and
Subtraction
Explanation: Class is a user defined data
type.
rin
.B
d) Addition and Multiplication 2. Given a function that does not return any
g.n
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
ww
c) round()
d) round(7463.123,2,1)
name error.
w.E
Answer: a
Explanation: Execute help(round) in the
Python code snippet?
1. def example(a):
asy
shell to get details of the parameters that are
passed into the round function. 2. a = a + '2'
a) int En
5. What is the return type of function id? 3. a = a*2
b) float
c) bool gin 4. return a
5. >>>example("hello")
d) dict
Answer: a ee
Explanation: Execute help(id) to find out
a) indentation Error
rin
b) cannot perform mathematical operation on
strings
details in python shell.id returns a integer
value that is unique.
c) hello2
d) hello2hello2 g.n
6. In python we do not specify types, it is
directly interpreted by the compiler, so
consider the following operation to be
Answer: a et
Explanation: Python codes have to be
indented properly.
performed.
9. What data type is the object below?
1. >>>x = 13 ? 2
L = [1, 23, 'hello', 1]
objective is to make sure x has a integer
value, select all that apply (python 3.xx) a) list
a) x = 13 // 2 b) dictionary
b) x = int(13 / 2) c) array
c) x = 13 % 2 d) tuple
d) All of the mentioned
Answer: a
Answer: d Explanation: List data type can store any
Explanation: // is integer operation in python
ww
SyntaxError?
a) ‘”Once upon a time…”, she said.’
a) 85.0
b) 85.1
c) 95.0
w.E
b) “He said, ‘Yes!'”
c) ‘3\’
d) ”’That’s okay”’
d) 95.1
Answer: a
Answer: c
asy
Explanation: Carefully look at the colons.
Explanation: Cause a decimal value of 0 to
appear as output.
En
12. The following is displayed by a print
14. Select all options that print.
1. tom
2. dick
ee a) print(‘hello’, ‘how’, ‘are’, ‘you’)
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
rin
c) print(‘hello-‘ + ‘how-are-you’)
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ +
3. harry ‘you’)
Answer: c
g.n
a)
print('''tom et
Explanation: Execute in the shell.
dick
TOPIC 2.4 NUMERIC TYPES
harry') (INT, FLOAT)
ww
2. Which of the following is not a complex
number?
octal numbers but 9 isn’t allowed in octal
numbers.
w.E
a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
7. What is the result of cmp(3, 1)?
a) 1
d) k = 2 + 3J
Answer: c asy b) 0
c) True
d) False
En
Explanation: l (or L) stands for long.
Answer: a
3. What is the type of inf?
a) Boolean gin Explanation: cmp(x, y) returns 1 if x > y, 0 if
x == y and -1 if x < y.
b) Integer
c) Float
d) Complex ee 8. Which of the following is incorrect?
a) float(‘inf’)
b) float(‘nan’)
rin
Answer: c
Explanation: Infinity is a special case of
floating point numbers. It can be obtained by
c) float(’56’+’78’)
d) float(’12+34′)
g.n
float(‘inf’).
ww
>>> round(-0.5)
TOPIC 2.5 PRECEDENCE OF
w.E
-1.0
>>>
OPERATORS
asy
In the above output, you can see that the
1. The value of the expressions 4/(3*(2-1))
and 4/3*(2-1) is the same.
a) True
En
round() functions on 0.5 and -0.5 are moving
away from 0 and hence “round(0.5) – b) False
(round(-0.5)) = 1 – (-1) = 2”
rin
making a difference. The result of both of
these expressions is 1.333333333. Hence the
>>> round(0.5)
0
statement is true.
g.n
>>> round(-0.5)
0
Python expression?
4 + 3 % 5
et
2. What will be the value of the following
>>> round(2.5)
a) 4
2 b) 7
c) 2
>>> round(3.5) d) 0
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
ww
4. Which of the following operators has its
associativity from right to left?
b) %
c) //
w.E
a) +
b) //
c) %
d) |
Answer: c
d) **
asy Explanation: // is the operator for truncation
division. It is called so because it returns only
the integer part of the quotient, truncating the
Answer: d
En
Explanation: All of the operators shown
decimal part. For example: 20//3 = 6.
gin
above have associativity from left to right,
except exponentiation operator (**) which
has its associativity from right to left.
8. What are the values of the following
Python expressions?
Answer: d
et
Explanation: Expression 1 is evaluated as:
Answer: b 2**9, which is equal to 512. Expression 2 is
Explanation: The expression shown above is evaluated as 8**2, which is equal to 64. The
an example of explicit conversion. It is last expression is evaluated as 2**(3**2).
evaluated as int(43.55+1) = int(44.55) = 44. This is because the associativity of **
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)
ww
a) 8
b) 8.0
Answer: c
Explanation: Coercion is the implicit
w.E
c) 8.3
d) 8.33
(automatic) conversion of operands to a
common type. Coercion is automatically
performed on mixed-type expressions. The
Answer: b
asy
Explanation: The expression shown above is
expression 1.7 % 2 is evaluated as 1.7 % 2.0
(that is, automatic conversion of int to float).
En
evaluated as: float( 7+1) = float(8) = 8.0.
Hence the result of this expression is 8.0.
4. What will be the output of the following
Python expression?
print(4.00/(2.0+2.0))
a) Error
ee a) (1,3)
b) (0,3)
c) (1,0)
rin
b) 1.0
c) 1.00
d) (3,1)
Answer: a g.n
d) 1
Answer: b
Explanation: The result of the expression
et
Explanation: The expressions are evaluated
as: 4%3 and 6//2 respectively. This results in
the answer (1,3). This is because the
associativity of both of the expressions shown
shown above is 1.0 because print rounds off
above is left to right.
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?
+, -, **, %, /, <<, >>, |
X = 2+9*((3*12)-8)/10
a) <<, >>
a) 30.0
b) **
b) 30.8
c) |
c) 28.4
d) %
d) 27.2
ww
Answer: c
Explanation: The above expression is an
example of explicit conversion. It is evaluated
the result of the expression shown above is 7.
w.E
as: float(4+int(2.39)%2) = float(4+2%2) =
float(4+0) = 4.0. Hence the result of this
expression is 4.0.
(2**2)**3.
a) True
b) False
asy
7. Which of the following expressions is an Answer: b
example of type conversion?
a) 4.0 + float(3)
En Explanation: The value of the expression
(2**2)**3 = 4**3 = 64. When the expression
b) 5.3 + 6.3
c) 5.0 + 3
d) 3 + 7
gin 2**2**3 is evaluated in python, we get the
result as 256, because this expression is
evaluated as 2**(2**3). This is because the
Answer: a ee
Explanation: Type conversion is nothing but
associativity of exponentiation operator (**)
rin
is from right to left and not from left to right.
x<<2
et
1. What will be the output of the following
in an error?
a) float(‘10’) a) 8
b) int(‘10’) b) 1
c) float(’10.8’) c) 2
d) int(’10.8’) d) 4
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)
gives the result 15. The expression int(‘1111’,
Answer: b 10) will give the result 1111.
Explanation: The binary form of the number
29 is 11101. Hence the output of this 6. What will be the output of the following
expression is ‘0b11101’. Python expression if x=15 and y=12?
ww
3. What will be the value of x in the
following Python expression, if the result of
x & y
w.E
that expression is 2?
x>>2
a) b1101
b) 0b1101
c) 12
a) 8
b) 4
asy d) 1101
c) 2
d) 1 En Answer: c
Explanation: The symbol ‘&’ represents
Answer: a gin bitwise AND. This gives 1 if both the bits are
equal to 1, else it gives 0. The binary form of
15 is 1111 and that of 12 is 1100. Hence on
ee
Explanation: When the value of x is equal to
8 (1000), then x>>2 (bitwise right shift)
yields the value 0010, which is equal to 2.
Hence the value of x is 8.
performing the bitwise AND operation, we
rin
get 1100, which is equal to 12.
Python expression?
int(1011)?
b) int(‘1011’,23)
c) int(1011,2)
d) int(‘1011’)
et
a) 1011
b) 11 Answer: c
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
Answer: a not be an error.
Explanation: The result of the expression
shown will be 1011. This is because we have 8. Which of the following represents the
not specified the base in this expression. bitwise XOR operator?
Hence it automatically takes the base as 10. a) &
b) ^
c) |
d) !
ww
Answer: d
Explanation: The prefix 0x specifies that the
one’s complement of 110010101 is
001101010.
w.E
value is hexadecimal in nature. When we
convert this hexadecimal value to binary
form, we get the result as: ‘0b1000’.
3. Bitwise _________ gives 1 if either of the
bits is 1 and 0 when both of the bits are 1.
asy
10. What will be the output of the following
a) OR
b) AND
c) XOR
Python expression?
En d) NOT
0x35 | 0x75
rin
4. What will be the output of the following
Answer: c
Explanation: The binary value of 0x35 is
Python expression?
4^12 g.n
110101 and that of 0x75 is 1110101. On OR-
ing these two values we get the output as:
1110101, which is equal to 117. Hence the
result of the above expression is 117.
a) 2
b) 4
c) 8
et
d) 12
1. It is not possible for the two’s complement
value to be equal to the original value in any Answer: c
case. Explanation: ^ is the XOR operator. The
a) True binary form of 4 is 0100 and that of 12 is
b) False 1100. Therefore, 0100^1100 is 1000, which is
equal to 8.
Answer: b
Explanation: In most cases the value of two’s 5. Any odd number on being AND-ed with
complement is different from the original ________ always gives 1. Hint: Any even
value. However, there are cases in which the number on being AND-ed with this value
two’s complement value may be equal to the always gives 0.
a) 10 a=a^b
b) 2 print(a,b)
c) 1
a) 10 20
d) 0
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
Answer: c
number on being AND-ed with this value
Explanation: The code shown above is used
always gives 0.
to swap the contents of two memory locations
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.
ww
bin(10-2)+bin(12^4)
a) 0b10000
9. What is the two’s complement of -44?
a) 1011011
b) 11010100
w.E
b) 0b10001000
c) 0b1000b1000
d) 0b10000b1000
c) 11101011
d) 10110011
En
Explanation: The output of bin(10-2) =
0b1000 and that of bin(12^4) is ob1000.
00101100. The one’s complement of this
value is 11010011. On adding one to this we
gin
Hence the output of the above expression is:
0b10000b1000.
get: 11010100 (two’s complement).
ee
7. Which of the following expressions can be
used to multiply a given number ‘a’ by 4?
a) a<<2
Python expression?
~100?
rin
b) a<<4
c) a>>2
d) a>>4
a) 101
b) -101 g.n
Answer: a
Explanation: Let us consider an example
wherein a=2. The binary form of 2 is 0010.
c) 100
d) -100
Answer: b
et
Explanation: Suppose we have an expression
When we left shift this value by 2, we get
~A. This is evaluated as: -A – 1. Therefore,
1000, the value of which is 8. Hence if we
the expression ~100 is evaluated as -100 – 1,
want to multiply a given number ‘a’ by 4, we
which is equal to -101.
can use the expression: a<<2.
Sanfoundry Global Education & Learning
8. What will be the output of the following
Series – Python.
Python code if a=10 and b =20?
False a)
ww True True
c)
w.EFalse b)
True
False
asy True
d)
En c)
False
True
Answer: d
ee
Explanation: The Boolean function returns
true if the argument passed to the bool d)
True
rin
function does not amount to zero. In the first
example, the string ‘False’ is passed to the
function bool. This does not amount to zero
False
g.n
and hence the output is true. In the second
function, an empty list is passed to the
function bool. Hence the output is false.
False
Answer: b et
Explanation: The function not returns true if
the argument amounts to false, and false if the
argument amounts to true. Hence the first
function returns false, and the second
2. What will be the output of the following function returns false.
Python code snippet?
['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
amount to zero. Else ‘t’ is printed. The Answer: c
argument given to the Boolean function in the Explanation: The code shown above shows
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
function is evaluated from left to right. Since
ww
5. What will be the output of the following
Python code?
the left operand is false, it is assumed that the
right operand must be true and hence the right
operand is returned in each of the above case.
w.E
l=[1, 0, 2, 0, 'hello', '', []]
list(filter(bool, l))
a) Error
b) [1, 0, 2, 0, ‘hello’, ”, []] asy 7. What will be the output of the following
Python code?
c) [1, 0, 2, ‘hello’, ”, []]
d) [1, 2, ‘hello’]
En class Truth:
Answer: d
Explanation: The code shown above returnsgin bool(x)
pass
x=Truth()
Answer: b
g.n
2017 (Wednesday)?
[] or {}
{} or []
et
Explanation: If the truth method is not
defined, the object is considered true. Hence
the output of the code shown above is true.
[] a) error
b) hello
c)
c) good
d) bad
ww
b) -6>=0 and -6<=10
c) not(-6<10 or-6==10)
x = ['ab', 'cd']
for i in x:
i.upper()
w.E
d) not(-6>10 or-6==10)
Answer: d
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
asy
Explanation: The expression not(-6<0 or
-6>10) returns the output False.
The expression -6>=0 and -6<=10 returns the
c) [None, None]
d) none of the mentioned
output False.
En
The expression not(-6<10 or -6==10) returns Answer: a
the output False.
gin
The expression not(-6>10 or -6==10) returns
Explanation: The function upper() does not
modify a string in place, it returns a new
string which isn’t being stored anywhere.
the output True.
ee
10. What will be the output of the following
Python code snippet? rin
2. What will be the output of the following
Python code?
a) [‘AB’, ‘CD’]
et
d) No output b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
Answer: b d) none of the mentioned
Explanation: The expression not(10<20)
returns false. The expression not(10>30) Answer: d
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 break
c) error print(i)
d) none of the mentioned i += 1
Answer: c a) 5 6 7 8
Explanation: SyntaxError, there shouldn’t be b) 5 6 7 8 9
ww
a space between + and = in +=.
w.E
Python code?
i = 1
Answer: d
Explanation: 9 isn’t allowed in an octal
while True:
if i%0O7 == 0:
break
asy number.
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
gin i = 1
while True:
if i%2 == 0:
c) error
d) none of the mentioned ee break
print(i)
i += 2
rin
Answer: a
Explanation: Control exits the loop when i
becomes 7.
a) 1
b) 1 2
c) 1 2 3 4 5 6 … g.n
5. What will be the output of the following
Python code?
d) 1 3 5 7 9 11 …
Answer: d
et
Explanation: The loop does not terminate
i = 5 since i is never an even number.
while True:
if i%0O11 == 0:
break 8. What will be the output of the following
print(i) Python code?
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
loop. b) 0 1 2
c) error
9. What will be the output of the following d) none of the mentioned
Python code?
Answer: b
ww
i = 1
while False:
if i%2 == 0:
Explanation: The else part is not executed if
control breaks out of the loop.
w.E break
print(i)
i += 2
2. What will be the output of the following
Python code?
a) 1
b) 1 3 5 7 … asy i = 0
while i < 3:
print(i)
c) 1 2 3 4 …
d) none of the mentioned En i += 1
else:
a) 0 1 2 3 0
because of False.
ee
Explanation: Control does not enter the loop
True = False
Answer: b
g.n
Explanation: The else part is executed when
while True:
print(True)
break
et
the condition in the while statement is false.
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"
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 = " ")
Answer: a a) i i i i i i
b) a a a a a a
ww
Explanation: “i” is not in “abcdef”.
w.E
Python code?
x = "abcdef"
Answer: b
Explanation: The string x is being shortened
i = "a"
while i in x:
print(i, end = " ") asy by one character in each iteration.
c) a a a a a a …
d) a b c d e f gin x = "abcdef"
i = "a"
while i in x[:-1]:
Answer: c ee
Explanation: As the value of i or x isn’t
changing, the condition will always evaluate
print(i, end = " ")
a) a a a a a
b) a a a a a a rin
to True. c) a a a a a a …
d) a g.n
6. What will be the output of the following
Python code?
x = "abcdef"
Answer: c
et
Explanation: String x is not being altered and
i is in x[:-1].
i = "a"
while i in x: 9. What will be the output of the following
print('i', end = " ")
Python code?
a) no output x = "abcdef"
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?
x = "abcdef" x = 'abcd'
i = "a" for i in range(x):
while i in x[1:]: print(i)
print(i, end = " ")
ww
a) a a a a a a
b) a
a) a b c d
b) 0 1 2 3
c) error
w.E
c) no output
d) error
d) none of the mentioned
Answer: c
Answer: c
asy
Explanation: i is not in x[1:].
Explanation: range(str) is not allowed.
Python code? En
1. What will be the output of the following Python code?
x = 'abcd'
for i in x:
gin x = 'abcd'
for i in range(len(x)):
print(i)
print(i)
x.upper()
a) a B C D
ee a) a b c d
b) 0 1 2 3
rin
c) error
b) a b c d
c) A B C D
d) 1 2 3 4
g.n
d) error
Answer: b
Explanation: Changes do not happen in-
Answer: b
et
Explanation: i takes values 0, 1, 2 and 3.
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'
i.upper() for i in range(len(x)):
print (x) x = 'a'
print(x)
a) a b c d
b) 0 1 2 3 a) a
ww
c) error
d) none of the mentioned
b) abcd abcd abcd
c) a a a a
d) none of the mentioned
w.E
Answer: c
Explanation: Objects of type int have no
attribute upper().
Answer: c
Explanation: range() is computed only at the
asy
7. What will be the output of the following
Python code snippet?
time of entering the loop.
a) abcd
b) ABCD
c) error
ee a) a
x = 'a'
rin
b) abcd abcd abcd abcd
d) none of the mentioned c) a a a a
d) none of the mentionedg.n
Answer: a
Explanation: Changes do not happen in-
place, rather a new instance of the string is
returned.
Answer: d
et
Explanation: abcd a a a is the output as x is
modified only after ‘abcd’ has been printed
once.
8. What will be the output of the following
Python code snippet? 1. What will be the output of the following
Python code?
x = 'abcd'
for i in range(len(x)): x = 123
i[x].upper() for i in x:
print (x) print(i)
a) abcd a) 1 2 3
b) ABCD b) 123
c) error c) error
d) none of the mentioned d) none of the mentioned
ww
d) none of the mentioned
Answer: a
the values.
w.E
Explanation: Loops over the keys of the
dictionary.
Python code?
asy
3. What will be the output of the following
Python code?
for x in d.values():
print(x)
b) a b c
c) 0 a 1 b 2 c
d) none of the mentioned
ee Answer: b
rin
Explanation: Loops over the values.
a) 0 1 2
d = {0: 'a', 1: 'b', 2: 'c'}
b) a b c
for x, y in d.items(): c) 0 a 1 b 2 c
print(x, y) d) none of the mentioned
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
attribute values. Python code?
9. What will be the output of the following for i in range(2.0):
Python code? print(i)
ww
d = {0, 1, 2}
for x in d:
print(x)
a) 0.0 1.0
b) 0 1
c) error
w.E
a) 0 1 2
b) {0, 1, 2} {0, 1, 2} {0, 1, 2}
d) none of the mentioned
Answer: c
c) error
d) none of the mentioned
asy Explanation: Object of type float cannot be
interpreted as an integer.
Answer: a
En
Explanation: Loops over the elements of the
2. What will be the output of the following
Python code?
set and prints them.
gin for i in range(int(2.0)):
Python code?
d = {0, 1, 2}
ee
10. What will be the output of the following print(i)
a) 0.0 1.0
b) 0 1 rin
for x in d:
print(d.add(x))
c) error
g.n
d) none of the mentioned
a) 0 1 2
b) 0 1 2 0 1 2 0 1 2 …
c) None None None
d) None of the mentioned
Answer: b
et
Explanation: range(int(2.0)) is the same as
range(2).
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)
ww
Answer: d
Explanation: OverflowError, cannot convert
for i in '':
print (i)
w.E
float infinity to integer.
Answer: b
En
for i in [1, 2, 3, 4][::-1]:
print (i) Explanation: The string does not have any
character to loop over.
a) 1 2 3 4
b) 4 3 2 1 gin 9. What will be the output of the following
c) error
d) none of the mentioned
Answer: b
ee Python code snippet?
x = 2
for i in range(x):
x += 1 rin
Explanation: [::-1] reverses the list.
for i in ''.join(reversed(list('abcd'))):
print (i)
a) 0 1 2 3 4 …
b) 0 1
c) 3 4
d) 0 1 2 3
et
a) a b c d Answer: c
b) d c b a Explanation: Variable x is incremented and
c) error printed twice.
d) none of the mentioned
10. What will be the output of the following
Answer: b Python code snippet?
Explanation: ‘ ‘.join(reversed(list(‘abcd’)))
x = 2
reverses a string. for i in range(x):
x -= 2
7. What will be the output of the following print (x)
Python code snippet?
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
Answer: a
Python code?
Explanation: The first statement creates a
for i in range(10): generator object.
if i == 5:
break 4. What will be the output of the following
ww else:
else:
print(i)
Python code?
x = (i for i in range(3))
w.E
print("Here")
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
for i in x:
print(i)
for i in x:
print(i)
c) 0 1 2 3 4
d) 1 2 3 4 5 asy a) 0 1 2
Answer: c
En b) error
c) 0 1 2 0 1 2
gin
Explanation: The else part is executed if
control doesn’t break out of the loop.
d) none of the mentioned
Answer: a
Python code?
for i in range(5):
ee
2. What will be the output of the following Explanation: We can loop over a generator
object only once.
rin
5. What will be the output of the following
if i == 5:
break
Python code?
g.n
else:
else:
print(i)
print("Here")
string = "my name is x"
for i in string:
print (i, end=", ") et
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
b) 0 1 2 3 4 5 Here c) my, name, is, x,
c) 0 1 2 3 4 d) error
d) 1 2 3 4 5
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?
ww
Python code snippet?
a = [0, 1, 2, 3]
10. What will be the output of the following
Python code snippet?
w.E
for a[-1] in a:
print(a[-1])
a) 0 1 2 3
string = "my name is x"
for i in ' '.join(string.split()):
print (i, end=", ")
b) 0 1 2 2
c) 3 3 3 3 asy a) m, y, , n, a, m, e, , i, s, , x,
d) error
En b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
Answer: b
gin
Explanation: The value of a[-1] changes in
each iteration.
d) error
Answer: a
rin
a = [0, 1, 2, 3]
for a[0] in a:
TOPIC 3.2 PYTHON STRINGS
g.n
print(a[0])
a) 0 1 2 3
b) 0 1 2 2
Python statement?
1. >>>"a"+"bc"
et
1. What will be the output of the following
c) 3 3 3 3
d) error a) a
b) bc
Answer: a c) bca
Explanation: The value of a[0] changes in d) abc
each iteration. Since the first value that it
takes is itself, there is no visible error in the Answer: d
current example. Explanation: + operator is concatenation
operator.
9. What will be the output of the following
Python code snippet? 2. What will be the output of the following
Python statement?
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?
ww
b)
string.ascii_lowercase+string.ascii_uppercase
Answer: b
Explanation: When prefixed with the letter
‘r’ or ‘R’ a string literal becomes a raw string
w.E
c) string.letters
d) string.lowercase_string.uppercase and the escape sequences such as \n are not
converted.
Answer: b
asy
Explanation: Execute in shell and check. 7. What will be the output of the following
Python statement?
Python code? En
4. What will be the output of the following
1. >>>print('new' 'line')
a) olleh
g.n
Explanation: String literal separated by
whitespace are allowed. They are
b) hello
c) h
d) o
concatenated.
et
8. What will be the output of the following
Python statement?
Answer: d
Explanation: -1 corresponds to the last index. 1. >>> print('x\97\x98')
ww
c) world
d) helloworld
Explanation: self.o1 was never created.
w.E
Answer: a
Explanation: Execute in shell to verify.
Python code?
1. class tester:
id="224"
a) 0xA0xB0xC
b) Error gin 5.
c) 0x22
d) 33
Answer: d
ee 6. >>>temp = tester(12)
7. >>>print(temp.id)
rin
Explanation: 0xA and 0xB and 0xC are
hexadecimal integer literals representing the
a) 224
b) Error g.n
decimal values 10, 11 and 12 respectively.
There sum is 33.
Answer: c
et
Python code? Explanation: Id in this case will be the
attribute of the class.
1. class father:
3. What will be the output of the following
2. def __init__(self, param):
Python code?
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
ww
a) snow
b) snow world
1. >>>example = "helle"
w.E
c) Error
d) snos world
2. >>>example.rfind("e")
a) -1
Answer: c
asy
Explanation: Strings cannot be modified.
b) 4
c) 3
d) 1
Python code? En
5. What will be the output of the following
Answer: b
a) error
b) u
c) t
ee 9. What will be the output of the following
Python code?
rin
1. >>>example="helloworld"
d) y
Answer: d
g.n
2. >>>example[::-1].startswith("d")
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
a) A d) str
b) B
c) a Answer: d
d) Error Explanation: Format function returns a
string.
ww
Answer: a
Explanation: Execute in shell to verify. 6. What will be the output of the “hello”
w.E
2. What will be the output of the following
Python statement?
+1+2+3?
a) hello123
b) hello
asy
1. >>>print(chr(ord('b')+1))
c) Error
d) hello6
a) a
b) b
En Answer: c
Explanation: Cannot concatenate str and int
c) c
d) A
gin objects.
Answer: c
ee
Explanation: Execute in the shell to verify.
rin
1. >>>print("D", end = ' ')
hello\example\test.txt?
a) print(“hello\example\test.txt”) g.n
2. >>>print("C", end = ' ')
b) print(“hello\example\test.txt”)
c) print(“hello\”example\”test.txt”)
d) print(“hello”\example”\test.txt”)
et
3. >>>print("B", end = ' ')
4. >>>print("A", end = ' ')
a) DCBA
Answer: b
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
4. Suppose s is “\t\tWorld\n”, what is
Answer: c
s.strip()?
Explanation: Execute in the shell.
a) \t\tWorld\n
b) \t\tWorld\n 8. What will be the output of the following
c) \t\tWORLD\n Python statement?(python 3.xx)
d) World
1. >>>print(format("Welcome", "10s"),
end = '#')
ww
ord(‘a’))?
a) 0
b) 1
Answer: a
w.E
c) -1
d) 2
Explanation: Execute in shell to verify.
gin
10. Say s=”hello” what will be the return
value of type(s)?
c) print obj
d) all of the mentioned
a) int
b) bool
c) str
d) String
ee Answer: d
rin
Explanation: Execute in shell to verify.
Answer: c g.n
5. To check whether string s1 contains
another string s2, use ________
a) s1.__contains__(s2)
Explanation: str is used to represent strings
in python.
ww 6. c2 = Count(2)
d) John Smith
Answer: b
w.E
7. print(id(c1) == id(c2), end = " ")
8.
Explanation: Execute in the shell to verify.
rin
“10.3f”) (_ indicates space).
a) __345.355
Answer: c
Explanation: Execute in the shell objects
b) ___345.355
c) ____345.355 g.n
cannot have same id, however in the case of
strings its different.
Answer: b
et
Explanation: Execute in the shell to verify.
Python code?
1. What will be the output of the following
1. class Name: Python code?
2. def __init__(self, firstName, m print("abc DEF".capitalize())
i, lastName):
a) abc def
3. self.firstName = firstName
b) ABC DEF
4. self.mi = mi c) Abc def
d) Abc Def
5. self.lastName = lastName
6.
ww
Answer: c
Explanation: The first letter of the string is
haven’t overridden the value of sep.
w.E
converted to uppercase and the others are
converted to lowercase.
Python code?
asy
3. What will be the output of the following
Python code?
'')
a) * abcdef *
print("abcdef".center())
En b) * abcdef *
c) *abcdef *
a) cd
b) abcdef gin d) * abcdef*
c) error
d) none of the mentioned
Answer: c
ee Answer: d
Explanation: Padding is done towards the
rin
left-hand-side first when the final string is of
odd length.
Explanation: The function center() takes at
least one parameter. g.n
7. What will be the output of the following
ww
print("abcdef".center(7, '1'))
a) 1abcdef
Answer: a
Explanation: Counts the number of times the
substring ‘yy’ is present in the given string,
w.E
b) abcdef1
c) abcdef
d) error
starting from position 1.
a) 2
print("abcdef".center(10, '12'))
a) 12abcdef12
ee d) none of the mentioned
Answer: c
rin
Explanation: Counts the number of times the
b) abcdef1212
c) 1212abcdef g.n
substring ‘yy’ is present in the given string,
starting from position 2.
d) error
Answer: d
Explanation: The fill character must be
Python code? et
4. What will be the output of the following
ww
position 11.
w.E
Python code?
print("xyyzxyzxzxyy".count('xyy', -10, -1
Answer: b
Explanation: The function returns True if the
))
a) 2
asy given string ends with the specified substring.
b) 0
c) 1 En 10. What will be the output of the following
Python code?
d) error
gin print("xyyzxyzxzxyy".endswith("xyy", 0, 2
))
Answer: b
ee
Explanation: Counts the number of times the
substring ‘xyy’ is present in the given string,
starting from position 2 and ending at
a) 0
b) 1
c) True rin
position 11. d) False
g.n
7. What will be the output of the following
Python code?
print('abc'.encode())
Answer: d
et
Explanation: The function returns False if
the given string does not end with the
specified substring.
a) abc 1. What will be the output of the following
b) ‘abc’ Python code?
c) b’abc’
d) h’abc’ print("ab\tcd\tef".expandtabs())
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
ww
spaces.
w.E
Python code?
print("ab\tcd\tef".expandtabs('+'))
a) 4
b) 0
c) Error
a) ab+cd+ef
b) ab++++++++cd++++++++ef
asy d) True
Answer: b
c) ab cd ef
d) none of the mentioned En Explanation: The first position in the given
string at which the substring can be found is
passed as an argument. ee
Explanation: TypeError, an integer should be
rin
print("Hello {0} and {1}".format('foo',
Python code? 'bin'))
a) True
b) Hello {0} and {1} foo bin
c) Error
d) Hello 0 and 1
et
b) False
c) Error Answer: a
d) None of the mentioned Explanation: The numbers 0 and 1 represent
the position at which the strings are present.
Answer: b
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
ww
b) Hello {} and {}
c) Error
d) Hello and
Explanation: !r causes the characters ‘ or ” to
be printed as well.
w.E
Answer: a
Explanation: It is the same as Hello {0} and
3. What will be the output of the following
Python code?
{1}.
asy
10. What will be the output of the following
print("Hello {0} and {1}".format(('foo',
'bin')))
Python code?
En a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
gin
print("Hello {name1} and {name2}".format(
'foo', 'bin'))
c) Error
d) None of the mentioned
rin
Explanation: IndexError, the tuple index is
out of range.
d) Hello and
Answer: c g.n
4. What will be the output of the following
Python code?
Explanation: The arguments passed to the
function format aren’t keyword arguments. et
print("Hello {0[0]} and {0[1]}".format((
'foo', 'bin')))
1. What will be the output of the following
a) Hello foo and bin
Python code?
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
print("Hello {name1} and {name2}".format( c) Error
name1='foo', name2='bin')) d) None of the mentioned
Answer: a a) 1,112,223,334
Explanation: The arguments passed to the b) 111,222,333,4
function format can be integers also. c) 1112223334
d) Error
6. What will be the output of the following
Python code snippet? Answer: d
ww
print('The sum of {0:b} and {1:x} is {2:
o}'.format(2, 10, 12))
Explanation: $ is an invalid format code.
w.E
a) The sum of 2 and 10 is 12
b) The sum of 10 and a is 14
Python code snippet?
print('{:#}'.format(1112223334))
c) The sum of 10 and a is c
d) Error
asy a) 1,112,223,334
b) 111,222,333,4
Answer: b
En
Explanation: 2 is converted to binary, 10 to
c) 1112223334
d) Error
hexadecimal and 12 to octal.
gin Answer: c
print('{:,}'.format(1112223334))
ee
7. What will be the output of the following Explanation: The number is printed as it is.
a) 1,112,223,334
b) 111,222,333,4 g.n
print('{0:.2}'.format(1/3))
c) 1112223334
d) Error
Answer: a
a) 0.333333
b) 0.33
c) 0.333333:.2
et
d) Error
Explanation: A comma is added after every
third digit from the right. Answer: b
Explanation: .2 specifies the precision.
8. What will be the output of the following
Python code snippet? 2. What will be the output of the following
Python code?
print('{:,}'.format('1112223334'))
print('{0:.2%}'.format(1/3))
a) 1,112,223,334
b) 111,222,333,4 a) 0.33
c) 1112223334 b) 0.33%
d) Error
ww
b) False
c) None
d) Error
Python code snippet?
print('0xa'.isdigit())
w.E
Answer: a
Explanation: The string has only letters and
a) True
b) False
digits.
asy c) None
d) Error
Python code?
En
4. What will be the output of the following
Answer: b
Explanation: Hexadecimal digits aren’t
print('ab,12'.isalnum())
gin considered as digits (a-f).
a) True
b) False
c) None
d) Error
ee 8. What will be the output of the following
Python code snippet?
print(''.isdigit()) rin
Answer: b a) True
b) False
g.n
Explanation: The character , is not a letter or
a digit.
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
ww
Explanation: It is a valid identifier.
Answer: a
w.E
Python code snippet?
print('for'.isidentifier())
Explanation: All the character are numeric.
c) None
d) Error En print('1.1'.isnumeric())
a) True
as valid identifiers. ee
Explanation: Even keywords are considered
Answer: b
rin
Explanation: The character . is not a numeric
Python code snippet? character.
g.n
print('abc'.islower())
a) True
b) False
Python code snippet?
et
6. What will be the output of the following
print('125erdE a'.isprintable())
c) None
d) Error a) True
b) False
Answer: a c) None
Explanation: There are no uppercase letters. d) Error
ww
a) True
b) False
Python code?
print('GYMK'.lower())
w.E
c) None
d) Error a) n
b) gymk
Answer: a
asy
Explanation: Tab Spaces are considered as
spaces.
c) rn
d) r
En
9. What will be the output of the following
Answer: b
Explanation: Uppercase letters are converted
Python code snippet?
gin to lowercase. The other characters are left
unchanged.
print('HelloWorld'.istitle())
a) True
b) False
ee 3. What will be the output of the following
Python code?
rin
c) None
d) Error
print('''
\tfoo'''.lstrip())
g.n
Answer: b
Explanation: The letter W is uppercased.
a) \tfoo
b) foo
c) foo
et
10. What will be the output of the following d) none of the mentioned
Python code snippet?
Answer: b
print('Hello World'.istitle()) Explanation: All leading whitespace is
removed.
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
ww
c) xyxzxxy
d) none of the mentioned
Explanation: The string is split into three
parts by partition.
w.E
Answer: a
Explanation: All combinations of the
characters passed as an argument are removed
9. What will be the output of the following
Python code?
rin
point where the separator first appears.
a) (‘ab’, ‘cd’, ”)
et
Python code? b) (‘ab’, ‘cd’)
c) error
print('a'.maketrans('ABC', '123')) d) none of the mentioned
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.
ww
a) (‘abef’)
b) (‘abef’, ‘cd’, ”)
Answer: b
Explanation: The first substring is not
w.E
c) (‘abef’, ”, ”)
d) error
present in the given string and hence nothing
is replaced.
Answer: c
asy
Explanation: The separator is not present in
6. What will be the output of the following
Python code snippet?
En
the string hence the second and the third
elements of the tuple are null strings. print('xyyxyyxyxyxxy'.replace('xy', '12',
0))
print('abcdef12'.replace('cd', '12'))
a) ab12ef12
ee b) 12y12y1212x12
c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
rin
b) abcdef12
c) ab12efcd
Answer: a
g.n
Explanation: The first 0 occurrences of the
d) none of the mentioned
Answer: a
Explanation: All occurrences of the first
et
given substring are replaced.
ww
9. What will be the output of the following
Python code snippet?
a) [‘ab’, ‘cd’, ‘ef’]
b) [‘ab\n’, ‘cd\n’, ‘ef\n’]
c) [‘ab\n’, ‘cd\n’, ‘ef’]
w.E
print('abcdefcdghcd'.split('cd', 0))
a) [‘abcdefcdghcd’]
d) [‘ab’, ‘cd’, ‘ef\n’]
Answer: a
b) ‘abcdefcdghcd’
c) error
d) none of the mentioned
asy Explanation: It is similar to calling
split(‘\n’).
gin
Explanation: The given string is split at 0
occurances of the specified substring.
Python code snippet?
print('Ab!2'.swapcase())
ww
capitalized. Special symbols terminate a
word.
Python code snippet?
print('ab'.zfill(5))
w.E
6. What will be the output of the following
Python code snippet? a) 000ab
b) 00ab0
asy
print('abcd'.translate('a'.maketrans('ab
c', 'bcd')))
c) 0ab00
d) ab000
a) bcde
b) abcd En Answer: a
Explanation: The string is padded with zeros
c) error
d) bcdd gin on the left hand side. It is useful for
formatting numbers.
Answer: d
ee
Explanation: The output is bcdd since no
translation is provided for d.
10. What will be the output of the following
Python code snippet?
rin
7. What will be the output of the following
print('+99'.zfill(5))
a) 00+99 g.n
Python code snippet?
Answer: d Answer: c
Explanation: The function seed is a function Explanation: The function all returns false if
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
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.
system output.
ww
2. What will be the output of the following
5. What will be the output of the following
Python expression?
w.E
Python expression?
round(4.576)
round(4.5676,2)?
a) 4.5
a) 4.5
b) 5 asy b) 4.6
c) 4.57
c) 4
d) 4.6 En d) 4.56
Answer: c
Answer: b
gin
Explanation: This is a built-in function
Explanation: The function round is used to
round off the given decimal number to the
ee
which rounds a number to give precision in
decimal digits. In the above case, since the
number of decimal places has not been
specified decimal places. In this case, the
number should be rounded off to two decimal
rin
places. Hence the output will be 4.57.
specified, the decimal number is rounded off
to a whole number. Hence the output will be
5. Python function? g.n
6. What will be the output of the following
a) Error
et
b) (x**y) / z b) True
c) (x**y) % z c) False
d) (x**y)*z d) 4>2
Answer: c Answer: b
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?
ww
8. What will be the output of the following
Python function?
1. What will be the output of the following
Python functions?
w.E
sum(2,4,6)
sum([1,2,3])
chr(‘97’)
chr(97)
a) Error, 6
b) 12, Error
c) 12, 6
asy a)
a
d) Error, Error
En Error
Answer: a
gin
Explanation: The first function will result in b)
ee
an error because the function sum() is used to
find the sum of iterable numbers. Hence the
outcomes will be Error and 6 respectively.
‘a’
a
rin
9. What will be the output of the following
Python function?
c)
Error
g.n
all(3,0,4.2)
a) True
d)
a et
b) False
c) Error Error
d) 0
Error
Answer: c
Explanation: The function all() returns Answer: c
‘True’ if any one or more of the elements of Explanation: The built-in function chr()
the iterable are non zero. In the above case, returns the alphabet corresponding to the
the values are not iterable, hence an error is value given as an argument. This function
thrown. accepts only integer type values. In the first
function, we have passed a string. Hence the
10. What will be the output of the following first function throws an error.
Python function?
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
b) 1 (2, 0)
c) 2j
d) 1+2j c)
ww
Explanation: The built-in function complex()
returns the argument in a complex form.
Hence the output of the function shown above
(2.0, 0.0)
w.E
will be 1+2j.
(2, 0.5)
complex()?
a) 0j asy (2)
Answer: c
b) 0+0j
c) 0
En Explanation: See python documentation for
the function divmod.
d) Error
Answer: a gin
ee
Explanation: The complex function returns
0j if both of the arguments are omitted, that
is, if the function is in the form of complex()
6. The function complex(‘2-3j’) is valid but
rin
the function complex(‘2 – 3j’) is invalid.
a) True
or complex(0), then the output will be 0j.
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 and the second function adds 3 zeros after the
Python functions? given number.
x=3
eval('x^2')
ww
a) Error
b) 1
c) 9
10. Which of the following functions does not
necessarily accept only iterables as
arguments?
w.E
d) 6
Answer: b
a) enumerate()
b) all()
c) chr()
asy
Explanation: The function eval is use to
evaluate the expression that it takes as an
d) max()
Answer: c
En
argument. In the above case, the eval()
function is used to perform XOR operation Explanation: The functions enumerate(), all()
and max() accept iterables as arguments
gin
between 3 and 2. Hence the output is 1.
float('1e-003')
float('2e+003')
ee note that the function chr() accepts only
integer values.
rin
1. Which of the following functions accepts
a) a) ord() g.n
only integers as arguments?
3.00
300
b) min()
c) chr()
d) any()
et
b) Answer: c
Explanation: The function chr() accepts only
0.001 integers as arguments. The function ord()
accepts only strings. The functions min() and
2000.0
max() can accept floating point as well as
c) integer arguments.
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
list, we use: list(reversed(l)). The output will Error
be: [4,3,2].
Answer: b
3. What will be the output of the following Explanation: The built-in function ord() is
Python function? used to return the ASCII value of the alphabet
ww
float(' -12345\n')
passed to it as an argument. Hence the first
function results in an error and the output of
the second function is 65.
w.E
(Note that the number of blank spaces before
the number is 5)
a) -12345.0 (5 blank spaces before the
number)
b) -12345.0 asy 5. What will be the output of the following
Python function?
c) Error
En
d) -12345.000000000…. (infinite decimal float(‘-infinity’)
float(‘inf’)
places)
Answer: b
gin a)
Explanation: The function float() will
ee
remove all the blank spaces and convert the
integer to a floating point number. Hence the
–inf
inf
rin
output will be: -12345.0.
ord(65)
ord(‘A’)
–infinity
inf et
c)
a) Error
A Error
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()
b) divmod() len(["hello",2, 4, 6])
c) all()
d) float() a) 4
b) 3
Answer: d c) Error
ww
Explanation: The built-in functions min(),
max(), divmod(), ord(), any(), all() etc throw
d) 6
Answer: a
w.E
an error when no arguments are passed to
them. However there are some built-in
functions like float(), complex() etc which do
Explanation: The function len() returns the
length of the number of elements in the
iterable. Therefore the output of the function
asy
not throw an error when no arguments are
passed to them. The output of float() is 0.0. shown above is 4.
En
7. What will be the output of the following
Python function?
10. What will be the output of the following
Python function?
hex(15)
gin oct(7)
oct(‘7’)
a) f
b) 0xF
c) 0Xf
ee a)
Error rin
d) 0xf
Answer: d
07
g.n
Explanation: The function hex() is used to
convert the given argument into its
hexadecimal representation, in lower case.
b)
0o7
et
Hence the output of the function hex(15) is Error
0xf.
c)
8. Which of the following functions does not
throw an error? 0o7
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!'
c)
TOPIC 3.3.2 USER DEFINED
FUNCTIONS Hello
Hello
ww
1. Which of the following is the use of
function in python?
a) Functions are reusable pieces of programs
d) None of the mentioned
w.E
b) Functions don’t provide better modularity
for your application
c) you can’t also create your own functions
Answer: a
Explanation: Functions are defined using the
def keyword. After this keyword comes an
d) All of the mentioned
Answer: a
asy identifier name for the function, followed by
a pair of parentheses which may enclose
some names of variables, and by the final
En
Explanation: Functions are reusable pieces
of programs. They allow you to give a name
colon that ends the line. Next follows the
block of statements that are part of this
gin
to a block of statements, allowing you to run
that block using the specified name anywhere
function.
b) Define
c) Def g.n
3. # End of function #
d) Function
Answer: c
Explanation: None.
4.
et
5. sayHello() # call the function
6. sayHello() # call the function agai
n
3. What will be the output of the following
Python code? 4. What will be the output of the following
Python code?
1. def sayHello():
1. def printMax(a, b):
2. print('Hello World!')
2. if a > b:
3. sayHello()
3. print(a, 'is maximum')
4. sayHello()
4. elif a == b:
a)
ww
Explanation: Here, we define a function
called printMax that uses two parameters
called a and b. We find out the greater
the function definition.
Next, we assign the value 2 to x. The name x
w.E
number using a simple if..else statement and
then print the bigger number.
is local to our function. So, when we change
the value of x in the function, the x defined in
the main block remains unaffected.
4.
5.
x = 2 ee
print('Changed local x to', x)
Python code?
1. x = 50
rin
6. func(x)
2. def func():
3. global x g.n
a)
7. print('x is now', x)
4.
5.
print('x is', x)
x = 2
et
x is 50
6. print('Changed global x to', x)
Changed local x to 2
7. func()
x is now 50
8. print('Value of x is', x)
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
use default values in case the user does not
x is 50
want to provide values for them. This is done
Changed global x to 50 with the help of default argument values. You
can specify default argument values for
Value of x is 50 parameters by appending to the parameter
ww
d) None of the mentioned
name in the function definition the
assignment operator (=) followed by the
default value.
w.E
Answer: b
Explanation: The global statement is used to
declare that x is a global variable – hence,
The function named say is used to print a
string as many times as specified. If we don’t
supply a value, then by default, the string is
asy
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.
printed just once. We achieve this by
specifying a default argument value of 1 to
En
7. What will be the output of the following
the parameter times.
In the first usage of say, we supply only the
Python code?
gin string and it prints the string once. In the
second usage of say, we supply both the
string and an argument 5 stating that we want
1. def say(message, times = 1):
2. print(message * times)
3. say('Hello')
ee to say the string message 5 times.
rin
4. say('World', 5) Python code? g.n
8. What will be the output of the following
a)
Hello 2.
et
1. def func(a, b=5, c=10):
print('a is', a, 'and b is', b,
'and c is', c)
WorldWorldWorldWorldWorld
3.
b)
4. func(3, 7)
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
ww
a is 25 and b is 5 and c is 24
else:
w.E
d) None of the mentioned 7. return y
Answer: c
asy
Explanation: If you have some functions
8.
9. print(maximum(2, 3))
En
with many parameters and you want to
specify only some of them, then you can give a) 2
gin
values for such parameters by naming them –
this is called keyword arguments – we use the
name (keyword) instead of the position
b) 3
c) The numbers are equal
d) None of the mentioned
(which we have been using all along) to
specify the arguments to the function. ee
The function named func has one parameter
Answer: b
rin
Explanation: The maximum function returns
without a default argument value, followed
by two parameters with default argument
values. g.n
the maximum of the parameters, in this case
the numbers supplied to the function. It uses a
simple if..else statement to find the greater
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?
ww a) sqrt
T.
2. What are the two main types of functions? b) rhombus
w.E
a) Custom function
b) Built-in function & User defined function
c) add
d) rhombus
O
c) User function
d) System function
En
Explanation: Built-in functions and user contained within external modules, which
G
defined ones. The built-in functions are part must be imported and functions defined by a
gin
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.
rin
.B
c) Another function
d) All of the mentioned 1. def cube(x):
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
ww
w.E
a syE
ngi
nee
rin
g.n
et
ww
a)
4. print C2F(0)
27
w.E
212
32
c)
567
b) asy 98
314
En d) None of the mentioned
Answer: b
24
c)
gin Explanation: The arguments in Python
functions may have implicit values. An
567
98
ee implicit value is used, if no value is provided.
Here we created a power function. The
rin
function has one argument with an implicit
value. We can call the function with one or
d) None of the mentioned
two arguments.
g.n
Answer: a
Explanation: The code shown above is used
to convert a temperature in degree celsius to
Python code?
1. def sum(*args):
et
10. What will be the output of the following
fahrenheit.
2. '''Function returns the sum
9. What will be the output of the following
Python code? 3. of all values'''
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__
ww
c)
Answer: a
Explanation: The lambda keyword creates an
anonymous function. The x is a parameter,
w.E
123
12345
that is passed to the lambda function. The
parameter is followed by a colon character.
The code next to the colon is the expression
d) None of the mentioned
asy that is executed, when the lambda function is
called. The lambda function is assigned to the
Answer: a
En
Explanation: We use the * operator to
z variable.
The lambda function is executed. The number
gin
indicate, that the function will accept
arbitrary number of arguments. The sum()
function will return the sum of all arguments.
8 is passed to the anonymous function and it
returns 48 as the result. Note that z is not a
name for this function. It is only a variable to
ee
The first string in the function body is called
the function documentation string. It is used
to document the function. The string must be
which the anonymous function was assigned.
rin
3. What will be the output of the following
Python code?
in triple quotes.
a) 15
et
b) pi b) 555
c) anonymous c) 125
d) none of the mentioned d) None of the mentioned
Answer: a Answer: c
Explanation: Python supports the creation of Explanation: None.
anonymous functions (i.e. functions that are
not bound to a name) at runtime, using a 4. Does Lambda contains return statements?
construct called lambda. Lambda functions a) True
are restricted to a single expression. They can b) False
be used wherever normal functions can be
used.
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. d) None of the mentioned
a) True
b) False Answer: b
Explanation: None.
Answer: b
Explanation: lambda is an anonymous
ww
function in Python. Hence this statement is
false.
9. What will be the output of the following
Python code?
w.E
6. Lambda contains block of statements.
a) True
1. L = [lambda x: x ** 2,
2. lambda x: x ** 3,
b) False
Explanation: None.
En 4.
5. for f in L:
Python code? gin
7. What will be the output of the following
6. print(f(3))
27
rin
a) 432
b) 24000
81
g.n
c) 430
d) No output
Answer: a
343
b) et
6
Explanation: None.
9
8. What will be the output of the following
Python code? 12
1. def writer(): c)
2. title = 'Sir' 9
ww
b) 9999
c) 9996
d) None of the mentioned
reflected outside the function.
w.E
Answer: c
Explanation: None.
4. What will be the output of the following
Python code?
asy
1. What is a variable defined outside a
function referred to as?
def a(b):
b = b + [5]
a) A static variable
b) A global variable En c = [1, 2, 3, 4]
a(c)
print(len(c))
c) A local variable
d) An automatic variable gin a) 4
Answer: b ee
Explanation: The value of a variable defined
outside all function definitions is referred to
b) 5
c) 1
rin
d) An exception is thrown
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.
c)
8. If a function doesn’t have a return
10 statement, which of the following does the
20 function return?
a) int
ww
d) Syntax Error b) null
c) None
w.E
Answer: a
Explanation: The statement “global b”
allows the global value of b to be accessed
d) An exception is thrown without the return
statement
asy
and changed. Whereas the variable a is local
and hence the change isn’t reflected outside
the function.
Answer: c
Explanation: A function can exist without a
return statement and returns None if the
En
6. What will be the output of the following
function doesn’t have a return statement.
Python code?
gin 9. What will be the output of the following
Python code?
def change(i = 1, j = 2):
i = i + j
j = j + 1
print(i, j)
change(j = 1, i = 2)
ee def display(b, n):
while n > 0:
rin
print(b,end="")
n=n-1
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.
10. What will be the output of the following
7. What will be the output of the following Python code?
Python code?
def find(a, **b):
def change(one, *two): print(type(b))
print(type(two)) find('letters',A='1',B='2')
change(1,2,3,4)
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
d) two underscores followed by a valid
TOPIC 3.3 ARGUMENTS AND identifier
PARAMETERS
Answer: c
Explanation: Refer documentation.
ww
1. What is the type of each element in
sys.argv?
a) set 5. How many keyword arguments can be
w.E
b) list
c) tuple
d) string
passed to a function in a single function call?
a) zero
b) one
Answer: d asy
Explanation: It is a list of strings.
c) zero or more
d) one or more
Answer: b
ee 6. What will be the output of the following
Python code?
rin
Explanation: The first argument is the name
of the program itself. Therefore the length of
def foo(fname, val):
print(fname(val))
foo(max, [1, 2, 3]) g.n
sys.argv is one more than the number
arguments.
a) 3 1
b) 1 3
et
Python code? c) error
d) none of the mentioned
def foo(k):
k[0] = 1 Answer: a
q = [0]
foo(q) Explanation: It is possible to pass function
print(q) names as arguments to other functions.
ww
def foo():
total += 1
1. What will be the output of the following
Python code?
w.E
return total
total = 0
print(foo())
def foo(k):
k = [1]
q = [0]
a) 0
b) 1 asy foo(q)
print(q)
c) error
d) none of the mentioned
En a) [0]
b) [1]
Answer: c
gin
Explanation: It is not possible to change the
c) [1, 0]
d) [0, 1]
specifying it. ee
value of a global variable without explicitly
Answer: a
rin
Explanation: A new list object is created in
the function and the reference is lost. This can
9. What will be the output of the following
Python code?
and after k = [1]. g.n
be checked by comparing the id of k before
def foo(x):
x = ['def', 'abc']
return id(x)
q = ['abc', 'def']
et
2. How are variable length arguments
specified in the function heading?
a) one star followed by a valid identifier
print(id(q) == foo(q))
b) one underscore followed by a valid
identifier
a) True
c) two stars followed by a valid identifier
b) False
d) two underscores followed by a valid
c) None
identifier
d) Error
Answer: a
Answer: b
Explanation: Refer documentation.
Explanation: A new object is created in the
function. 3. Which module in the python standard
library parses options received from the
10. What will be the output of the following
command line?
Python code?
ww
Answer: b a) True
b) False
w.E
Explanation: It is a list of elements.
Answer: c
Explanation: Refer documentation. gin 9. Where are the arguments received from the
command line stored?
a) sys.argv
function heading? ee
6. How are default arguments specified in the
GLOBAL SCOPE a) 13
b) 10
1. What will be the output of the following c) 2
Python code? d) 5
ww
f1()
a) Error
incremented by one and printed. Hence the
output of the code shown above is 13.
w.E
b) 12
c) 15
d) 1512
4. What will be the output of the following
Python code?
Answer: c asy
Explanation: In the code shown above, x=15
def f1():
global x
x+=1
En
is a local variable whereas x=12 is a global
variable. Preference is given to local variable
x=12
print(x)
print("x")
ee
2. What will be the output of the following
Python code?
b) 13
c)
13
rin
def f1():
x=100
print(x)
x
g.n
x=+1
f1()
a) Error
d) x
Answer: d
et
Explanation: In the code shown above, the
b) 100 variable ‘x’ is declared as global within the
c) 101 function. Hence the output is ‘x’. Had the
d) 99 variable ‘x’ been a local variable, the output
would have been:
Answer: b 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)
world
16
hello b)
Answer: a world
ww
Explanation: The code shown above will
result in an error because ‘x’ is a global
variable. Had it been a local variable, the
hello
hello
w.E
output would be: 16
hello c)
asy hello
world
Python code?
En
6. What will be the output of the following
world
x=12
def f1(a,b=x): gin d)
x=15
f1(4)
print(a,b)
ee world
hello
rin
a) Error
b) 12 4
c) 4 12
world
Answer: b g.n
d) 4 15
Answer: c
Explanation: At the time of leader
et
Explanation: Since the variable ‘a’ has been
explicitly specified as a global variable, the
value of a passed to the function is ‘world’.
Hence the output of this code is:
processing, the value of ‘x’ is 12. It is not world
modified later. The value passed to the hello
function f1 is 4. Hence the output of the code hello
shown above is 4 12.
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
ww
9. What will be the output of the following
Answer: a
T.
Python code?
Explanation: The error will be caused due to
w.E
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 asy SP
different and there would be no error.
print(p,q,r,s)
gin x = 5
LO
a) 1 2 3 4 def f1():
b) 5 10 15 4
c) 10 20 30 40
ee global x
x = 4
def f2(a,b):
rin
.B
d) 5 10 15 40 global x
return a+b+x
Answer: c f1()
g.n
17
def f(x):
print("outer") Answer: b
def f1(a): Explanation: In the code shown above, the
C
print("inner")
variable ‘x’ has been declared as a global
print(a,x)
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
b) 90 def cg():
c) 80 global x
x=x+1
d) Error cg()
x
Answer: a
ww
Explanation: The output of the code shown
above is 100. This is because the variable ‘x’
has been declared as global within the
a) 2
b) 1
w.E
functions f1 and f2.
asy
and point out the global variables?
Answer: a
Explanation: Since ‘x’ has been declared a
global variable, it can be modified very easily
y, z = 1, 2
def f():
global x En within the function. Hence the output is 2.
x = y+z
gin 3. On assigning a value to a variable inside a
function, it automatically becomes a global
a) x
b) y and z
c) x, y and z
d) Neither x, nor y, nor z
ee variable.
a) True
b) False
rin
Answer: c
Explanation: In the code shown above, x, y
Answer: b
g.n
Explanation: On assigning a value to a
variable inside a function, t automatically
and z are global variables inside the function
f. y and z are global because they are not
assigned in the function. x is a global variable
statement is false. et
becomes a local variable. Hence the above
because it is explicitly specified so in the 4. What will be the output of the following
code. Hence, x, y and z are global variables. Python code?
error
ww
5. What happens if a local variable exists with
the same name as the global variable you
want to access?
the local namespace and does not affect the
global namespace. Hence the output is 1.
w.E
a) Error
b) The local variable is shadowed
c) Undefined behavior
8. ______________ returns a dictionary of
the module namespace.
________________ returns a dictionary of
asy
d) The global variable is shadowed
Answer: d
the current namespace.
a)
En
Explanation: If a local variable exists with
the same name as the local variable that you
locals()
gin
want to access, then the global variable is
shadowed. That is, preference is given to the
globals()
b)
local variable.
ee
6. What will be the output of the following
Python code?
locals()
locals() rin
a=10 c) g.n
globals()['a']=25
print(a)
a) 10
globals()
locals()
et
b) 25
c) Junk value d)
d) Error
globals()
Answer: b globals()
Explanation: In the code shown above, the
value of ‘a’ can be changed by using globals() Answer: c
function. The dictionary returned is accessed Explanation: The function globals() returns a
using key of the variable ‘a’ and modified to dictionary of the module namespace, whereas
25. the function locals() returns a dictionary of
the current namespace.
7. What will be the output of the following
Python code?
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)
b) A function execution instance that calls b) (num-1)*(num-2)
another execution instance of the same c) num*(num-1)
function d) fact(num)*fact(num-1)
c) A class method that calls another class
method Answer: a
ww
d) An in-built method that is automatically
called
Explanation: Suppose n=5 then, 5*4*3*2*1
is returned which is the factorial of 5.
w.E
Answer: b
Explanation: The appropriate definition for a
5. What will be the output of the following
Python code?
asy
recursive function is a function execution
instance that calls another execution instance
of the same function either directly or
def test(i,j):
if(i==0):
indirectly.
En return j
else:
return test(i-1,i+j)
a) True
b) False
Answer: b
ee a) 13
b) 7
c) Infinite loop
d) 17 rin
Explanation: There are many other problems
can also be solved using recursion. Answer: d
g.n
Explanation: The test(i-1,i+j) part of the
3. Which of these is false about recursion?
a) Recursive function can be replaced by a
non-recursive function
et
function keeps calling the function until the
base condition of the function is satisfied.
b) Recursive functions usually take more 6. What will be the output of the following
memory space than non-recursive function Python code?
c) Recursive functions run faster than non-
recursive function l=[]
def convert(b):
d) Recursion makes programs easier to 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="")
ww
c) A recursive function where the function
doesn’t return anything and just prints the
Python code?
w.E
values
d) A function where the recursive call is the
last thing executed by the function
def fun(n):
if (n > 100):
return n - 5
return fun(fun(n+11));
Answer: d
asy
Explanation: A recursive function is tail
print(fun(45))
En
recursive when recursive call is executed by
the function in the last.
a) 50
b) 100
gin
8. Observe the following Python code?
c) 74
d) Infinite loop
def a(n):
if n == 0:
return
else:
0
ee Answer: b
rin
Explanation: The fun(fun(n+11)) part of the
code keeps executing until the value of n
return
def b(n, tot):
if n == 0:
n*a(n - 1)
returned and printed.
g.n
becomes greater than 100, after which n-5 is
return
else:
return
tot
b(n-2, tot-2)
programming approach.
a) True
et
11. Recursion and iteration are the same
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
ww
d) Sequence generation is easier than a nested DICTIONARIES
T.
iteration
w.E
Answer: c
TOPIC 4.1 LISTS ( LIST
O
Explanation: Recursive calls take up a lot of OPERATIONS, LIST SLICES,
LIST METHODS, LIST LOOP,
time the function is called.
asy
memory and time as memory is taken up each
SP
MUTABILITY, ALIASING,
CLONING LISTS, LIST
En
14. Which of these is not true about
PARAMETERS)
G
recursion?
gin
a) It’s easier to code some real-world
LO
problems using recursion than non-recursive 1. Which of the following commands will
equivalent
ee
b) Recursive functions are easy to debug
c) Recursive calls take up a lot of memory
create a list?
a) list1 = list()
b) list1 = []
rin
.B
Answer: b Answer: d
Explanation: Recursive functions may be
hard to debug as the logic behind recursion et
Explanation: Execute in the shell to verify
-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
ww
Answer: c
Explanation: Max returns the maximum
a) Error
b) None
w.E
element in the list.
min(list1)?
a) 3
b) 5 asy Answer: c
Explanation: -1 corresponds to the last index
in the list.
c) 25
d) 1 En 10. Suppose list1 is [2, 33, 222, 14, 25], What
rin
d) [25, 14, 222, 33, 2]
sum(list1)?
a) 1
b) 9
Answer: a
g.n
Explanation: Execute in the shell to verify.
c) 15
d) Error et
1. What will be the output of the following
Python code?
12.
sum += 1
13. sum += 10
gin a) True
b) False
14.
15. print sum
ee c) Error
d) None
Answer: b rin
a) 11
b) 12 one. g.n
Explanation: Elements are compared one by
c) 21
d) 22
Answer: b
which command?
a) list1.add(5)
et
6. To add a new element to a list we use
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)
ww
Explanation: Execute in the shell to verify.
w.E
list1.index(5)?
a) 0
Answer: c
Explanation: pop() removes the element at
the position specified in the parameter.
b) 1
c) 4
d) 2 asy 4. Suppose listExample is [3, 4, 5, 20, 5, 25,
1, 3], what is list1 after listExample.pop()?
details. gin
Explanation: Execute help(list.index) to get c) [3, 5, 20, 5, 25, 1, 3]
d) [1, 3, 4, 5, 20, 5, 25]
what is list1.count(5)?
a) 0
ee
10. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], Answer: a
rin
Explanation: pop() by default will remove
the last element.
b) 4
c) 1
d) 2 g.n
5. What will be the output of the following
Python code?
Answer: d
Explanation: Execute in the shell to verify.
et
1. >>>"Welcome to Python".split()
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
Python code? Python code?
ww 3. indexOfMax = 0 3. >>>list1[0] = 4
w.E
4. for i in range(1, len(myList)):
5. if myList[i] > max:
4. >>>print(list2)
a) [1, 3]
6.
7.
asy
max = myList[i]
b) [4, 3]
c) [1, 4]
d) [1, 3, 4]
8.
indexOfMax = i
En Answer: b
Answer: a
1. def f(values):
2. g.n
values[0] = 44
Explanation: First time the highest number is
encountered is at index 1. 3.
4. v = [1, 2, 3]
et
8. What will be the output of the following
Python code? 5. f(v)
1. myList = [1, 2, 3, 4, 5, 6] 6. print(v)
2. for i in range(1, 6): 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? ]
ww 7. v = f(3)
8. print(v)
Answer: d
Explanation: List Comprehension are a
w.E
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3]
shorthand for creating new lists.
gin
2. What will be the output of the following
3. numbers.append([5,6,7,8])
Python code?
ee
1. names1 = ['Amir', 'Bala', 'Chales']
4.
rin
5. print(len(numbers))
2.
3. if 'amir' in names1:
a) 4
b) 5
c) 8 g.n
4.
5. else:
print(1)
d) 12
Answer: b
et
Explanation: A list is passed in append so the
6. print(2) length is 5.
ww
d) 8
Answer: d
None
w.E
Explanation: + appends all the elements
individually into a new list.
b)
[3, 4, 5]
Python code?
asy
7. What will be the output of the following
None
1. def addItem(listParam):
En c)
[1, 2, 3]
2.
3.
listParam += [1]
gin [3, 4, 5]
4. mylist = [1, 2, 3, 4]
5. addItem(mylist)
ee d)
[1, 2, 3]
rin
6. print(len(mylist)) [3, 4, 5]
g.n
a) 1
b) 4
c) 5
None
Answer: a et
Explanation: Execute in the shell to verify.
d) 8
Answer: c
Explanation: + will append the element to 9. What will be the output of the following
the list. Python code?
ww
d) Return a list containing the items from L
starting from index 0, omitting every third a) 8
r y in range(0, 4)]
w.E
item
Answer: a
b) 12
c) 16
d) 32
asy
Explanation: Run the code to get a better
understanding with many arguments. Answer: c
En
10. What will be the output of the following
Python code?
Explanation: Execute in the shell to verify.
gin
1. veggies = ['carrot', 'broccoli', 'p
Python code?
otato', 'asparagus']
ee
2. veggies.insert(veggies.index('brocc
oli'), 'celery')
1. values = [[3, 4, 5, 1], [33, 6, 1,
2.
2]]
rin
3. print(veggies)
7. v = values[row][column]
d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’,
‘asparagus’] 8.
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
ww 5.
6.
for element in lst:
if v > element:
2.
3.
[4, 5, 6, 7],
w.E
7. v = element 4. [12, 13, 14, 15]]
8.
9. print(v) asy 5.
6. for i in range(0, 4):
a) 1
En 7. print(matrix[i][1], end = " ")
b) 3
c) 5
d) 6
gin a) 1 2 3 4
b) 4 5 6 7
Answer: a ee
Explanation: Execute in the shell to verify.
c) 1 3 8 12
d) 2 5 9 13
Answer: d rin
5. What will be the output of the following
Python code? g.n
Explanation: Execute in the shell to verify.
2.
2. v = list[0]
3. for row in values:
3. for e in list:
4. row.sort()
4. 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
d) 5 33 b) 2
c) 4
Answer: d d) 5
Explanation: Execute in the shell to verify.
Answer: c
ww
8. What will be the output of the following
Python code?
Explanation: Execute in the shell to verify.
w.E
1. data = [[[1, 2], [3, 4]], [[5, 6],
[7, 8]]]
Python code?
2. points.sort()
a) 1
En 3. print(points)
b) 2
c) 4
d) 5 gin a) [[1, 2], [3, 1.5], [0.5, 0.5]]
b) [[3, 1.5], [1, 2], [0.5, 0.5]]
Answer: d ee
Explanation: Execute in the shell to verify.
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
d) [[0.5, 0.5], [3, 1.5], [1, 2]]
Answer: c rin
9. What will be the output of the following
Python code? g.n
Explanation: Execute in the shell to verify.
2. b=list(a)
a[3][0]=95
3. def ttt(m): a[1]=34
print(b)
4. v = m[0][0]
a) [10,34,56,[95]]
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
ww
[(2,4),(‘b’,’c’),(‘yy’,’xx’)]
b)
[‘a’,’b’,’c’,’d’]
w.E
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’
‘)]
[‘a’,’b’,’c’,’d’]
b)
asy
[(2, 'b', 'yy'), (4, 'c', 'xx')] [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
c) Syntax error
d) En [‘a’,’b’,’c’,’d’]
[‘a’,’@’,’@d’]
[(2, 'b', 'yy'), (4, 'c', 'xx')]
Answer: d ee
Explanation: The zip function combines the
[‘a’,’b’,’c’,’d’]
d) rin
individual attributes of the lists into a list of
tuples. [‘a’,’@’,’@d’]
g.n
3. What will be the output of the following
Answer: c
et
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
] 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
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
to all the sublists.
6. What will be the output of the following
Python code? 9. What will be the output of the following
ww
a="hello"
b=list((x.upper(),len(x)) for x in a)
Python code?
b=[2,3,4,5]
w.E
print(b)
a) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
a=list(filter(lambda x:x%2,b))
print(a)
b) [(‘HELLO’, 5)]
asy
c) [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
d) Syntax error
a) [2,4]
b) [ ]
c) [3,5]
Answer: a En d) Invalid arguments for filter function
gin
Explanation: Variable x iterates over each
letter in string a hence the length of each
Answer: c
Explanation: The filter function gives value
letter is 1.
ee
7. What will be the output of the following
Python code?
from the list b for which the condition is true,
that is, x%2==1.
rin
10. What will be the output of the following
a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))
Python code?
lst=[3,4,6,1,2]
g.n
]
print(b)
a) 10
lst[1:2]=[7,8]
print(lst)
a) [3, 7, 8, 6, 1, 2]
et
b) [1,3,5,7] b) Syntax error
c) 4 c) [3,[7,8],6,1,2]
d) [1,3,6,10] d) [3,4,6,7,8]
Answer: d Answer: a
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?
1. What will be the output of the following
a=[[]]*3
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
Explanation: The append function simply
b) adds its arguments to the list as it is while
extend function extends its arguments and
[1, 2, 3, 4] later appends it.
ww
None
c) Syntax error
4. What is the output of the following piece of
code?
d)
w.E
[1,2,3]
a=list((45,)*4)
print((45)*4)
print(a)
[1,2,3,4]
Answer: b
asy a)
En
Explanation: Append function on lists
doesn’t return anything. Thus the value of b is
180
None.
gin [(45),(45),(45),(45)]
b)
ee
2. What will be the output of the following
Python code?
(45,45,45,45)
[45,45,45,45]
rin
>>> a=[14,52,7]
c)
g.n
>>>> b=a.copy()
>>> b is a
a) True
b) False
180
[45,45,45,45]
et
d) Syntax error
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
be reflected in list a. multiplied, it created references of itself
which is later converted to a list.
3. What will be the output of the following
Python code? 5. What will be the output of the following
a=[13,56,17]
Python code?
a.append([87])
lst=[[1,2],[3,4]]
print(sum(lst,[]))
ww
list1=[1,2,3]
list2=[1,2,3]
print(word1 is word2)
8. What will be the output of the following
Python code?
a)w.E
print(list1 is list2)
places = ['Bangalore', 'Mumbai', 'Delhi']
<br class="blank" />places1 = places
True
asy places2 = places[:]
<br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
True
b) En print(places)
c)
ee d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
Answer: b
rin
Explanation: places1 is an alias of the list
False
g.n
places. Hence, any change made to places1 is
reflected in places. places2 is a copy of the
False
d)
isn’t reflected in places.
et
list places. Thus, any change made to places2
Answer: a
7. What will be the output of the following
Explanation: The elements 1 and 2 are first
Python code?
ww
Answer: c
Explanation: First, map converts the number
c)
w.E
to string and then places the individual digits
in a list. Then, sum finds the sum of the digits
in the list. The code basically finds the sum of
[1,2,3]
d)
digits in the number.
asy
11. What will be the output of the following
1
Python code?
En [44,2,3]
a= [1, 2, 3, 4, 5]
for i in range(1, 5): gin Answer: a
Explanation: A list is mutable, hence it’s
a[i-1] = a[i]
for i in range(0, 5):
print(a[i],end = " ")
a) 5 5 1 2 3
ee value changes after function call. However,
integer isn’t mutable. Thus its value doesn’t
change.
rin
b) 5 1 2 3 4
c) 2 3 4 5 1 g.n
13. What will be the output of the following
d) 2 3 4 5 5
Answer: d
Explanation: The items having indexes from
Python code?
a =
<br
[1, 5, 7, 9, 9, 1]
class="blank" />b=a[0]
et
1 to 4 are shifted forward by one index due to <br class="blank" />x= 0
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 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"]
<br class="blank" />a.sort(key=len) print(k)
print(a)
a) all characters of my_string that aren’t
a) [‘Apple’, ‘Ball’, ‘Cobra’] vowels
b) [‘Ball’, ‘Apple’, ‘Cobra’] b) a list of Nones
ww
c) [‘Cobra’, ‘Apple’, ‘Ball’]
d) Invalid syntax for sort()
c) list of Trues
d) list of Falses
w.E
Answer: b
Explanation: The syntax isn’t invalid and the
list is sorted according to the length of the
Answer: b
Explanation: print() returns None.
asy
strings in the list since key is given as len.
Python code?
En my_string = "hello world"
k = [(i.upper(), len(i)) for i in my_stri
num = ['One', 'Two', 'Three']
for i, x in enumerate(num): gin ng]
print(k)
print('{}: {}'.format(i, x),end=" ")
a) 1: 2: 3:
b) Exception is thrown
ee a) [(‘HELLO’, 5), (‘WORLD’, 5)]
b) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1),
rin
(‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1),
(‘D’, 1)]
c) One Two Three
d) 0: One 1: Two 2: Three c) [(‘HELLO WORLD’, 11)]
d) none of the mentioned g.n
Answer: d
Explanation: enumerate(iterator,start=0) is a
built-in function which returns (0,lst[0]),
Answer: b et
Explanation: We are iterating over each letter
in the string.
(1,lst[1]) and so on where lst is a list(iterator).
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)]?
k = [print(i) for i in my_string if i not a)
in "aeiou"]
list_1 = []
a) prints all the vowels in my_string for i in list_0:
b) prints all the consonants in my_string if func(i):
c) prints all characters of my_string that list_1.append(i)
aren’t vowels
b)
d) prints only on executing print(k)
Answer: c Answer: d
Explanation: We have to create an empty list, Explanation: If it were to be executed as a
ww
loop over the contents of the existing list and
check if a condition is satisfied before
performing some operation and adding it to
nested for loop, i would be the outer loop and
j the inner loop.
w.E
the new list.
a) [0, 1, 2] En
x = [i**+1 for i in range(3)]; print(x);
a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’,
‘fc’]
b) [1, 2, 5]
c) error, **+ is not a valid operator gin b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’,
‘bf’, ‘cf’]]
d) error, ‘;’ is not allowed
Answer: a
ee
Explanation: i**+1 is evaluated as (i)**(+1).
c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’,
‘fb’, ‘fc’]]
rin
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
‘cf’]
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.
1. What will be the output of the following For example if we have a list l=[-65, 2, 7, -99,
Python code? -4, 3]
>>> [x for x in l if x<0]
l=[1,2,3,4,5] The output would be: [-65, -99, -4].
ww
[x&1 for x in l]
w.E
b) [1, 0, 1, 0, 1]
c) [1, 0, 0, 0, 0]
d) [0, 1, 0, 1, 0]
Python code?
En
Explanation: In the code shown above, each
of the numbers of the list, that is, 1, 2, 3, 4
b) [‘PUNE’, 4, ‘MUMBAI’, 6, ‘DELHI’, 5]
c) [PUNE, 4, MUMBAI, 6, DELHI, 5]
gin
and 5 are AND-ed with 1 and the result is
printed in the form of a list. Hence the output
is [1, 0, 1, 0, 1].
d) [(‘PUNE’, 4), (‘MUMBAI’, 6), (‘DELHI’,
5)]
Python code?
ee
2. What will be the output of the following
Answer: d
rin
Explanation: If we need to generate two
results, we need to put it in the form of a
tuple. The code shown above returns each
l1=[1,2,3]
l2=[4,5,6] g.n
word of list in uppercase, along with the
length of the word. Hence the output of the
[x*y for x in l1 for y in l2]
l1=[2,4,6]
Answer: c l2=[-2,-4,-6]
Explanation: The code shown above returns for i in zip(l1, l2):
x*y, where x belongs to the list l1 and y print(i)
belongs to the list l2. Therefore, the output is:
[4, 5, 6, 8, 10, 12, 12, 15, 18]. a)
Answer: c 1 4 7
ww
Explanation: The output of the code shown
will be:
(2, -2)
2 5 8
3 6 9
w.E
(4, -4)
(6, -6)
This format is due to the statement print(i).
d)
asy
6. What will be the output of the following
(1 4 7)
(2 5 8)
Python code?
En (3 6 9)
l1=[10, 20, 30]
l2=[-10, -20, -30]
l3=[x+y for x, y in zip(l1, l2)] gin Answer: b
Explanation: In the code shown above, ‘3’ is
l3
a) Error
b) 0
ee the index of the list. Had we used a number
greater than 3, it would result in an error. The
rin
output of this code is: [[1, 4, 7], [2, 5, 8], [3,
6, 9]].
c) [-20, -60, -80]
d) [0, 0, 0]
g.n
Answer: d
Explanation: The code shown above returns
x+y, for x belonging to the list l1 and y Python code?
et
9. What will be the output of the following
Answer: a Answer: c
Explanation: The list comprehension to print Explanation: The list comprehension shown
ww 1 4 7
2 5 8
b) [‘97’, ‘98’, ‘99’]
c) [65, 66, 67]
d) Error
w.E3 6 9
Answer: a
Explanation: The list comprehension shown
b)
(2 5 8)
En is: [97, 98, 99]. Had the string been ‘ABC’,
the output would be: [65, 66, 67].
(3 6 9)
gin 3. What will be the output of the following
Python code?
c) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
d) Error
Answer: a
ee t=32.00
rin
[round((x-32)*5/9) for x in t]
Answer: d
et
Explanation: The value of t in the code
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.
w="hello" 4. Write a list comprehension for producing a
v=('a', 'e', 'i', 'o', 'u')
list of numbers between 1 and 1000 that are
divisible by 3.
a) [x for w in v if x in v]
a) [x in range(1, 1000) if x%3==0]
b) [x for x in w if x in v]
b) [x for x in range(1000) if x%3==0]
c) [x for x in v if w in v]
c) [x%3 for x in range(1, 1000)]
d) [x for v in w for x in w]
d) [x%3=0 for x in range(1, 1000)]
ww
(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)==
(i*0.5)]
a) [x for x in range(1, 20) if (x%2==0)]
b) [x for x in range(0, 20) if (x//2==0)]
w.E
c) [i for i in range(1, 101) if int(i*0.5)=
(i*0.5)]
d) [i for i in range(1, 100) if int(i*0.5)=
c) [x for x in range(1, 20) if (x//2==0)]
d) [x for x in range(0, 20) if (x%2==0)]
(i*0.5)]
asy Answer: d
Explanation: The required list
Answer: b
En
Explanation: The code shown above prints
the value ‘i’ only if it satisfies the condition:
comprehension will print a whole number,
less than 20, provided that the number is
gin
int(i*0.5) is equal to (i*0.5). Hence the
required list comprehension is: [i for i in
even. Since the output list should contain zero
as well, the answer to this question is: [x for x
in range(0, 20) if (x%2==0)].
range(1, 101) if int(i*0.5)==(i*0.5)].
ee
6. What is the list comprehension equivalent
for: list(map(lambda x:x**-1, [1, 2, 3]))?
9. What will be the output of the following
rin
Python list comprehension?
Answer: c
et
a) A list of prime numbers up to 50
b) A list of numbers divisible by 2, up to 50
c) A list of non prime numbers, up to 50
Explanation: The output of the function d) Error
list(map(lambda x:x**-1, [1, 2, 3])) is [1.0,
Answer: c
0.5, 0.3333333333333333] and that of the list
Explanation: The list comprehension shown
comprehension [x**-1 for x in [1, 2, 3]] is
above returns a list of non-prime numbers up
[1.0, 0.5, 0.3333333333333333]. Hence the
to 50. The logic behind this is that the square
answer is: [x**-1 for x in [1, 2, 3]].
root of 50 is almost equal to 7. Hence all the
7. Write a list comprehension to produce the multiples of 2-7 are not prime in this range.
list: [1, 2, 4, 8, 16……212].
10. What will be the output of the following
a) [(2**x) for x in range(0, 13)]
Python code?
b) [(x**2) for x in range(1, 13)]
ww
any punctuation is ‘good’. Hence the output
of the code shown above is [‘good’].
A[1]
a) [4, 5, 6]
w.E
1. Which of the following matrices will throw
an error in Python?
a)
b) [3, 6, 9]
c) [1, 4, 7]
d) [1, 2, 3]
b)
[7, 8, 9]]
B = [[3, 3, 3]
[4, 4, 4]
ee 3. Which of the following Python statements
rin
will result in the output: 6?
[5, 5, 5]]
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]] g.n
c)
C = [(1, 2, 4),
a) A[2][3]
b) A[2][1]
c) A[1][2]
et
(5, 6, 7),
d) A[3][2]
(8, 9, 10)]
Answer: c
d) Explanation: The output that is required is 6,
that is, row 2, item 3. This position is
D = [2, 3, 4, represented by the statement: A[1][2].
3, 3, 3,
4. What will be the output of the following
4, 5, 6] Python code?
ww
[2, 5, 8].
w.E
Python code?
A = [[1, 2, 3],
a) [[11, 12, 13], [14, 15, 16], [17, 18, 19]]
b) Error
[4,
[7,
[A[i][i]
5, 6],
8, 9]]
asy
for i in range(len(A))]
c) [11, 12, 13], [14, 15, 16], [17, 18, 19]
d) [11, 12, 13, 14, 15, 16, 17, 18, 19]
a) [1, 5, 9] En Answer: a
Explanation: The code shown above shows a
b) [3, 5, 7]
c) [4, 5, 6] gin list comprehension which adds 10 to each
element of the matrix A and prints it row-
d) [2, 5, 8]
Answer: a ee
Explanation: We can also perform tasks like
wise. Hence the output of the code is: [[11,
12, 13], [14, 15, 16], [17, 18, 19]]
rin
8. What will be the output of the following
pulling out a diagonal. The expression shown
above uses range to generate the list of offsets
and the indices with the row and column the
Python code?
A = [[1, 2, 3],
g.n
same, picking out A[0][0], then A[1][1] and
so on. Hence the output of the code is: [1, 5,
9].
[4, 5, 6],
[7, 8, 9]] et
[A[i][len(A)-1-i] for i in range(len(A))]
a) [1, 5, 9]
6. What will be the output of the following b) [4, 5, 6]
Python code? c) [3, 5, 7]
l=[[1, 2, 3], [4, 5, 6]]
d) [2, 5, 8]
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].
ww
d) 0
Answer: a
a) [0, 30, 60, 120, 160, 200, 300, 350, 400]
b) [[3, 6, 9], [16, 20, 24], [35, 40, 45]]
c) No output
w.E
Explanation: In the code shown above, we
have used list comprehension to combine
values of multiple matrices. We have
d) Error
Answer: b
asy
multiplied the elements of the matrix B with
that of the matrix A, in the range(3). Hence
Explanation: The list comprehension shown
above results in the output: [[3, 6, 9], [16, 20,
En
the output of this code is: [3, 6, 9, 16, 20, 24,
35, 40, 45].
24], [35, 40, 45]].
gin
10. What will be the output of the following
Python code?
12. What will be the output of the following
Python code?
a) [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20,
a) Address of the zip object
et
b) Address of the matrices A and B
c) No output
30, 40, 50, 60, 70, 80, 90] d) [3, 6, 9, 16, 20, 24, 35, 40, 45]
b) [10, 20, 30, 40, 50, 60, 70, 80, 90]
c) [11, 12, 13, 14, 15, 16, 17, 18, 19] Answer: a
d) [0, 10, 20, 30, 40, 50, 60, 70, 80] Explanation: The output of the code shown
above returns the address of the zip object. If
Answer: a we print it in the form of a list, we get:
Explanation: The code shown above adds 10 >>> list(zip(A, B))
to each element of the matrix and prints the [([1, 2, 3], [3, 3, 3]), ([4, 5, 6], [4, 4, 4]), ([7,
output row-wise. Since the list l already 8, 9], [5, 5, 5])]
contains some elements, the new elements are
appended to it. Hence the output of this code
a) (1, 2)
TOPIC 4.2 TUPLES (TUPLE
b) (1, 2, 4)
ASSIGNMENT, TUPLE AS c) (2, 4)
RETURN VALUE) d) (2, 4, 3)
ww
round brackets.
w.E
following is incorrect?
a) print(t[3])
b) t[3] = 45
a) [2, 3, 9]
b) [1, 2, 4, 3, 8, 9]
c) [1, 4, 8]
c) print(max(t))
d) print(len(t)) asy d) (1, 4, 8)
Answer: c
Answer: b
En
Explanation: Values cannot be modified in
Explanation: Execute in the shell to verify.
gin
the case of tuple, that is, tuple is immutable. 6. What will be the output of the following
Python code?
Python code?
1. >>>t=(1,2,4,3)
ee
3. What will be the output of the following
1. d = {"john":40, "peter":45}
2. d["john"] rin
2. >>>t[1:3] a) 40
b) 45
g.n
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
c) “john”
d) “peter” et
d) (2, 4, 3) Answer: a
Explanation: Execute in the shell to verify.
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) (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]
2. >>>t2 = (1, 2, 3, 4) a) 30
b) 24
3. >>>t1 < t2 c) 33
ww
a) True
b) False
d) 12
Answer: c
w.E
c) Error
d) None
Explanation: Tuples can be used for keys
into dictionary. The tuples can have mixed
length and the order of the items in the tuple
Answer: b
asy
Explanation: Elements are compared one by
one in this case.
is considered when comparing the equality of
the keys.
En
9. What will be the output of the following
1. What is the data type of (1)?
Python code?
gin a) Tuple
b) Integer
c) List
1. >>>my_tuple = (1, 2, 3, 4)
2. >>>my_tuple.append( (5, 6, 7) ) ee d) Both tuple and integer
Answer: b
rin
3. >>>print len(my_tuple)
a) 1
created as (1,).
g.n
Explanation: A tuple of one element must be
b) 2
c) 5
d) Error
et
2. If a=(1,2,3,4), a[1:-1] is _________
a) Error, tuple slicing doesn’t exist
b) [2,3]
c) (2,3,4)
Answer: d d) (2,3)
Explanation: Tuples are immutable and don’t
have an append method. An exception is Answer: d
thrown in this case. Explanation: Tuple slicing exists and a[1:-1]
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?
in the subtuple of b, False is printed.
>>> a=(1,2,3,4)
>>> del a
4. What will be the output of the following
Python code? a) No because tuple is immutable
ww
>>> a=("Check")*3
>>> a
b) Yes, first element in the tuple is deleted
c) Yes, the entire tuple is deleted
d) No, invalid syntax for del method
w.E
a) (‘Check’,’Check’,’Check’)
b) * Operator not valid for tuples
c) (‘CheckCheckCheck’)
Answer: c
Explanation: The command del a deletes the
d) Syntax error
asy entire tuple.
Python code?
>>> a=(1,2,3,4)
ee
5. What will be the output of the following
Answer: b
rin
Explanation: The variable a has tuples
enclosed in a list making it a list of tuples.
>>> del(a[2])
a) Now, a=(1,2,4)
g.n
9. What will be the output of the following
b) Now, a=(1,3,4)
c) Now a=(3,4)
d) Error as tuple is immutable
Python code?
>>> a=(0,1,2,3,4)
>>> b=slice(0,2)
et
>>> a[b]
Answer: d
Explanation: ‘tuple’ object doesn’t support a) Invalid syntax for slicing
item deletion. b) [0,2]
c) (0,1)
6. What will be the output of the following d) (0,2)
Python code?
Answer: c
>>> a=(2,3,4) Explanation: The method illustrated in the
>>> sum(a,3) above piece of code is that of naming of
slices.
a) Too many arguments for sum() method
b) The method sum() doesn’t exist for tuples 10. Is the following Python code valid?
ww
1. Is the following Python code valid?
b) Yes, this is an example of tuple unpacking.
a=(1,2) and b=3
c) No, too many values to unpack
w.E
>>> a,b,c=1,2,3
>>> a,b,c d) Yes, this is an example of tuple unpacking.
a=1 and b=(2,3)
a) Yes, [1,2,3] is printed
b) No, invalid syntax
c) Yes, (1,2,3) is printed asy Answer: c
Explanation: For unpacking to happen, the
d) 1 is printed
En number of values of the right hand side must
be equal to the number of variables on the left
Answer: c
gin
Explanation: A tuple needn’t be enclosed in
hand side.
Python code?
ee
2. What will be the output of the following
Python code?
>>>
>>>
a=(1,2)
b=(3,4) rin
a = ('check',)
n = 2
>>>
>>>
c=a+b
c g.n
for i in range(int(n)):
a = (a,)
print(a)
a) (4,6)
b) (1,2,3,4) et
c) Error as tuples are immutable
a) Error, tuples are immutable d) None
b)
Answer: b
(('check',),) Explanation: In the above piece of code, the
values of the tuples aren’t being changed.
((('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
ww
])
>>>
>>>
obj=a(i=4,j=7)
obj
doesn’t have a sort attribute.
w.E
a) a(i=4, j=7)
b) obj(i=4, j=7)
>>> a=(1,2,3)
>>> b=a.update(4,)
c) (4,7)
d) An exception is thrown
asy 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)
Answer: a
En
Explanation: The above piece of code
c) No because tuples are immutable
d) No because wrong syntax for update()
gin
illustrates the concept of named tuples. method
Answer: c
a) True
b) False ee
7. Tuples can’t be made keys of a dictionary.
Explanation: Tuple doesn’t have any
rin
update() attribute because it is immutable.
Answer: b
Explanation: Tuples can be made keys of a
dictionary because they are hashable.
Python code?
g.n
11. What will be the output of the following
>>> a=2,3,4,5
>>> a=[(2,4),(1,2),(3,9)]
>>> a.sort()
>>> a
et
>>> a a) [(1, 2), (2, 4), (3, 9)]
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
d) Yes, (2,3,4,5) is printed Answer: a
Explanation: A list of tuples is a list itself.
Answer: d Hence items of a list can be sorted.
Explanation: A tuple needn’t be enclosed in
parenthesis. TOPIC 4.3 DICTIONARIES
(OPERATIONS AND METHODS)
ww 1. d = {"john":40, "peter":45}
w.E
b) “john” and “peter”
c) 40 and 45
a) True
b) False
Answer: b asy
d) d = (40:”john”, 45:”peter”) c) Error
d) None
gin
3. What will be the output of the following
Python code snippet?
be used with dictionaries.
1. d = {"john":40, "peter":45}
2. "john" in d
ee 6. What will be the output of the following
Python code snippet?
rin
1. d = {"john":40, "peter":45}
a) True 2. d["john"]
g.n
b) False
c) None
d) Error
a) 40
b) 45
c) “john”
et
d) “peter”
Answer: a
Explanation: In can be used to check if the Answer: a
key is int dictionary. Explanation: Execute in the shell to verify.
4. What will be the output of the following 7. Suppose d = {“john”:40, “peter”:45}, to
Python code snippet? delete the entry for “john” what command do
we use?
1. d1 = {"john":40, "peter":45}
a) d.delete(“john”:40)
2. d2 = {"john":466, "peter":45} b) d.delete(“john”)
c) del d[“john”]
3. d1 == d2 d) del d(“john”:40)
ww
9. What will be the output of the following
Python code snippet?
c) {1,”A”,2”B”}
d) { }
w.E
1. d = {"john":40, "peter":45}
2. print(list(d.keys()))
Answer: c
Explanation: Option c is a set, not a
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
Python code?
a={1:"A",2:"B",3:"C"}
print(a.get(5,4)) a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a) Error, invalid syntax a.update(b)
ww
b) A
c) 5
d) 4
print(a)
w.E
Answer: d
Explanation: The get() method returns the
b) Method update() doesn’t exist for
dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
asy
default value(second parameter) if the key
isn’t present in the dictionary.
d) {4: ‘D’, 5: ‘E’}
Answer: c
En
6. What will be the output of the following Explanation: update() method adds
dictionary b’s key-value pairs to dictionary a.
Python code snippet?
print(a.setdefault(3))
a={1:"A",2:"B",3:"C"}
rin
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for
b=a.copy()
b[2]="D"
print(a) g.n
dictionary
Answer: b
Explanation: setdefault() is similar to get()
dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
et
a) Error, copy() method doesn’t exist for
but will set dict[key]=default if key is not c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
already in the dictionary. d) “None” is printed
7. What will be the output of the following Answer: b
Python code snippet? Explanation: Changes made in the copy of
the dictionary isn’t reflected in the original
a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D") one.
print(a)
10. What will be the output of the following
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’} Python code?
b) None
ww
dictionary keys?
a) More than one key isn’t allowed
b) Keys must be immutable
for i in a:
print(i,end=" ")
w.E
c) Keys must be integers
d) When duplicate keys encountered, the last
assignment wins
a) 1 2 3
b) ‘A’ ‘B’ ‘C’
c) 1 ‘A’ 2 ‘B’ 3 ‘C’
Answer: a
any data type that is immutable.
En
Explanation: Keys of a dictionary may be
Explanation: The variable i iterates over the
keys of the dictionary and hence the keys are
a={1:5,2:3,3:4}
a.pop(3)
print(a)
ee 15. What will be the output of the following
Python code?
rin
>>> a={1:"A",2:"B",3:"C"}
a) {1: 5}
b) {1: 5, 2: 3}
>>> a.items()
ww
a) method del doesn’t exist for the dictionary
b) del deletes the values in the dictionary
c) del deletes the entire dictionary
Python code snippet?
w.E
d) del deletes the keys in the dictionary
Answer: c
a = {}
a[1] = 1
a['1'] = 2
a[1]=a[1]+1
asy
Explanation: del deletes the entire dictionary
and any further attempt to access it will throw
count = 0
for i in a:
count += a[i]
an error.
En
3. If a is a dictionary with some key-value
print(count)
given as an argument
d) Invalid method for dictionary
ee
c) Removes the key-value pair for the key
d) Error, the keys can’t be a mixture of letters
and numbers
rin
Answer: c
Answer: a g.n
Explanation: The above piece of code
basically finds the sum of the values of keys.
Explanation: The method popitem() removes
a random key-value pair.
ww
a) 0
b) None
c) 3
keys (2+4).
w.E
d) An exception is thrown
Answer: a
Python code snippet?
a={}
asy
Explanation: In the second line of code, the
dictionary becomes an empty dictionary.
Thus, length=0.
a['a']=1
a['b']=[2,3,4]
print(a)
En
8. What will be the output of the following
a) Exception is thrown
Python code snippet?
gin b) {‘b’: [2], ‘a’: 1}
c) {‘b’: [2], ‘a’: [3]}
d) {‘b’: [2, 3, 4], ‘a’: 1}
test = {1:'A', 2:'B', 3:'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test))
ee Answer: d
rin
Explanation: Mutable members can be used
as the values of the dictionary but they cannot
a) 0 g.n
be used as the keys of the dictionary.
b) 2
c) Error as the key-value pair of 1:’A’ is
already deleted
d) 1
Python code snippet?
>>>import collections
et
11. What will be the output of the following
>>> a=collections.Counter([1,1,2,3,3,4,4,
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. 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?
Answer: c
a = {}
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
ww
Answer: d
Explanation: The most_common() method
c) Counter({4: 2})
d) Counter({5: 1})
w.E
returns the n number key-value pairs where
the value is the most recurring.
Answer: b
Explanation: a&b returns the pair of keys
and the lowest recurring value.
>>>import collections
En
>>> b=collections.Counter([2,2,3,4,4,4])
class demo(dict):
def __test__(self,key):
>>> b.most_common(1)
a) True
b) False rin
Answer: d
Explanation: The most_common() method
Answer: b
g.n
Explanation: The output of the code is:
returns the n number key-value pairs where
the value is the most recurring.
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?
3. What will be the output of the following
Python code? >>> a={}
>>> a.fromkeys([1,2,3],"check")
a={}
a[2]=1 a) Syntax error
ww
a[1]=[2,3,4]
print(a[1][1])
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}
w.E
a) [2,3,4]
b) 3
c) 2
Answer: b
Explanation: The dictionary takes values of
d) An exception is thrown
Answer: b
asy keys from the list and initializes it to the
default value (value given in the second
En
Explanation: Now, a={1:[2,3,4],2:1} . a[1]
[1] refers to second element having key 1.
parameter). Execute in Python shell to verify.
gin
4. What will be the output of the following
Python code?
Python code?
>>> a={'B':5,'A':9,'C':7}
>>> sorted(a)
ee >>> b={}
>>> all(b)
a) { } rin
a) [‘A’,’B’,’C’]
b) [‘B’,’C’,’A’]
b) False
c) True
d) An exception is thrown
g.n
c) [5,7,9]
d) [9,5,7]
Answer: a
Answer: c et
Explanation: Function all() returns True if all
keys of the dictionary are true or if the
Explanation: Return a new sorted list of keys 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
Python code? true
b) Returns False if dictionary is empty
>>> a={i: i*i for i in range(6)}
>>> a c) Returns True if all keys of the dictionary
are true
a) Dictionary comprehension doesn’t exist d) Method any() doesn’t exist for dictionary
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
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?
ww
c) {‘a’: ‘b’: ‘c’: }
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}
b) 0
c) An exception is thrown
d) ‘ ‘
w.E
Answer: d
Explanation: The above piece of code inverts
the key-value pairs in the dictionary.
Answer: b
Explanation: The statement
asy
10. What will be the output of the following
Python code?
a=collections.defaultdict(int) gives the default
value of 0
(since int data type is given within the
En
>>> a={i: 'A' + str(i) for i in range(5)}
parenthesis) even if the keys don’t exist in the
dictionary.
>>> a
a) An exception is thrown
gin 13. What will be the output of the following
ee
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4:
‘A4’}
c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}
Python code?
>>>
>>>
rin
import collections
a=dict()
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}
Answer: b
>>>
>>> a['A']
g.n
a=collections.defaultdict(str)
ww
in the dictionary.
w.E
Python code?
Answer: b
Explanation: The line of code
a=collections.OrderedDict() generates a
ee Answer: a
rin
Explanation: a is used to indicate that data is
to be appended.
dictionary satisfying the conditions given
within the parenthesis and in an ascending g.n
4. Which of the following statements are
true?
order of the keys.
et
a) When you open a file for reading, if the file
does not exist, an error occurs
b) When you open a file for writing, if the file
does not exist, a new file is created
c) When you open a file for writing, if the file
UNIT V FILES, exists, the existing file is overwritten with the
MODULES, PACKAGES new file
d) All of the mentioned
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)
file as a string from a file object infile, we use b) infile.read()
____________ c) infile.readline()
a) infile.read(2) d) infile.readlines()
b) infile.read()
c) infile.readline() Answer: d
ww
d) infile.readlines() Explanation: Execute in the shell to verify.
1. f = None En Answer: b
2. for i in range (5):
gin Explanation: Every line is stored in a list and
returned.
3.
4.
:
if i > 2:
ee
with open("data.txt", "w") as f
1. Which are the two built-in functions to
rin
read a line of text from standard input, which
by default comes from the keyboard?
5. break
a) Raw_input & Input
b) Input & Scan
c) Scan & Scanner g.n
6. print(f.closed)
a) True
b) False
d) Scanner
Answer: a
et
Explanation: Python provides two built-in
c) None functions to read a line of text from standard
d) Error input, which by default comes from the
keyboard. These functions are:
Answer: a
raw_input and input
Explanation: The WITH statement when
used with open file guarantees that the file 2. What will be the output of the following
object is closed when the with block exits. Python code?
8. To read the next line of the file from a file 1. str = raw_input("Enter your input:
object infile, we use ____________ ");
a) infile.read(2)
b) infile.read() 2. print "Received input is : ", str
ww
Received input is : Python
c) rename
d) mode
w.E
d) None of the mentioned
Answer: a
Answer: c
Explanation: rename is not the attribute of
file rest all are files attributes.
asy
Explanation: The raw_input([prompt])
function reads one line from standard input
and returns it as a string. This would prompt
Attribute Description
En
you to enter any string and it would display
same string on the screen. When I typed
file.closed Returns true if file is c
losed, false otherwise.
“Hello Python!”
gin file.mode Returns access mode with
which file was opened.
Python code?
ee
3. What will be the output of the following
rin
file.softspace Returns false if space ex
plicitly required with print, true otherw
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. d) None of the mentioned
rename(current_file_name, new_file_name)
Answer: c
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
a) remove(file_name)
ww
b) remove(new_file_name,
current_file_name,)
is used as an iterator, typically in a loop, the
next() method is called repeatedly. This
method returns the next input line, or raises
w.E
c) remove(() , file_name))
d) none of the mentioned
StopIteration when EOF is hit.
Output:
Answer: a
Explanation: remove(file_name)
asy Name of the file: foo.txt
En
8. What will be the output of the following
Python code?
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)
ww
file?
a) truncates the file size
7.
8.
break
name = name + c
w.E
b) deletes the content of the file
c) deletes the file size
d) none of the mentioned
9.
10. print 'Your name is:', name
Answer: a
asy
Explanation: The method truncate() truncates a) sanfoundry
En
the file size. Following is the syntax for
truncate() method:
b) sanfoundry, sanfoundry
c) San
fileObject.truncate( [ size ])
gin d) None of the mentioned
Answer: a
Parameters
ee
size — If this optional argument is present,
the file is truncated to (at most) that size.
Explanation: In order to work with standard
rin
I/O streams, we must import the sys module.
The read() method reads one character from
1. Which is/are the basic I/O connections in
file?
a) Standard Input g.n
the standard input. In our example we get a
prompt saying “Enter your name”. We enter
our name and press enter. The enter key
b) Standard Output
c) Standard Errors
d) All of the mentioned
Output: et
generates the new line character: \n.
Answer: d Answer: b
Explanation: None Explanation: We have been working with
Output: simple textual data. What if we are working
Hello with objects rather than simple text? For such
Python situations, we can use the pickle module. This
module serializes Python objects. The Python
objects are converted into byte streams and
written to text files. This process is called
ww
4. Which of the following mode will refer to
binary data?
pickling. The inverse operation, reading from
a file and reconstructing objects is called
w.E
a) r
b) w
c) +
deserializing or unpickling.
Answer:d
asy function?
a) file = open(file_name [, access_mode][,
buffering])
En
Explanation: Mode Meaning is as explained
below:
b) file object = open(file_name [,
access_mode][, buffering])
r Reading
w Writing gin c) file object = open(file_name)
d) none of the mentioned
a Appending
b Binary data
+ Updating.
ee Answer: b
rin
Explanation: Open() function correct syntax
with the parameter details as shown below:
5. What is the pickling?
a) It is used for object serialization [, buffering]) g.n
file object = open(file_name [, access_mode]
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
ww
a) Compilation Error
sizehint — This is the number of bytes to be
read from the file.
T.
b) Runtime Error
w.E
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
asy
Explanation: The method flush() flushes the
internal buffer. Python automatically flushes
SP
b) append, read
c) write, append
d) none of the mentioned
En
the files when closing them. But you may
G
want to flush the data before closing any file. Answer: a
rin
.B
c) fileObject.writelines(sequence) b) Write
d) none of the mentioned c) Append
d) None of the mentioned
g.n
17
Answer: c
Explanation: The method writelines() writes
a sequence of strings to the file. The sequence
Answer: b
et
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
w.E
from file?
a) Readline()
b) Readlines()
Explanation: f.close()to close it and free up
any system resources taken up by the open
file.
c) Readstatement()
d) Readfullline()
asy 9. Is it possible to create a text file in python?
a) Yes
Answer: b
En
Explanation: The readline function reads a
b) No
c) Machine dependent
“r”) gin
single line from the file fh = open(“filename”, d) All of the mentioned
content = fh.readline().
ee
6. Which function is used to write all the
characters?
Answer: a
Explanation: Yes we can create a file in
rin
python. Creation of file is as shown below.
file = open(“newfile.txt”, “w”)
a) write()
b) writecharacters()
c) writeall()
g.n
file.write(“hello world in the new file\n”)
file.write(“and another line\n”)
d) writechar()
Answer: a
file.close().
et
10. Which of the following are the modes of
both writing and reading in binary format in
Explanation: To write a fixed sequence of file?
characters to a file a) wb+
fh = open(“hello.txt”,”w”) b) w
write(“Hello World”). c) wb
d) w+
7. Which function is used to write a list of
string in a file? Answer: a
a) writeline() Explanation: Here is the description below
b) writelines() “w” Opens a file for writing only. Overwrites
c) writestatement() the file if the file exists. If the file does not
d) writefullline() exist, creates a new file for writing.
“wb” Opens a file for writing only in binary
1. Which of the following is not a valid mode 5. How do you close a file object (fp)?
ww
to open a file?
a) ab
a) close(fp)
b) fclose(fp)
w.E
b) rw
c) r+
d) w+
c) fp.close()
d) fp.__close__()
Answer: b
asy
Explanation: Use r+, w+ or a+ to perform
Answer: c
Explanation: close() is a method of the file
object.
file object. En
both read and write operations using a single
6. How do you get the current position within
gin
2. What is the difference between r+ and w+
the file?
a) fp.seek()
modes?
a) no difference
ee
b) in r+ the pointer is initially placed at the
beginning of the file and the pointer is at the
b) fp.tell()
c) fp.loc
d) fp.pos
rin
end for w+
c) in w+ the pointer is initially placed at the
Answer: b
g.n
Explanation: It gives the current position as
an offset from the start of file.
beginning of the file and the pointer is at the
end for r+
d) depends on the operating system et
7. How do you rename a file?
a) fp.name = ‘new_name.txt’
Answer: b b) os.rename(existing_name, new_name)
Explanation: none. c) os.rename(fp, new_name)
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
a) fp.name Explanation: os.rename() is used to rename
b) fp.file(name) files.
c) self.__name__(fp)
8. How do you delete a file?
d) fp.__name__()
a) del(fp)
Answer: a b) fp.delete()
Explanation: name is an attribute of the file c) os.remove(‘file’)
d) os.delete(‘file’)
ww
10. What happens if no arguments are passed
return False
else:
return True
w.E
to the seek function?
a) file position is set to the start of file
b) file position is set to the end of file
c)
d) error
asy
c) file position remains unchanged class foo:
def __init__(self, x):
self.x = x
Answer: d
En
Explanation: seek() takes at least one
def __lt__(self, other):
if self.x < other.x:
gin
return True
argument. else:
return False
1. Which function is called when the
following Python code is executed?
f = foo()
ee d)
class foo:
rin
format(f)
a) format()
self.x = x
g.n
def __init__(self, x):
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) ||
b) |
Answer: b c) //
Explanation: __invert__() overloads ~. d) /
ww
a) __eq__()
b) __equ__()
Explanation: The function __or__()
overloads the bitwise OR operator |.
w.E
c) __isequal__()
d) none of the mentioned 10. Which function overloads the // operator?
a) __div__()
Answer: a
asy
Explanation: The other two do not exist.
b) __ceildiv__()
c) __floordiv__()
d) __truediv__()
a) < En
6. Which operator is overloaded by __lg__()?
Answer: c
b) >
c) != gin Explanation: __floordiv__() is for //.
Answer: d
Explanation: __lg__() is invalid.
ee TOPIC 5.2 EXCEPTION
HANDLING
rin
7. Which function overloads the >> operator?
a) __more__()
except block have? g.n
1. How many except statements can a try-
b) __gt__()
c) __ge__()
d) none of the mentioned
a) zero
b) one
c) more than one
d) more than zero
et
Answer: d Answer: d
Explanation: __rshift__() overloads the >> Explanation: There has to be at least one
operator. except statement.
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
ww
c) no, finally must come before except
d) yes
def foo():
try:
return 1
w.E
Answer: b
Explanation: Refer documentation.
finally:
k = foo()
return 2
asy
4. Is the following Python code valid?
print(k)
a) 1
try:
# Do something
except: En b) 2
c) 3
# Do something
else: gin d) error, there is more than one return
statement in a single try-finally block
# Do something
rin
Explanation: The finally block is executed
even there is a return statement in the try
c) no, else must come before except
d) yes
block.
g.n
8. What will be the output of the following
Answer: d
Explanation: Refer documentation.
def foo():
try:
et
print(1)
multiple exception? finally:
a) yes, like except TypeError, SyntaxError print(2)
[,…] foo()
b) yes, like except [TypeError, SyntaxError]
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'
else:
print("someError has not occurre a) Assertion Error
d") b) 10 8
except "someError":
print ("someError has occurred") c) No output
d) 108
ww
a) someError has occurred
b) someError has not occurred
c) invalid code
Answer: c
Explanation: The code shown above results
w.E
d) none of the mentioned
Answer: c
in an error if and only if x<y. However, in the
above case, since x>y, there is no error. Since
there is no print statement, hence there is no
asy
Explanation: A new exception class must
inherit from a BaseException. There is no
output.
a) we get a True
b) we get a False gin
10. What happens when ‘1’ == 1 is executed?
#generator
def f(x):
c) an TypeError occurs
d) a ValueError occurs
Answer: b
ee yield x+1
g=f(8)
print(next(g))
a) 8 rin
Explanation: It simply evaluates to False and
does not raise any exception.
b) 9
c) 7 g.n
1. The following Python code will result in an
error if the input value is entered as -5.
d) Error
Answer: b
et
Explanation: The code shown above returns
assert False, 'Spanish' the value of the expression x+1, since we
have used to keyword yield. The value of x is
a) True 8. Hence the output of the code is 9.
b) False
4. What will be the output of the following
Answer: a Python code?
Explanation: The code shown above results
in an assertion error. The output of the code def f(x):
is: yield x+1
Traceback (most recent call last): print("test")
yield x+2
File “<pyshell#0>”, line 1, in <module> g=f(9)
assert False, ‘Spanish’
ww
to yield 9, and there is no next(g), the
iteration stops. Hence there is no output.
a) No output
b) after f?
c) error
w.E
5. What will be the output of the following
Python code?
d) after f
Answer: c
def f(x):
yield x+1 asy Explanation: This code shown above will
result in an error simply because ‘f’ is not
print("test")
yield x+2
g=f(10) En defined. ‘try’ and ‘finally’ are keywords used
in exception handling.
print(next(g))
print(next(g)) gin 7. What will be the output of the following
Python code?
a) No output
b) ee def f(x):
for i in range(5):
yield i rin
11
test
g=f(8)
print(list(g))
g.n
12
c)
a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
et
d) [0, 1, 2, 3, 4, 5, 6, 7]
11
Answer: a
test
Explanation: The output of the code shown
above is a list containing whole numbers in
d) 11
the range (5). Hence the output of this code
Answer: b is: [0, 1, 2, 3, 4].
Explanation: The code shown above results
8. The error displayed in the following
in the output:
Python code is?
11
test import itertools
12 l1=(1, 2, 3)
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
Answer: b c) Input output error
Explanation: The error raised in the code d) Name error
shown above is that: ‘tuple’ object is not
iterator. Had we given l2 as argument to next, Answer: a
the error would have been: ‘list’ object is not Explanation: In the code shown above, if the
ww
iterator.
w.E
handling keyword in Python?
a) try
b) except
The user is then prompted to reenter the file
name. Error is not thrown.
Answer: c
En
Explanation: The keywords ‘try’, ‘except’
lst = [1, 2, 3]
lst[3]
gin
and ‘finally’ are exception handling keywords
in python whereas the word ‘accept’ is not a
a) NameError
b) ValueError
keyword at all.
ee
10. What will be the output of the following
Python code?
c) IndexError
d) TypeError
Answer: c rin
g = (i for i in range(5)) g.n
Explanation: The snippet of code shown
above throws an index error. This is because
type(g)
a) class <’loop’>
b) class <‘iteration’>
et
the index of the list given in the code, that is,
3 is out of range. The maximum index of this
list is 2.
c) class <’range’> 3. What will be the output of the following
d) class <’generator’> Python code?
Answer: d t[5]
Explanation: Another way of creating a
generator is to use parenthesis. Hence the a) IndexError
output of the code shown above is: b) NameError
class<’generator’>. c) TypeError
d) ValeError
1. What happens if the file is not found in the
following Python code? Answer: b
Explanation: The expression shown above
results in a name error. This is because the ctorial you want to find"))
name ‘t’ is not defined. print(math.factorial(num))
ww
Answer: d
Explanation: The line of code shown above
will result in a type error. This is because the
is because we have not imported the math
module. Hence the name ‘math’ is undefined.
w.E
operand ‘+’ is not supported when we
combine the data types ‘int’ and ‘str’. Sine
this is exactly what we have done in the code
7. What will be the output of the following
Python code?
asy
shown above, a type error is thrown. def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
Python code?
En
5. What will be the output of the following print(m)
getMonth(6)
int('65.43')
gin a) ValueError
b) Invalid
a) ImportError
b) ValueError
c) TypeError
d) NameError
ee c) 6
rin
d) ValueError(“Invalid”)
Answer: b
Answer: c
g.n
Explanation: In the code shown above, since
the value passed as an argument to the
Explanation: The snippet of code shown
above results in a value error. This is because
there is an invalid literal for int() with base
10: ’65.43’.
et
function is between 1 and 12 (both included),
hence the output is the value itself, that is 6. If
the value had been above 12 and less than 1, a
ValueError would have been thrown.
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?
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")
ww
Python codes? ValueError are standard exceptions in Python
whereas Assignment error is not a standard
w.E
Print(“Good Morning”)
print(“Good night)
a) Syntax, Syntax
exception in Python.
rin
13. An exception is ____________
syntax error is thrown.
Answer: a
et
Explanation: An exception is an object that
c) When there is a deviation from the rules of is raised by a function signaling that an
a programming language, a semantic error is unexpected situation has occurred, that the
thrown function itself cannot handle.
d) If any exception is thrown in try block, else
block is executed 14. _______________________ exceptions
are raised as a result of an error in opening a
Answer: a particular file.
Explanation: When any exception is thrown a) ValueError
in try block, except block is executed. If b) TypeError
exception in not thrown in try block, else c) ImportError
block is executed. When there is a deviation d) IOError
from the rules of a programming language, a
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
b) else b) Docstring
c) finally c) Interface
d) assert d) Modularity
Answer: c Answer: a
ww
Explanation: The statements in the finally
block will always be executed, whether an
Explanation: Program code making use of a
given module is called the client of the
w.E
exception is thrown or not. This clause is
used to close the resources used in a code.
module. There may be multiple clients for a
module.
En
1. Which of these definitions correctly
a) Interface
b) Modularity
describes a module?
gin
a) Denoted by triple quotes for providing the
c) Client
d) Docstring
rin
Explanation: Docstring used for providing
the specifications of program elements.
c) Defines the specification of how it is to be
used g.n
5. Which of the following is true about top-
down design process?
d) Any program that reuses code
Answer: b
Explanation: The term “module” refers to the
et
a) The details of a program design are
addressed before the overall design
b) Only the details of the program are
implementation of specific functionality to be addressed
incorporated into a program. c) The overall design of the program is
addressed before the details
2. Which of the following is not an advantage d) Only the design of the program is
of using modules? addressed
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks Answer: c
c) Provides a means of reducing the size of Explanation: Top-down design is an
the program approach for deriving a modular design in
d) Provides a means of testing individual which the overall design.
parts of the program
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
modules
7. All modular designs are because of a top- c) Special name given to main modules is:
down design process. __main__
a) True d) Other main modules can import main
b) False modules
ww
Answer: b Answer: d
w.E
Explanation: The details of the program can
be addressed before the overall design too.
Hence, all modular designs are not because of
Explanation: Main modules are not meant to
be imported into other modules.
print(b)
#mod2
def change(a):
b=[x*x for x in a]
ee Answer: b
Explanation: During a Python program
rin
execution, there are as many as three
namespaces – built-in namespace, global
print(b)
from mod1 import
from mod2 import
change
change g.n
namespace and local namespace.
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
a) 120
identifier
b) Nothing is printed
b) This form of import prevents name clash
c) Error, method factorial doesn’t exist in
c) The namespace of imported module
math module
becomes part of importing module
d) Error, the statement should be:
d) The identifiers in module are accessed
print(factorial(5))
directly as: identifier
Answer: d
Answer: b
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
factorial()) aren’t specified along with the
names of the imported identifiers aren’t
ww
specified along with the module name. module name.
w.E
13. Which of the statements about modules is
false?
a) In the “from-import” form of import,
Python looks for an identifier?
a) Python first searches the global namespace,
then the local namespace and finally the built-
asy
identifiers beginning with two underscores
are private and aren’t imported
b) dir() built-in function monitors the items in
in namespace
b) Python first searches the local namespace,
the namespace of the main module
En
c) In the “from-import” form of import, all
then the global namespace and finally the
built-in namespace
is automatically produced
ee
version of the module with file extension .pyc d) Python first searches the built-in
rin
namespace, then the local namespace and
finally the global namespace
Answer: c
Explanation: In the “from-import” form of Answer: b
g.n
Explanation: Python first searches for the
import, identifiers beginning with two
underscores are private and aren’t imported.
Python code?
ww
w.E
a syE
ngi
nee
rin
g.n
et