Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

GE8151 Problem Solving and Python Programming MCQ

This document discusses algorithms and flowcharts. It contains the following key points: 1. An algorithm refers to a special method usable by a computer for solving problems. Algorithms can be represented as programs, flowcharts, or pseudo code. 2. A flowchart uses graphical symbols like boxes, circles, and arrows to visually represent the steps of an algorithm. Actual instructions are represented with boxes, while process flow is shown with arrows. 3. There are no set standards for the level of detail in a flowchart. A detailed flowchart is called a structure chart.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

GE8151 Problem Solving and Python Programming MCQ

This document discusses algorithms and flowcharts. It contains the following key points: 1. An algorithm refers to a special method usable by a computer for solving problems. Algorithms can be represented as programs, flowcharts, or pseudo code. 2. A flowchart uses graphical symbols like boxes, circles, and arrows to visually represent the steps of an algorithm. Actual instructions are represented with boxes, while process flow is shown with arrows. 3. There are no set standards for the level of detail in a flowchart. A detailed flowchart is called a structure chart.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

Downloaded From: www.EasyEngineering.

net

ww
w.E
a syE
ngi
nee
rin
g.n
et

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials, Students & Graduates if You Find the Same Materials with
EasyEngineering.net Watermarks or Logo, Kindly report us to
easyengineeringnet@gmail.com
Downloaded From: www.EasyEngineering.net
Downloaded From: www.EasyEngineering.net

2. In computer science, algorithm refers to a


special method usable by a computer for the
GE8151 PROBLEM solution to a problem.
a) True
SOLVING AND b) False

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

Downloaded From: www.EasyEngineering.net 1


Downloaded From: www.EasyEngineering.net

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.

7. Any algorithm is a program. En TOPIC 1.2 FLOW CHARTS

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

Downloaded From: www.EasyEngineering.net 2


Downloaded From: www.EasyEngineering.net

3. The process of drawing a flowchart for an Answer: b


algorithm is called __________ Explanation: A diamond shape box denotes
a) Performance either a truth value or a false value. It jumps
b) Evaluation onto two different statements following it via
c) Algorithmic Representation flow lines.
d) Flowcharting
7. There should be certain set standards on
Answer: d the amount of details that should be provided
Explanation: It is called as flowcharting. A in a flowchart.
flowchart is nothing but a pictorial a) True
representation of an algorithm. b) False

4. Actual instructions in flowcharting are Answer: b


represented in __________ Explanation: The statement is false. There

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

Downloaded From: www.EasyEngineering.net 3


Downloaded From: www.EasyEngineering.net

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.

4. Which of the following is not a flowchart


structure?

Downloaded From: https://cse-r17.blogspot.com Downloaded From: www.EasyEngineering.net 4


Downloaded From: www.EasyEngineering.net

7. What type of structure is this? shapes. They also show the flow of the
program.

10. The following box denotes?

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.

8. What type of a structure is this?


result is checked accordingly if the condition
is true or false.

asy TOPIC 1.4 PSEUDO CODE

En 1. Keep the statement language


______________ while writing a pseudo

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.

2. Capitalize initial keyword – This is a rule


9. A _______ is a connector showing the while writing a pseudo code.
relationship between the representative a) True
shapes. b) False
a) line
b) arrow Answer: a
c) Process Explanation: The statement is true. It is an
d) box important rule to capitalize the initial
keyword while writing a pseudo code.
Answer: b
Explanation: Arrows are the connectors that 3. Which of the following is not a keyword?
show the relationship between different a) Read

Downloaded From: www.EasyEngineering.net 5


Downloaded From: www.EasyEngineering.net

b) Write identified by their addresses, we give them


c) start names (field names/variable names) using
d) endif words descriptive to us such as ctr as opposed
to a location addresses such as 19087.
Answer: c
Explanation: Start is not a Keyword. Other 7. ____________ begins with lower case
words like read, write, if, else, etc are letters.
keywords and convey a special meaning. a) Keywords
b) Variables
4. ______________ is used to show hierarchy c) Tokens
in a pseudo code. d) Functions
a) Indentation
b) Curly Braces Answer: b
c) Round Brackets Explanation: Variables begin with a

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

Downloaded From: www.EasyEngineering.net 6


Downloaded From: www.EasyEngineering.net

to close the IF block. ENDIF statement b) 1st_string


should be in line with the IF statement. c) foo
d) _

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.

3. Which of the following is invalid?


a) _a = 1
b) UPPER CASE
c) Capitalized
d) None of the mentioned
et
b) __a = 1
c) __str__ = 1 Answer: d
d) none of the mentioned Explanation: True, False and None are
capitalized while the others are in lower case.
Answer: d
Explanation: All the statements will execute 8. Which of the following is true for variable
successfully but at the cost of reduced names in Python?
readability. a) unlimited length
b) all private members must have leading and
4. Which of the following is an invalid trailing underscores
variable? c) underscore and ampersand are the only two
a) my_string_1

Downloaded From: www.EasyEngineering.net 7


Downloaded From: www.EasyEngineering.net

special characters allowed Answer: b


d) none of the mentioned Explanation: When both of the operands are
integer then python chops out the fraction
Answer: a part and gives you the round off value, to get
Explanation: Variable names can be of any the accurate answer use floor division. This is
length. floor division. For ex, 5/2 = 2.5 but both of
the operands are integer so answer of this
9. Which of the following is an invalid expression in python is 2. To get the 2.5
statement? answer, use floor division.
a) abc = 1,000,000
b) a b c = 1000 2000 3000 3. What is the order of precedence in python?
c) a,b,c = 1000, 2000, 3000 i) Parentheses
d) a_b_c = 1,000,000 ii) Exponential
iii) Multiplication
ww
Answer: b
Explanation: Spaces are not allowed in
iv) Division
v) Addition

w.E
variable names.

10. Which of the following cannot be a


vi) Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
variable?
a) __init__
b) in asy c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
c) it
d) on En Answer: a
Explanation: For order of precedence, just
Answer: b gin remember this PEMDAS (similar to
BODMAS).
Explanation: in is a keyword.

TOPIC 2.2 OPERATORS


ee 4. What is the answer to this expression, 22 %
3 is?
a) 7 rin
1. Which is the correct operator for
power(xy)?
b) 1
c) 0 g.n
a) X^y
b) X**y
c) X^^y
d) 5

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…’.

Downloaded From: www.EasyEngineering.net 8


Downloaded From: www.EasyEngineering.net

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

a) Addition and Subtraction Answer: d

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

Answer: a executed in shell.


Explanation: “Addition and Subtraction” are
at the same precedence level. Similarly,
“Multiplication and Division” are at the same
a) int
b) bool
et
-R

c) void
precedence level. However, Multiplication d) None
and Division operators are at a higher
SE

precedence level than Addition and Answer: d


Subtraction operators. Explanation: Python shell throws a
NoneType object back.
9. The expression Int(x) implies that the
C

variable x is converted to integer. 3. What will be the output of the following


a) True Python code?
b) False
1. >>>str="hello"
Answer: a
Explanation: None. 2. >>>str[:2]
3. >>>

Downloaded From: www.EasyEngineering.net 9


Downloaded From: www.EasyEngineering.net

a) he 3.0 and int(..) is a type cast operator.


b) lo
c) olleh 7. What error occurs when you execute the
d) hello following Python code snippet?

Answer: a apple = mango


Explanation: We are printing only the 1st
two bytes of string and hence the answer is a) SyntaxError
“he”. b) NameError
c) ValueError
4. Which of the following will run without d) TypeError
errors?
a) round(45.8) Answer: b
b) round(6352.898,2,5) Explanation: Mango is not defined hence

ww
c) round()
d) round(7463.123,2,1)
name error.

8. What will be the output of the following

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

Downloaded From: www.EasyEngineering.net 10


Downloaded From: www.EasyEngineering.net

values within it. Answer: c


Explanation: The \n adds a new line.
10. In order to store values in terms of key
and value we use what core data type.
a) list
b) tuple 13. What is the average value of the
c) class following Python code snippet?
d) dictionary
1. >>>grade1 = 80
Answer: d
Explanation: Dictionary stores values in 2. >>>grade2 = 90
terms of keys and values. 3. >>>average = (grade1 + grade2) / 2
11. Which of the following results in a

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.

that result in this output. gin


function call. Select all of the function calls hello-how-are-you

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.

15. What is the return value of trunc()?


\ndick a) int
b) bool
\nharry''')
c) float
b) print(”’tomdickharry”’) d) None
c) print(‘tom\ndick\nharry’)
Answer: a
d)
Explanation: Execute help(math.trunc) to get
print('tom details.

dick
TOPIC 2.4 NUMERIC TYPES
harry') (INT, FLOAT)

Downloaded From: www.EasyEngineering.net 11


Downloaded From: www.EasyEngineering.net

1. What is the output of print 0.1 + 0.2 == c) +11


0.3? d) -5
a) True
b) False Answer: a
c) Machine dependent Explanation: ~x is equivalent to -(x+1).
d) Error
6. Which of the following is incorrect?
Answer: b a) x = 0b101
Explanation: Neither of 0.1, 0.2 and 0.3 can b) x = 0x4f5
be represented accurately in binary. The c) x = 19023
round off errors from 0.1 and 0.2 accumulate d) x = 03964
and hence there is a difference of 5.5511e-17
between (0.1 + 0.2) and 0.3. Answer: d
Explanation: Numbers starting with a 0 are

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

4. What does ~4 evaluate to?


Answer: d
et
Explanation: ‘+’ cannot be converted to a
float.
a) -5
b) -4 9. What is the result of round(0.5) –
c) -3 round(-0.5)?
d) +3 a) 1.0
b) 2.0
Answer: a c) 0.0
Explanation: ~x is equivalent to -(x+1). d) Value depends on Python version

5. What does ~~~~~~5 evaluate to? Answer: d


a) +5 Explanation: The behavior of the round()
b) -11 function is different in Python 2 and Python
3. In Python 2, it rounds off numbers away
from 0 when the number to be rounded off is

Downloaded From: www.EasyEngineering.net 12


Downloaded From: www.EasyEngineering.net

exactly halfway through. round(0.5) is 1 and towards 0 and hence “round(0.5) –


round(-0.5) is -1 whereas in Python 3, it (round(-0.5)) = 0 – 0 = 0“. Also note that the
rounds off numbers towards nearest even round(2.5) is 2 (which is an even number)
number when the number to be rounded off is whereas round(3.5) is 4 (which is an even
exactly halfway through. See the below number).
output.
10. What does 3 ^ 4 evaluate to?
$ python a) 81
Python 2.7.17 (default, Nov 7 2019, 10:0
b) 12
7:09) c) 0.75
d) 7
>>> round(0.5)
Answer: d
1.0 Explanation: ^ is the Binary XOR operator.

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”

$ python3 gin Answer: a


Explanation: Although the presence of

Python 3.6.8 (default, Oct


9:55) ee
7 2019, 12:5
parenthesis does affect the order of
precedence, in the case shown above, it is not

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

Downloaded From: www.EasyEngineering.net 13


Downloaded From: www.EasyEngineering.net

3. Evaluate the expression given below if A = a) (6.0, 16.0)


16 and B = 15. b) (6.00, 16.00)
c) (6, 16)
A % B // A d) (6.00, 16.0)
a) 0.0 Answer: a
b) 0 Explanation: The result of the expression
c) 1.0 shown above is (6.0, 16.0). This is because
d) 1 the result is automatically rounded off to one
decimal place.
Answer: b
Explanation: The above expression is 7. Which of the following is the truncation
evaluated as: 16%15//16, which is equal to division operator?
1//16, which results in 0. a) /

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?

5. What will be the value of x in the


following Python expression?
ee 2**(3**2)
(2**3)**2
2**3**2
rin
x = int(43.55+2/2) a) 64, 512, 64
b) 64, 64, 64 g.n
a) 43
b) 44
c) 22
d) 23
c) 512, 512, 512
d) 512, 64, 512

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)

Downloaded From: www.EasyEngineering.net 14


Downloaded From: www.EasyEngineering.net

a) (1.0, 4.0) Answer: d


b) (1.0, 1.0) Explanation: The expression shown above is
c) (4.0. 1.0) evaluated as: 2+9*(36-8)/10, which simplifies
d) (4.0, 4.0) to give 2+9*(2.8), which is equal to 2+25.2 =
27.2. Hence the result of this expression is
Answer: a 27.2.
Explanation: The above expressions are
evaluated as: 2/2, 8/2, which is equal to (1.0, 3. Which of the following expressions
4.0). involves coercion when evaluated in Python?
a) 4.7 – 1.5
10. What is the value of the following b) 7.9 * 6.3
expression? c) 1.7 % 2
d) 3.4 + 4.6
float(22//3+3/3)

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?

Python expression? gin


1. What will be the output of the following 24//6%3, 24//4//2

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

Downloaded From: www.EasyEngineering.net 15


Downloaded From: www.EasyEngineering.net

Answer: b 9. What will be the value of the following


Explanation: The highest precedence is that Python expression?
of the exponentiation operator, that is of **.
4+2**5//10
6. What will be the value of the following
Python expression? a) 3
b) 7
float(4+int(2.39)%2) c) 77
d) 0
a) 5.0
b) 5 Answer: b
c) 4.0 Explanation: The order of precedence is: **,
d) 4 //, +. The expression 4+2**5//10 is evaluated
as 4+32//10, which is equal to 4+3 = 7. Hence

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.

10. The expression 2**2**3 is evaluates as:

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.

explicit conversion of operands to a specific


type. Options 5.3 + 6.3 and 5.0 + 3 are
examples of implicit conversion whereas g.n
TOPIC 2.6 BITWISE OPERATOR

option 4.0 + float(3) is an example of explicit


conversion or type conversion.

8. Which of the following expressions results


Python code snippet if x=1?

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.

Downloaded From: www.EasyEngineering.net 16


Downloaded From: www.EasyEngineering.net

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.

4. What will be the output of the following


in an error?
a) int(1011) g.n
7. Which of the following expressions results

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

Downloaded From: www.EasyEngineering.net 17


Downloaded From: www.EasyEngineering.net

Answer: b original value. For example, the two’s


Explanation: The ^ operator represent complement of 10000000 is also equal to
bitwise XOR operation. &: bitwise AND, | : 10000000. Hence the statement is false.
bitwise OR and ! represents bitwise NOT.
2. The one’s complement of 110010101 is:
9. What is the value of the following Python a) 001101010
expression? b) 110010101
c) 001101011
bin(0x8) d) 110010100
a) ‘0bx1000’ Answer: a
b) 8 Explanation: The one’s complement of a
c) 1000 value is obtained by simply changing all the
d) ‘0b1000’ 1’s to 0’s and all the 0’s to 1’s. Hence the

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

a) 115 gin Answer: c


Explanation: Bitwise XOR gives 1 if either
b) 116
c) 117
d) 118
ee of the bits is 1 and 0 when both of the bits are
1.

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.

Downloaded From: www.EasyEngineering.net 18


Downloaded From: www.EasyEngineering.net

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

Answer: d asy Answer: b


Explanation: The binary form of -44 is

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

10. What will be the output of the following

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?

a=10 TOPIC 2.7 BOOLEAN


b=20
a=a^b
b=a^b

Downloaded From: www.EasyEngineering.net 19


Downloaded From: www.EasyEngineering.net

1. What will be the output of the following Answer: c


Python code snippet? Explanation: The line of code shown above
can be simplified to state that ‘hello’ should
bool(‘False’) be printed if the argument passed to the
bool()
Boolean function amounts to zero, else
‘morning’ will be printed.
a)

True 3. What will be the output of the following


Python code snippet?
True
not(3>4)
b) not(1&1)

False a)

ww True True

c)
w.EFalse b)
True

False
asy True

d)
En c)
False

True

False gin False

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

Downloaded From: www.EasyEngineering.net 20


Downloaded From: www.EasyEngineering.net

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

a new list containing only those elements of


the list l which do not amount to zero. Hence
the output is: [1, 2, ‘hello’].
ee a) pass
b) true
c) false rin
6. What will be the output of the following
Python code if the system date is 21st June,
d) error

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) 8. What will be the output of the following


Python code?
[]
if (9 < 0) and (0 < -9):
{} print("hello")
elif (9 > 0) or False:
b) print("good")
else:
[] print("bad")

[] a) error
b) hello
c)

Downloaded From: www.EasyEngineering.net 21


Downloaded From: www.EasyEngineering.net

c) good
d) bad

Answer: c UNIT III CONTROL


Explanation: The code shown above prints FLOW, FUNCTIONS
the appropriate option depending on the
conditions given. The condition which
matches is (9>0), and hence the output is: TOPIC 3.1 FOR AND WHILE
good. LOOPS
9. Which of the following Boolean
1. What will be the output of the following
expressions is not logically equivalent to the
Python code?
other three?
a) not(-6<0 or-6>10)

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?

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


x = ['ab', 'cd']
for i in x: g.n
a) True
b) False
c) Error
x.append(i.upper())
print(x)

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?

Downloaded From: www.EasyEngineering.net 22


Downloaded From: www.EasyEngineering.net

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 +=.

4. What will be the output of the following


c) 5 6 7 8 9 10 11 12 13 14 15 ….
d) error

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.

7. What will be the output of the following


print(i)
i += 1 En Python code?

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

Downloaded From: www.EasyEngineering.net 23


Downloaded From: www.EasyEngineering.net

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:

Answer: d gin print(0)

a) 0 1 2 3 0
because of False.
ee
Explanation: Control does not enter the loop

10. What will be the output of the following


b) 0 1 2 0
c) 0 1 2
d) error
rin
Python code?

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.

3. What will be the output of the following


Python code?
a) True
b) False x = "abcdef"
c) None while i in x:
d) none of the mentioned print(i, end=" ")

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.

Downloaded From: www.EasyEngineering.net 24


Downloaded From: www.EasyEngineering.net

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

5. What will be the output of the following


c) a a a a a
d) none of the mentioned

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.

8. What will be the output of the following


a) no output
b) i i i i i i … En Python code?

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

Downloaded From: www.EasyEngineering.net 25


Downloaded From: www.EasyEngineering.net

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.

4. What will be the output of the following

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.

5. What will be the output of the following


place, rather a new instance of the string is Python code?
returned.
x = 'abcd'
2. What will be the output of the following for i in range(len(x)):
Python code? print(i.upper())

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

Downloaded From: www.EasyEngineering.net 26


Downloaded From: www.EasyEngineering.net

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.

10. What will be the output of the following

x = 'abcd' En Python code snippet?


for i in range(len(x)):
x[i].upper()
print (x) gin x = 'abcd'
for i in range(len(x)):
print(x)

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

Downloaded From: www.EasyEngineering.net 27


Downloaded From: www.EasyEngineering.net

Answer: c 5. What will be the output of the following


Explanation: Objects of type int are not Python code?
iterable.
d = {0: 'a', 1: 'b', 2: 'c'}
2. What will be the output of the following for x in d.keys():
print(d[x])
Python code?

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


a) 0 1 2
for i in d: b) a b c
print(i) c) 0 a 1 b 2 c
d) none of the mentioned
a) 0 1 2
b) a b c Answer: b
c) 0 a 1 b 2 c Explanation: Loops over the keys and prints

ww
d) none of the mentioned

Answer: a
the values.

6. What will be the output of the following

w.E
Explanation: Loops over the keys of the
dictionary.
Python code?

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

asy
3. What will be the output of the following
Python code?
for x in d.values():
print(x)

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


for x, y in d: En a) 0 1 2
b) a b c
print(x, y)

a) 0 1 2 gin c) 0 a 1 b 2 c


d) none of the mentioned

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.

7. What will be the output of the following


Answer: d
Explanation: Error, objects of type int aren’t
Python code?
g.n
iterable.

4. What will be the output of the following


Python code?
for x in d.values():
print(d[x]) et
d = {0: 'a', 1: 'b', 2: 'c'}

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():

Downloaded From: www.EasyEngineering.net 28


Downloaded From: www.EasyEngineering.net

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

3. What will be the output of the following


Answer: c
Python code?
Explanation: Variable x takes the values 0, 1
and 2. set.add() returns None which is for i in range(float('inf')):
printed. print (i)

11. What will be the output of the following a) 0.0 0.1 0.2 0.3 …
Python code? b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
for i in range(0): d) none of the mentioned
print(i)

Downloaded From: www.EasyEngineering.net 29


Downloaded From: www.EasyEngineering.net

Answer: d for i in 'abcd'[::-1]:


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

ww
Answer: d
Explanation: OverflowError, cannot convert
for i in '':
print (i)

w.E
float infinity to integer.

5. What will be the output of the following


a) None
b) (nothing is printed)
c) error
Python code snippet?
asy d) none of the mentioned

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.

6. What will be the output of the following


print (x)
g.n
Python code snippet?

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?

Downloaded From: www.EasyEngineering.net 30


Downloaded From: www.EasyEngineering.net

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?

Downloaded From: www.EasyEngineering.net 31


Downloaded From: www.EasyEngineering.net

string = "my name is x" a = [0, 1, 2, 3]


for i in string.split(): i = -2
print (i, end=", ") for i not in a:
print(i)
a) m, y, , n, a, m, e, , i, s, , x, i += 1
b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x, a) -2 -1
d) error b) 0
c) error
Answer: c d) none of the mentioned
Explanation: Variable i takes the value of
one word at a time. Answer: c
Explanation: SyntaxError, not in isn’t
7. What will be the output of the following allowed in for loops.

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

8. What will be the output of the following


Python code snippet?
ee Explanation: Variable i takes the value of
one character at a time.

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?

Downloaded From: www.EasyEngineering.net 32


Downloaded From: www.EasyEngineering.net

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?

Answer: c 1. >>>print (r"\nhello")


Explanation: Slice operation is performed on
string. a) a new line and hello
b) \nhello
3. The output of executing string.ascii_letters c) the letter r and then hello
can also be achieved by: d) error
a) string.ascii_lowercase_string.digits

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

1. >>> str1 = 'hello'


gin a) Error
b) Output equivalent to print ‘new\nline’
2. >>> str2 = ','
3. >>> str3 = 'world'
ee c) newline
d) new line
rin
Answer: c
4. >>> str1[-1:]

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

5. What arithmetic operators cannot be used a) Error


with strings? b)
a) + 97
b) *
c) – 98
d) All of the mentioned
c) x\97
d) \x97\x98

Downloaded From: www.EasyEngineering.net 33


Downloaded From: www.EasyEngineering.net

Answer: c 7. self.o2 = param


Explanation: \x is an escape sequence that
means the following 2 digits are a 8.
hexadecimal number encoding a character. 9. >>>obj = child(22)
9. What will be the output of the following 10. >>>print "%d %d" % (obj.o1, obj.o2)
Python code?
a) None None
1. >>>str1="helloworld" b) None 22
c) 22 None
2. >>>str1[::-1]
d) Error is generated
a) dlrowolleh
Answer: d
b) hello

ww
c) world
d) helloworld
Explanation: self.o1 was never created.

2. What will be the output of the following

w.E
Answer: a
Explanation: Execute in shell to verify.
Python code?

1. class tester:

Python code? asy


10. What will be the output of the following 2. def __init__(self, id):

print(0xA + 0xB + 0xC)


En 3.
4.
self.id = str(id)

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.

1. What will be the output of the following


c) 12
d) None

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

Downloaded From: www.EasyEngineering.net 34


Downloaded From: www.EasyEngineering.net

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

1. >>>example = "snow world" Answer: c


Explanation: Returns lowest index.
2. >>>example[3] = 's'
8. What will be the output of the following
3. >>>print example Python code?

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

1. >>>max("what are you") gin Explanation: Returns highest index.

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

Explanation: Max returns the character with


the highest ascii value.
a) dlrowolleh
b) True
c) -1
et
6. Given a string example=”hello” what is the d) None
output of example.count(‘l’)?
a) 2 Answer: b
b) 1 Explanation: Starts with checks if the given
c) None string starts with the parameter that is passed.
d) 0
10. To concatenate two strings to a third what
Answer: a statements are applicable?
Explanation: l occurs twice in hello. a) s3 = s1 . s2
b) s3 = s1.add(s2)
7. What will be the output of the following c) s3 = s1.__add__(s2)
Python code? d) s3 = s1 * s2

Downloaded From: www.EasyEngineering.net 35


Downloaded From: www.EasyEngineering.net

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.

3. Which of the following statement prints


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

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 = '#')

Downloaded From: www.EasyEngineering.net 36


Downloaded From: www.EasyEngineering.net

2. >>>print(format(111, "4d"), end = b) s.getitem(3)


'#') c) s.__getitem__(3)
d) s.getItem(3)
3. >>>print(format(924.656, "3.2f"))
Answer: c
a) Welcome# 111#924.66 Explanation: __getitem(..) can be used to get
b) Welcome#111#924.66 character at index specified as parameter.
c) Welcome#111#.66
d) Welcome # 111#924.66 3. To return the length of string s what
command do we execute?
Answer: d a) s.__len__()
Explanation: Execute in the shell to verify. b) len(s)
c) size(s)
9. What will be displayed by print(ord(‘b’) –
d) s.size()

ww
ord(‘a’))?
a) 0
b) 1
Answer: a

w.E
c) -1
d) 2
Explanation: Execute in shell to verify.

4. If a class defines the __str__(self) method,


Answer: b
asy
Explanation: ASCII value of b is one more
for an object obj for the class, you can use
which command to invoke the __str__
method.
which is equal to 1.
En
than a. Hence the output of this code is 98-97, a) obj.__str__()
b) str(obj)

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.

1. What is “Hello”.replace(“l”, “e”)?


b) s2 in s1
c) s1.contains(s2)
d) si.in(s2)
et
a) Heeeo Answer: a
b) Heelo Explanation: s2 in s1 works in the same way
c) Heleo as calling the special function __contains__ .
d) None
6. Suppose i is 5 and j is 4, i + j is same as
Answer: a ________
Explanation: Execute in shell to verify. a) i.__add(j)
b) i.__add__(j)
2. To retrieve the character at index 3 from
c) i.__Add(j)
string s=”Hello” what command do we
d) i.__ADD(j)
execute (multiple answers allowed)?
a) s[]

Downloaded From: www.EasyEngineering.net 37


Downloaded From: www.EasyEngineering.net

Answer: b 7. firstName = "John"


Explanation: Execute in shell to verify.
8. name = Name(firstName, 'F', "Smith"
7. What will be the output of the following )
Python code? 9. firstName = "Peter"
1. class Count: 10. name.lastName = "Pan"
2. def __init__(self, count = 0): 11. print(name.firstName, name.lastName
)
3. self.__count = count
a) Peter Pan
4.
b) John Pan
5. c1 = Count(2) c) Peter Smith

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.

9. What function do you use to read a string?


9. s1 = "Good"
asy a) input(“Enter a string”)
b) eval(input(“Enter a string”))
10. s2 = "Good"
11. print(id(s1) == id(s2)) En c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))

a) True False gin Answer: a


Explanation: Execute in shell to verify.
b) True True
c) False True
d) False False
ee 10. Suppose x is 345.3546, what is format(x,

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.

8. What will be the output of the following


d) _____345.354

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.

Downloaded From: www.EasyEngineering.net 38


Downloaded From: www.EasyEngineering.net

Answer: c 5. What will be the output of the following


Explanation: The first letter of the string is Python code?
converted to uppercase and the others are
converted to lowercase. print('*', "abcdef".center(7), '*')

2. What will be the output of the following a) * abcdef *


Python code? b) * abcdef *
c) *abcdef *
print("abc. DEF".capitalize()) d) * abcdef*

a) abc. def Answer: b


b) ABC. DEF Explanation: Padding is done towards the
c) Abc. def left-hand-side first when the final string is of
d) Abc. Def odd length. Extra spaces are present since we

ww
Answer: c
Explanation: The first letter of the string is
haven’t overridden the value of sep.

6. What will be the output of the following

w.E
converted to uppercase and the others are
converted to lowercase.
Python code?

print('*', "abcdef".center(7), '*', sep=

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

4. What will be the output of the following


Python code?
Python code?
et
print('*', "abcde".center(6), '*', sep=''
)
print("abcdef".center(0))
a) * abcde *
a) cd b) * abcde *
b) abcdef c) *abcde *
c) error d) * abcde*
d) none of the mentioned
Answer: c
Answer: b Explanation: Padding is done towards the
Explanation: The entire string is printed right-hand-side first when the final string is of
when the argument passed to center() is less even length.
than the length of the string.
8. What will be the output of the following
Python code?

Downloaded From: www.EasyEngineering.net 39


Downloaded From: www.EasyEngineering.net

print("abcdef".center(7, 1)) Answer: a


Explanation: Counts the number of times the
a) 1abcdef substring ‘yy’ is present in the given string.
b) abcdef1
c) abcdef 2. What will be the output of the following
d) error Python code?
Answer: d print("xyyzxyzxzxyy".count('yy', 1))
Explanation: TypeError, the fill character
must be a character, not an int. a) 2
b) 0
9. What will be the output of the following c) 1
Python code? d) none of the mentioned

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.

3. What will be the output of the following


Answer: a asy
Explanation: The character ‘1’ is used for
Python code?

padding instead of a space.


En print("xyyzxyzxzxyy".count('yy', 2))

a) 2

Python code? gin


10. What will be the output of the following b) 0
c) 1

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

exactly one character long. print("xyyzxyzxzxyy".count('xyy', 0, 100)


)
1. What will be the output of the following
Python code? a) 2
b) 0
print("xyyzxyzxzxyy".count('yy')) c) 1
d) error
a) 2
b) 0 Answer: a
c) error Explanation: An error will not occur if the
d) none of the mentioned end value is greater than the length of the
string itself.

Downloaded From: www.EasyEngineering.net 40


Downloaded From: www.EasyEngineering.net

5. What will be the output of the following b) qwerty


Python code? c) utf-8
d) utf-16
print("xyyzxyzxzxyy".count('xyy', 2, 11))
Answer: c
a) 2 Explanation: The default value of encoding
b) 0 is utf-8.
c) 1
d) error 9. What will be the output of the following
Python code?
Answer: b
Explanation: Counts the number of times the print("xyyzxyzxzxyy".endswith("xyy"))
substring ‘xyy’ is present in the given string,
starting from position 2 and ending at a) 1

ww
position 11.

6. What will be the output of the following


b) True
c) 3
d) 2

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

Downloaded From: www.EasyEngineering.net 41


Downloaded From: www.EasyEngineering.net

spaces by default. print("abcdef".find("cd"))

2. What will be the output of the following a) True


Python code? b) 2
c) 3
print("ab\tcd\tef".expandtabs(4)) d) None of the mentioned

a) ab  cd  ef Answer: b


b) abcdef Explanation: The first position in the given
c) ab\tcd\tef string at which the substring can be found is
d) ab cd ef returned.

Answer: d 6. What will be the output of the following


Explanation: Each \t is converted to 4 blank Python code?

ww
spaces.

3. What will be the output of the following


print("ccdcddcd".find("c"))

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

Answer: d gin returned.

passed as an argument. ee
Explanation: TypeError, an integer should be

4. What will be the output of the following


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

rin
print("Hello {0} and {1}".format('foo',
Python code? 'bin'))

a) Hello foo and bin g.n


print("abcdef".find("cd") == "cd" in "abc
def")

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

Downloaded From: www.EasyEngineering.net 42


Downloaded From: www.EasyEngineering.net

c) Error their names.


d) None of the mentioned
2. What will be the output of the following
Answer: a Python code?
Explanation: The numbers 0 and 1 represent
the position at which the strings are present. print("Hello {0!r} and {0!s}".format('fo
o', 'bin'))
9. What will be the output of the following
a) Hello foo and foo
Python code?
b) Hello ‘foo’ and foo
print("Hello {} and {}".format('foo', 'bi c) Hello foo and ‘bin’
n')) d) Error

a) Hello foo and bin Answer: b

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

a) Hello foo and bin


b) Hello {name1} and {name2}
c) Error
ee Answer: c

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

a) Hello foo and bin Answer: a


b) Hello {name1} and {name2} Explanation: The elements of the tuple are
c) Error accessed by their indices.
d) Hello and
5. What will be the output of the following
Answer: a Python code snippet?
Explanation: The arguments are accessed by

Downloaded From: www.EasyEngineering.net 43


Downloaded From: www.EasyEngineering.net

print('The sum of {0} and {1} is {2}'.for Answer: d


mat(2, 10, 12)) Explanation: An integer is expected.
a) The sum of 2 and 10 is 12 9. What will be the output of the following
b) Error Python code snippet?
c) The sum of 0 and 1 is 2
d) None of the mentioned print('{:$}'.format(1112223334))

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.

10. What will be the output of the following

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

Python code snippet?

print('{:,}'.format(1112223334))
ee
7. What will be the output of the following Explanation: The number is printed as it is.

Python code? rin


1. What will be the output of the following

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

Downloaded From: www.EasyEngineering.net 44


Downloaded From: www.EasyEngineering.net

c) 33.33% 6. What will be the output of the following


d) 33% Python code?

Answer: c print('a B'.isalpha())


Explanation: The symbol % is used to
represent the result of an expression as a a) True
percentage. b) False
c) None
3. What will be the output of the following d) Error
Python code?
Answer: b
print('ab12'.isalnum()) Explanation: Space is not a letter.

a) True 7. What will be the output of the following

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.

5. What will be the output of the following


c) None
d) Error et
Python code? Answer: b
Explanation: If there are no characters then
print('ab'.isalpha()) False is returned.

a) True 9.What will be the output of the following


b) False Python code snippet?
c) None
d) Error print('my_string'.isidentifier())

Answer: a a) True
Explanation: The string has only letters. b) False
c) None
d) Error

Downloaded From: www.EasyEngineering.net 45


Downloaded From: www.EasyEngineering.net

Answer: a c) None
Explanation: It is a valid identifier. d) Error

10. What will be the output of the following Answer: a


Python code snippet? Explanation: There are no uppercase letters.

print('__foo__'.isidentifier()) 4. What will be the output of the following


Python code snippet?
a) True
b) False print('11'.isnumeric())
c) None
d) Error a) True
b) False
Answer: a c) None

ww
Explanation: It is a valid identifier.

1. What will be the output of the following


d) Error

Answer: a

w.E
Python code snippet?

print('for'.isidentifier())
Explanation: All the character are numeric.

5. What will be the output of the following


a) True
b) False
asy Python code snippet?

c) None
d) Error En print('1.1'.isnumeric())

a) True

Answer: a gin b) False


c) None

as valid identifiers. ee
Explanation: Even keywords are considered

2. What will be the output of the following


d) Error

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

3. What will be the output of the following Answer: a


Python code snippet? Explanation: All those characters are
printable.
print('fewjfw 1,'.islower())
7. What will be the output of the following
a) True Python code snippet?
b) False

Downloaded From: www.EasyEngineering.net 46


Downloaded From: www.EasyEngineering.net

print(''''''.isspace()) 1. What will be the output of the following


Python code?
a) True
b) False print('#World'.istitle())
c) None
d) Error a) True
b) False
Answer: b c) None
Explanation: None. d) error

8. What will be the output of the following Answer: a


Python code snippet? Explanation: It is in the form of a title.

print('\t'.isspace()) 2. What will be the output of the following

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

Downloaded From: www.EasyEngineering.net 47


Downloaded From: www.EasyEngineering.net

c) z so it’s behaviour does not depend on the


d) zxxy object from which it is being called.

Answer: b 8. What will be the output of the following


Explanation: The leading characters Python code?
containing xyy are removed.
print('abcdef'.partition('cd'))
5. What will be the output of the following
Python code? a) (‘ab’, ‘ef’)
b) (‘abef’)
print('xyxxyyzxxy'.lstrip('xyy')) c) (‘ab’, ‘cd’, ‘ef’)
d) 2
a) zxxy
b) xyxxyyzxxy Answer: c

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?

from the left hand side.


asy print('abcdefcdgh'.partition('cd'))

a) (‘ab’, ‘cd’, ‘ef’, ‘cd’, ‘gh’)


Python code?
En
6. What will be the output of the following
b) (‘ab’, ‘cd’, ‘efcdgh’)
c) (‘abcdef’, ‘cd’, ‘gh’)
print('cba'.maketrans('abc', '123'))
gin d) error

a) {97: 49, 98: 50, 99: 51}


b) {65: 49, 66: 50, 67: 51}
c) 321
d) 123
ee Answer: b
Explanation: The string is partitioned at the

rin
point where the separator first appears.

Answer: a Python code? g.n


10. What will be the output of the following

Explanation: A translation table is returned


by maketrans.

7. What will be the output of the following


print('abcd'.partition('cd'))

a) (‘ab’, ‘cd’, ”)
et
Python code? b) (‘ab’, ‘cd’)
c) error
print('a'.maketrans('ABC', '123')) d) none of the mentioned

a) {97: 49, 98: 50, 99: 51} Answer: a


b) {65: 49, 66: 50, 67: 51} Explanation: The last item is a null string.
c) {97: 49}
d) 1 1. What will be the output of the following
Python code snippet?
Answer: b
Explanation: maketrans() is a static method print('cd'.partition('cd'))

Downloaded From: www.EasyEngineering.net 48


Downloaded From: www.EasyEngineering.net

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.

Answer: d 5. What will be the output of the following


Explanation: The entire string has been Python code snippet?
passed as the separator hence the first and the
last item of the tuple returned are null strings. print('abcefd'.replace('cd', '12'))

2. What will be the output of the following a) ab1ef2


Python code snippet? b) abcefd
c) ab1efd
print('abef'.partition('cd')) d) ab12ed2

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

Python code snippet? gin


3. What will be the output of the following
a) xyyxyyxyxyxxy

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.

7. What will be the output of the following


Python code snippet?
substring are replaced by the second
print('xyyxyyxyxyxxy'.replace('xy', '12',
substring. 100))

4. What will be the output of the following a) xyyxyyxyxyxxy


Python code snippet? b) 12y12y1212x12
print('abef'.replace('cd', '12'))
c) none of the mentioned
d) error
a) abef
b) 12 Answer: b
c) error Explanation: The first 100 occurrences of the
d) none of the mentioned given substring are replaced.

Downloaded From: www.EasyEngineering.net 49


Downloaded From: www.EasyEngineering.net

8. What will be the output of the following a) [‘ab’, ‘ef’, ‘ghcd’]


Python code snippet? b) [‘ab’, ‘efcdghcd’]
c) [‘abcdef’, ‘ghcd’]
print('abcdefcdghcd'.split('cd')) d) none of the mentioned
a) [‘ab’, ‘ef’, ‘gh’] Answer: a
b) [‘ab’, ‘ef’, ‘gh’, ”] Explanation: The string is split into a
c) (‘ab’, ‘ef’, ‘gh’) maximum of maxsplit+1 substrings.
d) (‘ab’, ‘ef’, ‘gh’, ”)
2. What will be the output of the following
Answer: b Python code snippet?
Explanation: The given string is split and a
list of substrings is returned. print('ab\ncd\nef'.splitlines())

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

Answer: a En 3. What will be the output of the following

gin
Explanation: The given string is split at 0
occurances of the specified substring.
Python code snippet?

print('Ab!2'.swapcase())

Python code snippet?


ee
10. What will be the output of the following a)
b) ab12
c) aB!2 rin
print('abcdefcdghcd'.split('cd', -1))

a) [‘ab’, ‘ef’, ‘gh’]


d)
g.n
b) [‘ab’, ‘ef’, ‘gh’, ”]
c) (‘ab’, ‘ef’, ‘gh’)
d) (‘ab’, ‘ef’, ‘gh’, ”)
Answer: c
et
Explanation: Lowercase letters are converted
to uppercase and vice-versa.

4. What will be the output of the following


Answer: b Python code snippet?
Explanation: Calling the function with a
negative value for maxsplit is the same as print('ab cd ef'.title())
calling it without any maxsplit specified. The
string will be split into as many substring s as a) Ab cd ef
possible. b) Ab cd eF
c) Ab Cd Ef
1. What will be the output of the following d) None of the mentioned
Python code snippet?
Answer: c
print('abcdefcdghcd'.split('cd', 2)) Explanation: The first letter of every word is

Downloaded From: www.EasyEngineering.net 50


Downloaded From: www.EasyEngineering.net

capitalized. print('abcd'.translate({'a': '1', 'b':


'2', 'c': '3', 'd': '4'}))
5. What will be the output of the following
Python code snippet? a) abcd
b) 1234
print('ab cd-ef'.title()) c) error
d) none of the mentioned
a) Ab cd-ef
b) Ab Cd-ef Answer: a
c) Ab Cd-Ef Explanation: The function translate expects a
d) None of the mentioned dictionary of integers. Use maketrans()
instead of doing the above.
Answer: c
Explanation: The first letter of every word is 9. What will be the output of the following

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?

print('abcd'.translate({97: 98, 98: 99, 9


9: 100}))
b) 00099
c) +0099
d) +++99
et
a) bcde Answer: c
b) abcd Explanation: zeros are filled in between the
c) error first sign and the rest of the string.
d) none of the mentioned

Answer: d TOPIC 3.3 FUNCTIONS


Explanation: The output is bcdd since no
translation is provided for d.
TOPIC 3.3.1 BUILT-IN
8. What will be the output of the following FUNCTIONS
Python code snippet?

Downloaded From: www.EasyEngineering.net 51


Downloaded From: www.EasyEngineering.net

1. Which of the following functions is a built- all([2,4,0,6])


in function in python?
a) seed() a) Error
b) sqrt() b) True
c) factorial() c) False
d) print() d) 0

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

3. The function pow(x,y,z) is evaluated as:


a) (x**y)**z
any([2>8, 4>2, 1>2])

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?

Downloaded From: www.EasyEngineering.net 52


Downloaded From: www.EasyEngineering.net

import math min(max(False,-3,-4), 2,7)


abs(math.sqrt(25))
a) 2
a) Error b) False
b) -5 c) -3
c) 5 d) -4
d) 5.0
Answer: b
Answer: d Explanation: The function max() is being
Explanation: The abs() function prints the used to find the maximum value from among
absolute value of the argument passed. For -3, -4 and false. Since false amounts to the
example: abs(-5)=5. Hence, in this case we value zero, hence we are left with min(0, 2, 7)
get abs(5.0)=5.0. Hence the output is 0 (false).

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?

Downloaded From: www.EasyEngineering.net 53


Downloaded From: www.EasyEngineering.net

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)

Answer: d (2.0, 0.5)

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.

3. What is the output of the function


d)

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

4. The function divmod(a,b), where both ‘a’


b) False
g.n
and ‘b’ are integers is evaluated as:
a) (a%b, a//b)
b) (a//b, a%b)
c) (a//b, a*b)
Answer: a
et
Explanation: When converting from a string,
the string must not contain any blank spaces
around the + or – operator. Hence the
d) (a/b, a%b) function complex(‘2 – 3j’) will result in an
error.
Answer: b
Explanation: The function divmod(a,b) is 7. What will be the output of the following
evaluated as a//b, a%b, if both ‘a’ and ‘b’ are Python function?
integers. list(enumerate([2, 3]))

5. What will be the output of the following a) Error


Python function? b) [(1, 2), (2, 3)]
divmod(10.5,5)
c) [(0, 2), (1, 3)]
divmod(2.4,1.2) d) [(2, 3)]

Downloaded From: www.EasyEngineering.net 54


Downloaded From: www.EasyEngineering.net

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.

9. What will be the output of the following


whereas the function chr() throws an error on
receiving an iterable as an argument. Also
Python functions?

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.

0.001 2. Suppose there is a list such that: l=[2,3,4].


If we want to print this list in reverse order,
200 which of the following methods should be
used?
d) a) reverse(l)

Downloaded From: www.EasyEngineering.net 55


Downloaded From: www.EasyEngineering.net

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.

4. What will be the output of the following


b)
g.n
Python function?

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

Downloaded From: www.EasyEngineering.net 56


Downloaded From: www.EasyEngineering.net

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

Downloaded From: www.EasyEngineering.net 57


Downloaded From: www.EasyEngineering.net

Answer: c Hello World!


Explanation: The function oct() is used to
Hello World!
convert its argument into octal form. This
function does not accept strings. Hence the b)
second function results in an error while the
output of the first function is 0o7. 'Hello World!'

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

2. Which keyword is used for function?


a) Fun
ee
in your program and any number of times. 1. def sayHello():
2.
rin
print('Hello World!') # block b
elonging to the 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)

Downloaded From: www.EasyEngineering.net 58


Downloaded From: www.EasyEngineering.net

5. print(a, 'is equal to', b) c)


6. else: x is 50

7. print(b, 'is maximum') Changed local x to 2

8. printMax(3, 4) x is now 100

a) 3 d) None of the mentioned


b) 4
c) 4 is maximum Answer: a
d) None of the mentioned Explanation: The first time that we print the
value of the name x with the first line in the
Answer: c function’s body, Python uses the value of the
parameter declared in the main block, above

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.

Python code? asy


5. What will be the output of the following With the last print function call, we display
the value of x as defined in the main block,
thereby confirming that it is actually
1. x = 50
En unaffected by the local assignment within the
previously called function.
2. def func(x):
3. print('x is', x) gin 6. What will be the output of the following

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

Downloaded From: www.EasyEngineering.net 59


Downloaded From: www.EasyEngineering.net

b) d)

x is 50 Hello

Changed global x to 2 HelloHelloHelloHelloHello

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

Downloaded From: www.EasyEngineering.net 60


Downloaded From: www.EasyEngineering.net

a is 25 and b is 5 and c is 24 parameter c before that for a even though a is


defined before c in the function definition.
a is 5 and b is 100 and c is 50
9. What will be the output of the following
b)
Python code?
a is 3 and b is 7 and c is 10
1. def maximum(x, y):
a is 5 and b is 25 and c is 24
2. if x > y:
a is 50 and b is 100 and c is 5
3. return x
c)
4. elif x == y:
a is 3 and b is 7 and c is 10
5. return 'The numbers are equ

ww
a is 25 and b is 5 and c is 24

a is 100 and b is 5 and c is 50 6.


al'

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

In the first usage, func(3, 7), the parameter a


gets the value 3, the parameter b gets the
value 7 and c gets the default value of 10.
et
value and then returns that value.

10. Which of the following is a feature of


DocString?
a) Provide a convenient way of associating
In the second usage func(25, c=24), the documentation with Python modules,
variable a gets the value of 25 due to the functions, classes, and methods
position of the argument. Then, the parameter b) All functions should have a docstring
c gets the value of 24 due to naming i.e. c) Docstrings can be accessed by the __doc__
keyword arguments. The variable b gets the attribute on objects
default value of 5. d) All of the mentioned

In the third usage func(c=50, a=100), we use Answer: d


keyword arguments for all specified values. Explanation: Python has a nifty feature
Notice that we are specifying the value for called documentation strings, usually referred
to by its shorter name docstrings. DocStrings

Downloaded From: www.EasyEngineering.net 61


Downloaded From: www.EasyEngineering.net

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

Answer: b asy Answer: a


SP
Explanation: Functions that are always
available for usage, functions that are

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.

3. Where is function defined? ee A sqrt() function is imported from the math


module.

rin
.B

a) Module 7. What will be the output of the following


b) Class Python code?
g.n
17

c) Another function
d) All of the mentioned 1. def cube(x):

Answer: d 2. return x * x * xet


-R

Explanation: Functions can be defined inside


3. x = cube(3)
a module, a class or another function.
SE

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

Downloaded From: www.EasyEngineering.net 62


Downloaded From: www.EasyEngineering.net

ww
w.E
a syE
ngi
nee
rin
g.n
et

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials, Students & Graduates if You Find the Same Materials with
EasyEngineering.net Watermarks or Logo, Kindly report us to
easyengineeringnet@gmail.com
Downloaded From: www.EasyEngineering.net
Downloaded From: www.EasyEngineering.net

values from a function. A function may or 5. return r


may not return a value. If a function does not
have a return keyword, it will send a none 6. print power(3)
value. 7. print power(3, 3)
8. What will be the output of the following a)
Python code?
212
1. def C2F(c):
32
2. return c * 9/5 + 32
b)
3. print C2F(100)
9

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'''

1. def power(x, y=2): 4. r = 0

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__

Downloaded From: www.EasyEngineering.net 63


Downloaded From: www.EasyEngineering.net

9. print sum(1, 2, 3) 2. What will be the output of the following


Python code?
10. print sum(1, 2, 3, 4, 5)
1. y = 6
a)
2. z = lambda x: x * y
6
3. print z(8)
15
a) 48
b) b) 14
c) 64
6
d) None of the mentioned
100

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.

1. Python supports the creation of anonymous g.n


1. lamb = lambda x: x ** 3
functions at runtime, using a construct called
__________
a) lambda
2. print(lamb(5))

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.

Downloaded From: www.EasyEngineering.net 64


Downloaded From: www.EasyEngineering.net

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

Answer: b asy 3. lambda x: x ** 4]

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

1. def f(x, y, z): return x + y + z


2. f(2, 30, 400)
ee a)

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

3. name = (lambda x:title + ' 27


' + x)
81
4. return name

Downloaded From: www.EasyEngineering.net 65


Downloaded From: www.EasyEngineering.net

d) None of the mentioned i=0


def change(i):
Answer: c i=i+1
return i
Explanation: None. change(1)
print(i)
10. What will be the output of the following
Python code? a) 1
b) Nothing is displayed
1. min = (lambda x, y: x if x < y else c) 0
y) d) An exception is thrown
2. min(101*99, 102*98)
Answer: c
a) 9997 Explanation: Any change made in to an
immutable data type in a function isn’t

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

as a global variable and can be used by


multiple functions of the program.
Answer: b
g.n
Explanation: Since a list is mutable, any
change made in the list in the function is
2. What is a variable defined inside a function
referred to as?
a) A global variable
et
reflected outside the function.

5. What will be the output of the following


Python code?
b) A volatile variable
c) A local variable a=10
d) An automatic variable b=20
def change():
Answer: c global b
Explanation: The variable inside a function a=45
b=56
is called as local variable and the variable change()
definition is confined only to that function. print(a)
print(b)
3. What will be the output of the following
Python code? a)

Downloaded From: www.EasyEngineering.net 66


Downloaded From: www.EasyEngineering.net

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

a) An exception is thrown because of


display('z',3)
g.n
conflicting values
b) 1 2
c) 3 3
d) 3 2
a) zzz
b) zz
et
c) An exception is executed
d) Infinite loop

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)

Downloaded From: www.EasyEngineering.net 67


Downloaded From: www.EasyEngineering.net

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

2. What is the length of sys.argv?En Answer: c


Explanation: Zero keyword arguments may
a) number of arguments
b) number of arguments + 1 gin be passed if all the arguments have default
values.
c) number of arguments – 1
d) none of the mentioned

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.

3. What will be the output of the following


foo(min, [1, 2, 3])

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.

a) [0] 7. What will be the output of the following


b) [1] Python code?
c) [1, 0]
d) [0, 1] def foo():
return total + 1

Downloaded From: www.EasyEngineering.net 68


Downloaded From: www.EasyEngineering.net

total = 0 def foo(i, x=[]):


print(foo()) x.append(i)
return x
a) 0 for i in range(3):
b) 1 print(foo(i))
c) error
a) [0] [1] [2]
d) none of the mentioned
b) [0] [0, 1] [0, 1, 2]
Answer: b c) [1] [2] [3]
Explanation: It is possible to read the value d) [1] [1, 2] [1, 2, 3]
of a global variable directly.
Answer: b
8. What will be the output of the following Explanation: When a list is a default value,
Python code? the same list will be reused.

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?

Downloaded From: www.EasyEngineering.net 69


Downloaded From: www.EasyEngineering.net

a) getopt within square brackets ([])


b) os d) identifier
c) getarg
d) main Answer: d
Explanation: Refer documentation.
Answer: a
Explanation: getopt parses options received 8. What will be the output of the following
from the command line. Python code?

4. What is the type of sys.argv? def foo(x):


x[0] = ['def']
a) set x[1] = ['abc']
b) list return id(x)
c) tuple q = ['abc', 'def']
d) string print(id(q) == foo(q))

ww
Answer: b a) True
b) False
w.E
Explanation: It is a list of elements.

5. What is the value stored in sys.argv[0]?


c) None
d) Error
a) null
b) you cannot access it
c) the program’s name asy Answer: a
Explanation: The same object is modified in
d) the first argument
En the function.

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

a) identifier followed by an equal to sign and


b) os.argv
c) argv
d) none of the mentioned
rin
the default value
b) identifier followed by the default value
within backticks (“)
Answer: a
g.n
Explanation: Refer documentation.
c) identifier followed by the default value
within square brackets ([])
d) identifier Python code?
et
10. What will be the output of the following

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


x.append(x.append(i))
Explanation: Refer documentation. return x
for i in range(3):
7. How are required arguments specified in y = foo(i)
the function heading? print(y)
a) identifier followed by an equal to sign and
the default value a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]
b) identifier followed by the default value b) [[0], [[0], 1], [[0], [[0], 1], 2]]
within backticks (“) c) [0, None, 1, None, 2, None]
c) identifier followed by the default value d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]]

Downloaded From: www.EasyEngineering.net 70


Downloaded From: www.EasyEngineering.net

Answer: c def san(x):


Explanation: append() returns None. print(x+1)
x=-2
x=4
TOPIC 3.4 LOCAL AND san(12)

GLOBAL SCOPE a) 13
b) 10
1. What will be the output of the following c) 2
Python code? d) 5

def f1(): Answer: a


x=15 Explanation: The value passed to the
print(x)
x=12
function san() is 12. This value is

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

code shown above is 15. gin


over global variable. Hence the output of the
a) Error

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

Downloaded From: www.EasyEngineering.net 71


Downloaded From: www.EasyEngineering.net

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.

7. What will be the output of the following


Python code? 8. What will be the output of the following
Python code?
def f():
global a def f1(a,b=[]):
print(a) b.append(a)
a = "hello"
print(a)

Downloaded From: www.EasyEngineering.net 72


Downloaded From: www.EasyEngineering.net

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)

En 11. What will be the output of the following


Python code?
G
p,q,r,s = 1,2,3,4
f(5,10,15)

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

Explanation: The above code shows a total = f2(1,2)


print(total)
combination of local and global variables.
The output of this code is: 10 20 30 40
a) Error et
-R

10. What will be the output of the following b) 7


Python code? c) 8
d) 15
SE

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.

a) 12. What will be the output of the following


Python code?
outer

Downloaded From: www.EasyEngineering.net 73


Downloaded From: www.EasyEngineering.net

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.

13. Read the following Python code carefully


c) 0
d) Error

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?

1. Which of the following data structures is e="butter"


def f(a): print(a)+e
returned by the functions globals() and f("bitter")
locals()?
a) list a) error
b) set b)
c) dictionary
d) tuple butter

error

Downloaded From: www.EasyEngineering.net 74


Downloaded From: www.EasyEngineering.net

c) def f(): x=4


x=1
bitter f()
x
error
a) Error
d) bitterbutter b) 4
c) Junk value
Answer: c d) 1
Explanation: The output of the code shown
above will be ‘bitter’, followed by an error. Answer: d
The error is because the operand ‘+’ is Explanation: In the code shown above, when
unsupported on the types used above. we call the function f, a new namespace is
created. The assignment x=4 is performed in

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?

Downloaded From: www.EasyEngineering.net 75


Downloaded From: www.EasyEngineering.net

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)

can be solved using recursion. gin


2. Only problems that are recursively defined print(test(4,7))

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="")

Downloaded From: www.EasyEngineering.net 76


Downloaded From: www.EasyEngineering.net

a) 011 a) Every recursive function must have a base


b) 110 case
c) 3 b) Infinite recursion can occur if the base case
d) Infinite loop isn’t properly mentioned
c) A recursive function makes the code easier
Answer: b to understand
Explanation: The above code gives the d) Every recursive function must have a
binary equivalent of the number. return value

7. What is tail recursion? Answer: d


a) A recursive function that has two base Explanation: A recursive function needn’t
cases have a return value.
b) A function where the recursive functions
leads to an infinite loop 10. What will be the output of the following

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

a) Both a() and b() aren’t tail recursive b) False


b) Both a() and b() are tail recursive
Answer: b
c) b() is tail recursive but a() isn’t
Explanation: In recursion, the function calls
d) a() is tail recursive but b() isn’t
itself till the base condition is reached
Answer: c whereas iteration means repetition of process
Explanation: A recursive function is tail for example in for-loops.
recursive when recursive call is executed by
12. What happens if the base condition isn’t
the function in the last.
defined in recursive programs?
9. Which of the following statements is false a) Program gets into an infinite loop
about recursion? b) Program runs once

Downloaded From: www.EasyEngineering.net 77


Downloaded From: www.EasyEngineering.net

c) Program runs n number of times where n is a) 0 1 2 3


the argument given to the function b) An exception is thrown
d) An exception is thrown c) 0 1 1 2 3
d) 0 1 1 2
Answer: a
Explanation: The program will run until the Answer: d
system gets out of memory. Explanation: The above piece of code prints
the Fibonacci series.
13. Which of these is not true about

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

d) Programs using recursion take longer time c) list1 = list([1, 2, 3])


than their non-recursive equivalent d) all of the mentioned
g.n
17

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

may be hard to follow. 2. What is the output when we execute


list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
SE

15. What will be the output of the following


Python code? b) [‘hello’]
c) [‘llo’]
def a(n): d) [‘olleh’]
C

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

Downloaded From: www.EasyEngineering.net 78


Downloaded From: www.EasyEngineering.net

b) 4 8. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0],


c) None Which of the following is correct syntax for
d) Error slicing operation?
a) print(list1[0])
Answer: a b) print(list1[:2])
Explanation: Execute in the shell and verify. c) print(list1[:-2])
d) all of the mentioned
4. Suppose list1 is [2445,133,12454,123],
what is max(list1)? Answer: d
a) 2445 Explanation: Slicing is allowed in lists just
b) 133 as in the case of strings.
c) 12454
d) 123 9. Suppose list1 is [2, 33, 222, 14, 25], What
is list1[-1]?

ww
Answer: c
Explanation: Max returns the maximum
a) Error
b) None

w.E
element in the list.

5. Suppose list1 is [3, 5, 25, 1, 3], what is


c) 25
d) 2

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

Answer: d gin is list1[:-1]?


a) [2, 33, 222, 14]
Explanation: Min returns the minimum
element in the list.

6. Suppose list1 is [1, 5, 9], what is


ee b) Error
c) 25

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?

Answer: c 1. >>>names = ['Amir', 'Bear', 'Charlt


Explanation: Sum returns the sum of all on', 'Daman']
elements in the list.
2. >>>print(names[-1][-1])
7. To shuffle the list(say list1) what function
a) A
do we use?
b) Daman
a) list1.shuffle()
c) Error
b) shuffle(list1)
d) n
c) random.shuffle(list1)
d) random.shuffleList(list1) Answer: d
Explanation: Execute in the shell to verify.
Answer: c
Explanation: Execute in the shell to verify.

Downloaded From: www.EasyEngineering.net 79


Downloaded From: www.EasyEngineering.net

2. What will be the output of the following c) [1, 3, 2, 1, 3, 2]


Python code? d) [1, 3, 2, 3, 2, 1]

1. names1 = ['Amir', 'Bear', 'Charlto Answer: c


n', 'Daman'] Explanation: Execute in the shell and verify.
2. names2 = names1 4. Suppose list1 = [0.5 * x for x in range(0,
3. names3 = names1[:] 4)], list1 is:
a) [0, 1, 2, 3]
4. b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
5. names2[0] = 'Alice' d) [0.0, 0.5, 1.0, 1.5, 2.0]
6. names3[1] = 'Bob' Answer: c

ww 7. Explanation: Execute in the shell to verify.

5. What will be the output of the following


w.E
8. sum = 0
9. for ls in (names1, names2, names3):
Python code?

1. >>>list1 = [11, 2, 23]


10.
11.
asy
if ls[0] == 'Alice':
2. >>>list2 = [11, 2, 2]

12.
sum += 1

if ls[1] == 'Bob': En 3. >>>list1 < list2 is

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

Explanation: When assigning names1 to b) list1.append(5)


names2, we create a second reference to the c) list1.addLast(5)
same list. Changes to names2 affect names1. d) list1.addEnd(5)
When assigning the slice of all elements in
names1 to names3, we are creating a full Answer: b
copy of names1 which can be modified Explanation: We use the function append to
independently. add an element to the list.

3. Suppose list1 is [1, 3, 2], What is list1 * 2? 7. To insert 5 to the third position in list1, we
a) [2, 6, 4] use which command?
b) [1, 3, 2, 1, 3] a) list1.insert(3, 5)
b) list1.insert(2, 5)

Downloaded From: www.EasyEngineering.net 80


Downloaded From: www.EasyEngineering.net

c) list1.add(3, 5) listExample.extend([34, 5])?


d) list1.append(3, 5) a) [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
b) [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
Answer: b c) [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
Explanation: Execute in the shell to verify. d) [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]

8. To remove string “hello” from list1, we use Answer: a


which command? Explanation: Execute in the shell to verify.
a) list1.remove(“hello”)
b) list1.remove(hello) 3. Suppose listExample is [3, 4, 5, 20, 5, 25,
c) list1.removeAll(“hello”) 1, 3], what is list1 after listExample.pop(1)?
d) list1.removeOne(“hello”) a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
Answer: a c) [3, 5, 20, 5, 25, 1, 3]

ww
Explanation: Execute in the shell to verify.

9. Suppose list1 is [3, 4, 5, 20, 5], what is


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

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

Answer: d En a) [3, 4, 5, 20, 5, 25, 1]


b) [1, 3, 3, 4, 5, 5, 20, 25]

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

a) [“Welcome”, “to”, “Python”]


1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], b) (“Welcome”, “to”, “Python”)
what is list1 after list1.reverse()? c) {“Welcome”, “to”, “Python”}
a) [3, 4, 5, 20, 5, 25, 1, 3] d) “Welcome”, “to”, “Python”
b) [1, 3, 3, 4, 5, 5, 20, 25]
c) [25, 20, 5, 5, 4, 3, 3, 1] Answer: a
d) [3, 1, 25, 5, 20, 5, 4, 3] Explanation: split() function returns the
elements in a list.
Answer: d
Explanation: Execute in the shell to verify. 6. What will be the output of the following
Python code?
2. Suppose listExample is [3, 4, 5, 20, 5, 25,
1, 3], what is list1 after 1. >>>list("a#b#c#d".split('#'))

Downloaded From: www.EasyEngineering.net 81


Downloaded From: www.EasyEngineering.net

a) [‘a’, ‘b’, ‘c’, ‘d’] a) 2 3 4 5 6 1


b) [‘a b c d’] b) 6 1 2 3 4 5
c) [‘a#b#c#d’] c) 2 3 4 5 6 6
d) [‘abcd’] d) 1 1 2 3 4 5

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?

1. myList = [1, 5, 5, 5, 5, 1] 1. >>>list1 = [1, 3]


2. max = myList[0] 2. >>>list2 = list1

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

9. >>>print(indexOfMax) gin Explanation: Lists should be copied by


executing [:] operation.
a) 1
b) 2
c) 3
ee 10. What will be the output of the following
Python code?
rin
d) 4

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]

5. for i in range(0, 6): Answer: c


Explanation: Execute in the shell to verify.
6. print(myList[i], end = " ")

Downloaded From: www.EasyEngineering.net 82


Downloaded From: www.EasyEngineering.net

1. What will be the output of the following 1. names1 = ['Amir', 'Bala', 'Charlie'
Python code? ]

1. def f(i, values = []): 2. names2 = [name.lower() for name in


names1]
2. values.append(i)
3.
3. return values
4. print(names2[2][0])
4.
a) None
5. f(1) b) a
c) b
6. f(2) d) c

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.

4. What will be the output of the following


Python code?
c) [1, 2, 3]
d) 1 2 3 asy 1. numbers = [1, 2, 3, 4]
Answer: c
En
Explanation: Execute in the shell to verify
2.

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.

a) None 5. To which of the following the “in” operator


b) 1 can be used to check if an item is in it?
c) 2 a) Lists
d) Error b) Dictionary
c) Set
Answer: c d) All of the mentioned
Explanation: Execute in the shell to verify.
Answer: d
3. What will be the output of the following Explanation: In can be used in all data
Python code? structures.

Downloaded From: www.EasyEngineering.net 83


Downloaded From: www.EasyEngineering.net

6. What will be the output of the following 3. while i < len(L):


Python code?
4. L[i] = L[i] + increment
1. list1 = [1, 2, 3, 4]
5. i = i + 1
2. list2 = [5, 6, 7, 8]
6.
3.
7. values = [1, 2, 3]
4. print(len(list1 + list2))
8. print(increment_items(values, 2))
a) 2 9. print(values)
b) 4
c) 5 a)

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?

8. What will be the output of the following 1. def example(L):


Python code?
2. ''' (list) -> list
1. def increment_items(L, increment):
3. '''
2. i = 0
4. i = 0

Downloaded From: www.EasyEngineering.net 84


Downloaded From: www.EasyEngineering.net

5. result = [] 1. >>>m = [[x, x + 1, x + 2] for x in


range(0, 3)]
6. while i < len(L):
a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
7. result.append(L[i]) b) [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
c) [1, 2, 3, 4, 5, 6, 7, 8, 9]
8. i = i + 3
d) [0, 1, 2, 1, 2, 3, 2, 3, 4]
9. return result
Answer: b
a) Return a list containing every third item Explanation: Execute in the shell to verify.
from L starting at index 0
b) Return an empty list 2. How many elements are in m?
c) Return a list containing every third index
from L starting at index 0 1. m = [[x, y] for x in range(0, 4) fo

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.

3. What will be the output of the following

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)

a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’,


3. v = values[0][0]
g.n
‘asparagus’] Correct 1.00
b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’] 5. et
4. for row in range(0, len(values)):
for column in range(0, len(valu
es[row])):
c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’,
‘asparagus’] 6. if v < values[row][column]:

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

Downloaded From: www.EasyEngineering.net 85


Downloaded From: www.EasyEngineering.net

Answer: d b) The program prints on row 3 4 5 1 33 6 1 2


Explanation: Execute in the shell to verify. c) The program prints two rows 3 4 5 1
followed by 33 6 1 2
4. What will be the output of the following d) The program prints two rows 1 3 4 5
Python code? followed by 1 2 6 33

1. values = [[3, 4, 5, 1], [33, 6, 1, Answer: d


2]] Explanation: Execute in the shell to verify.
2. 6. What will be the output of the following
3. v = values[0][0] Python code?

4. for lst in values: 1. matrix = [[1, 2, 3, 4],

ww 5.
6.
for element in lst:

if v > element:
2.
3.
[4, 5, 6, 7],

[8, 9, 10, 11],

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.

1. values = [[3, 4, 5, 1 ], [33, 6, 1,


2]]
1. def m(list):
et
7. What will be the output of the following
Python code?

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

Downloaded From: www.EasyEngineering.net 86


Downloaded From: www.EasyEngineering.net

8. 9.
9. for row in values: 10. return v

10. print(m(row), end = " ") 11.

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.

10. What will be the output of the following

w.E
1. data = [[[1, 2], [3, 4]], [[5, 6],
[7, 8]]]
Python code?

1. points = [[1, 2], [3, 1.5], [0.5,


2.
3. print(data[1][0][0]) asy 0.5]]

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.

1. data = [[[1, 2], [3, 4]], [[5, 6],


[7, 8]]]
a=[10,23,56,[78]]
et
1. What will be the output of the following
Python code?

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

Downloaded From: www.EasyEngineering.net 87


Downloaded From: www.EasyEngineering.net

shallow copy and only changes made in Answer: b


sublist is reflected in the copied list. Explanation: The above copy is deepcopy.
Any change made in the original list isn’t
2. What will be the output of the following reflected.
Python code?
4. What will be the output of the following
print(list(zip((1,2,3),('a'),('xxx','yyy' Python code?
))))
print(list(zip((2,4),('b','c'),('yy','xx' s="@"
)))) a=list(s.partition("@"))
print(a)
a) b=list(s.split("@",3))
print(b)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)]
a)

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

[(1, 'a', 'xxx')]


gin c)

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

Explanation: The partition function only


Python code? splits for the first parameter along with the
import copy
separator while split function splits for the
a=[10,23,56,[78]] number of times given in the second
b=copy.deepcopy(a) argument but without the separator.
a[3][0]=95
a[1]=34
print(b)
5. What will be the output of the following
a) [10,34,56,[95]]
Python code?
b) [10,23,56,[78]]
c) [10,23,56,[95]] a=[1,2,3,4]
d) [10,34,56,[78]] b=[sum(a[0:x+1]) for x in range(0,len(a))

Downloaded From: www.EasyEngineering.net 88


Downloaded From: www.EasyEngineering.net

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

Downloaded From: www.EasyEngineering.net 89


Downloaded From: www.EasyEngineering.net

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

Downloaded From: www.EasyEngineering.net 90


Downloaded From: www.EasyEngineering.net

a) [[3],[7]] def unpack(a,b,c,d):


b) [1,2,3,4] print(a+d)
x = [1,2,3,4]
c) Error unpack(*x)
d) [10]
a) Error
Answer: b b) [1,4]
Explanation: The above piece of code is used c) [5]
for flattening lists. d) 5
6. What will be the output of the following Answer: d
Python code? Explanation: unpack(*x) unpacks the list
into the separate variables. Now, a=1 and
word1="Apple"
word2="Apple" d=4. Thus 5 gets printed.

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)

a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]

False gin b) [‘Bangalore’, ‘Pune’, ‘Delhi’]


c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
True

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

9. What will be the output of the following


True
Python code?
False
x=[[1],[2]]
Answer: d print(" ".join(list(map(str,x))))
Explanation: In the above case, both the lists
a) [1] [2]
are equivalent but not identical as they have
b) [49] [50]
different objects.
c) Syntax error
d) [[1]] [[2]]

Answer: a
7. What will be the output of the following
Explanation: The elements 1 and 2 are first
Python code?

Downloaded From: www.EasyEngineering.net 91


Downloaded From: www.EasyEngineering.net

put into separate lists and then combined with print(k)


a space in between using the join attribute. print(a)

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


Python code? 3
a=165 [44, 2, 3]
b=sum(list(map(int,str(a))))
print(b)
b)
a) 561 1
b) 5
c) 12 [1,2,3]
d) Syntax error

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)

Downloaded From: www.EasyEngineering.net 92


Downloaded From: www.EasyEngineering.net

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.

15. What will be the output of the following


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

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)

Downloaded From: www.EasyEngineering.net 93


Downloaded From: www.EasyEngineering.net

for i in list_0: print([i+j for i in "abc" for j in "def"]


if func(i): )
list_1.append(expr(i))
a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’,
c) ‘fc’]
b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’,
list_1 = []
‘bf’, ‘cf’]]
for i in list_0:
if func(i): c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’,
list_1.append(expr(i)) ‘fb’, ‘fc’]]
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
d) none of the mentioned ‘cf’]

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.

5. What will be the output of the following


8. What will be the output of the following
Python code snippet?

Python code snippet?


asy print([[i+j for i in "abc"] for j in "de
f"])

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

6. What will be the output of the following Answer: b g.n


Python code snippet?

print([i.lower() for i in "HELLO"])


for each value of j.
et
Explanation: The inner list is generated once

9. What will be the output of the following


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] Python code snippet?
b) ‘hello’
c) [‘hello’] print([if i%2==0: i; else: i+1; for i in
d) hello range(4)])

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.

Downloaded From: www.EasyEngineering.net 94


Downloaded From: www.EasyEngineering.net

10. Which of the following is the same as b) [x for x<0 in l]


list(map(lambda x: x**-1, [1, 2, 3]))? c) [x in l for x<0]
a) [x**-1 for x in [(1, 2, 3)]] d) [x for x in l if x<0]
b) [1/x for x in [(1, 2, 3)]]
c) [1/x for x in (1, 2, 3)] Answer: d
d) error Explanation: To pick out only the negative
numbers from a given list ‘l’, the correct list
Answer: c comprehension statement would be: [x for x
Explanation: x**-1 is evaluated as (x)**(-1). in l if x<0].

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]

a) [1, 1, 1, 1, 1] 4. What will be the output of the following

w.E
b) [1, 0, 1, 0, 1]
c) [1, 0, 0, 0, 0]
d) [0, 1, 0, 1, 0]
Python code?

s=["pune", "mumbai", "delhi"]


[(w.upper(), len(w)) for w in s]

Answer: b asy a) Error

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]

a) [4, 8, 12, 5, 10, 15, 6, 12, 18]


b) [4, 10, 18]
(‘DELHI’, 5)]. et
code is: [(‘PUNE’, 4), (‘MUMBAI’, 6),

5. What will be the output of the following


c) [4, 5, 6, 8, 10, 12, 12, 15, 18]
d) [18, 12, 6, 15, 10, 5, 12, 8, 4] Python code?

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)

3. Write the list comprehension to pick out 2, -2


only negative integers from a given list ‘l’.
4, -4
a) [x<0 in l]

Downloaded From: www.EasyEngineering.net 95


Downloaded From: www.EasyEngineering.net

a list of cube of the numbers for the given list


6, -6 is: [x**3 for x in l].
b) [(2, -2), (4, -4), (6, -6)] 8. What will be the output of the following
c) Python code?
(2, -2) l=[[1 ,2, 3], [4, 5, 6], [7, 8, 9]]
[[row[i] for row in l] for i in range(3)]
(4, -4)

(6, -6) a) Error


b) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
d) [-4, -16, -36] c)

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

belonging to the list l2. That is, l3=[10-10, import math


20-20, 30-20], which is, [0, 0, 0]. [str(round(math.pi)) for i in range (1, 6
)]
7. Write a list comprehension for number and
its cube for l=[1, 2, 3, 4, 5, 6, 7, 8, 9]. a) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
a) [x**3 for x in l] b) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’,
b) [x^3 for x in l] ‘3.141582’]
c) [x**3 in l] c) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
d) [x^3 in l] d) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’]

Answer: a Answer: c
Explanation: The list comprehension to print Explanation: The list comprehension shown

Downloaded From: www.EasyEngineering.net 96


Downloaded From: www.EasyEngineering.net

above rounds off pi(3.141) and returns its Answer: b


value, that is 3. This is done 5 times. Hence Explanation: The tuple ‘v’ is used to
the output is: [‘3’, ‘3’, ‘3’, ‘3’, ‘3’]. generate a list containing only vowels in the
string ‘w’. The result is a list containing only
10. What will be the output of the following vowels present in the string “hello”. Hence
Python code? the required list comprehension is: [x for x in
w if x in v].
l1=[1,2,3]
l2=[4,5,6]
2. What will be the output of the following
l3=[7,8,9]
for x, y, z in zip(l1, l2, l3): Python code?
print(x, y, z)
[ord(ch) for ch in 'abc']
a)
a) [97, 98, 99]

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)

(1 4 7) asy above returns the ASCII value of each


alphabet of the string ‘abc’. Hence the output

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

Explanation: The output of the code shown


above is:
a) [0]
b) 0 g.n
147
258
369
This is due to the statement: print(x, y,z).
c) [0.00]
d) Error

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

Downloaded From: www.EasyEngineering.net 97


Downloaded From: www.EasyEngineering.net

Answer: b c) [(2**x) for x in range(1, 13)]


Explanation: The list comprehension [x for x d) [(x**2) for x in range(0, 13)]
in range(1000) if x%3==0] produces a list of
numbers between 1 and 1000 that are Answer: a
divisible by 3. Explanation: The required list
comprehension will print the numbers from 1
5. Write a list comprehension equivalent for to 12, each raised to 2. The required answer is
the Python code shown below. thus, [(2**x) for x in range(0, 13)].

for i in range(1, 101): 8. What is the list comprehension equivalent


if int(i*0.5)==i*0.5: for?
print(i)
{x : x is a whole number less than 20, x
a) [i for i in range(1, 100) if int(i*0.5)== is even} (including zero)

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?

a) [1|x for x in [1, 2, 3]]


b) [-1**x for x in [1, 2, 3]] , 50, i)] g.n
[j for i in range(2,8) for j in range(i*2

c) [x**-1 for x in [1, 2, 3]]


d) [x^-1 for x in range(4)]

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

Downloaded From: www.EasyEngineering.net 98


Downloaded From: www.EasyEngineering.net

l=["good", "oh!", "excellent!", "#450"] error because in the absence of a comma at


[n for n in l if n.isalpha() or n.isdigit the end of each row, it behaves like three
()]
separate lists. The error thrown states that the
a) [‘good’, ‘oh’, ‘excellent’, ‘450’ ] list integers must be integers or slices, not
b) [‘good’] tuples.
c) [‘good’, ‘#450’]
d) [‘oh!’, ‘excellent!’, ‘#450’]

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


Explanation: The code shown above returns Python code?
a new list containing only strings which do A = [[1, 2, 3],
not have any punctuation in them. The only [4, 5, 6],
string from the list which does not contain [7, 8, 9]]

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]

A = [[1, 2, 3], asy Answer: a


Explanation: We can index the rows and
[4, 5, 6],
En columns using normal index operations. The
statement A[1] represents the second row,

b)
[7, 8, 9]]

gin that is, the middle row. Hence the output of


the code will be: [4, 5, 6].

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?

Answer: b A = [[1, 2, 3],


Explanation: In matrix B will result in an [4, 5, 6],

Downloaded From: www.EasyEngineering.net 99


Downloaded From: www.EasyEngineering.net

[7, 8, 9]] c) [[1, 2, 3], [4, 5, 6]]


[A[row][1] for row in (0, 1, 2)] d) [[11, 12, 13], [14, 15, 16]]
a) [7, 8, 9] Answer: d
b) [4, 5, 6] Explanation: We use range twice if the
c) [2, 5, 8] shapes differ. Each element of list l is
d) [1, 4, 7] increased by 10. Hence the output is: [[11, 12,
13], [14, 15, 16]]
Answer: c
Explanation: To get a particular column as 7. What will be the output of the following
output, we can simple iterate across the rows Python code?
and pull out the desired column, or iterate
through positions in rows and index as we go. A = [[1, 2, 3],
Hence the output of the code shown above is: [4, 5, 6],

ww
[2, 5, 8].

5. What will be the output of the following


[7, 8, 9]]

[[col + 10 for col in row] for row in A]

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

Downloaded From: www.EasyEngineering.net 100


Downloaded From: www.EasyEngineering.net

9. What will be the output of the following is: [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20,
Python code? 30, 40, 50, 60, 70, 80, 90].

A = [[1, 2, 3], 11. What will be the output of the following


[4, 5, 6], Python code?
[7, 8, 9]]
B = [[3, 3, 3],
A = [[1, 2, 3],
[4, 4, 4],
[4, 5, 6],
[5, 5, 5]]
[7, 8, 9]]
[B[row][col]*A[row][col] for row in range
B = [[3, 3, 3],
(3) for col in range(3)]
[4, 4, 4],
[5, 5, 5]]
a) [3, 6, 9, 16, 20, 24, 35, 40, 45] [[col1 * col2 for (col1, col2) in zip(row
b) Error 1, row2)] for (row1, row2) in zip(A, B)]
c) [0, 30, 60, 120, 160, 200, 300, 350, 400]

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?

r = [11, 12, 13, 14, 15, 16, 17, 18, 19]


A = [[0, 10, 20],
[30, 40, 50],
ee A = [[1, 2,
[4, 5,
[7, 8,
B = [[3, 3,
3],
6],
9]]
3],
rin
for row in A:
[60, 70, 80]]

for col in row:


[4, 4,
[5, 5,
zip(A, B)
4],
5]]
g.n
r
r.append(col+10)

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

Downloaded From: www.EasyEngineering.net 101


Downloaded From: www.EasyEngineering.net

a) (1, 2)
TOPIC 4.2 TUPLES (TUPLE
b) (1, 2, 4)
ASSIGNMENT, TUPLE AS c) (2, 4)
RETURN VALUE) d) (2, 4, 3)

1. Which of the following is a Python tuple? Answer: c


a) [1, 2, 3] Explanation: Slicing in tuples takes place
b) (1, 2, 3) just as it does in strings.
c) {1, 2, 3}
5. What will be the output of the following
d) {}
Python code?
Answer: b
1. >>>t = (1, 2, 4, 3, 8, 9)
Explanation: Tuples are represented with

ww
round brackets.

2. Suppose t = (1, 2, 4, 3), which of the


2. >>>[t[i] for i in range(0, len(t),
2)]

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?

4. What will be the output of the following 1. >>>t = (1, 2)


Python code?
2. >>>2 * t
1. >>>t=(1,2,4,3)
a) (1, 2, 1, 2)
2. >>>t[1:-1] b) [1, 2, 1, 2]

Downloaded From: www.EasyEngineering.net 102


Downloaded From: www.EasyEngineering.net

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]

1. >>>t1 = (1, 2, 4, 3) 8. print len(numberGames) + sum

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

Downloaded From: www.EasyEngineering.net 103


Downloaded From: www.EasyEngineering.net

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.

8. What type of data is: a=[(1,1),(2,4),(3,9)]?


Answer: c
En
Explanation: Here (“Check”) is a string not a a) Array of tuples
b) List of tuples
element.
gin
tuple because there is no comma after the
c) Tuples of lists
d) Invalid type

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?

Downloaded From: www.EasyEngineering.net 104


Downloaded From: www.EasyEngineering.net

>>> a=(1,2,3) Answer: b


>>> b=('A','B','C') Explanation: The loop runs two times and
>>> c=tuple(zip(a,b))
each time the loop runs an extra parenthesis
a) Yes, c will be ((1, ‘A’), (2, ‘B’), (3, ‘C’)) along with a comma is added to the tuple (as
b) Yes, c will be ((1,2,3),(‘A’,’B’,’C’)) a=(a’)).
c) No because tuples are immutable
d) No because the syntax for zip function
isn’t valid
3. Is the following Python code valid?
Answer: a >>> a,b=1,2,3
Explanation: Zip function combines
individual elements of two iterables into a) Yes, this is an example of tuple unpacking.
tuples. Execute in Python shell to verify. a=1 and b=2

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.

4. What will be the output of the following


parenthesis.

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

Downloaded From: www.EasyEngineering.net 105


Downloaded From: www.EasyEngineering.net

a) (6,7) 9. What will be the output of the following


b) Invalid syntax Python code?
c) (7,6)
d) Nothing is printed >>> a=(2,3,1,5)
>>> a.sort()
>>> a
Answer: c
Explanation: The above piece of code a) (1,2,3,5)
illustrates the unpacking of variables. b) (2,3,1,5)
c) None
6. What will be the output of the following
d) Error, tuple has no attribute sort
Python code?

>>> import collections


Answer: d
>>> a=collections.namedtuple('a',['i','j' Explanation: A tuple is immutable thus it

ww
])
>>>
>>>
obj=a(i=4,j=7)
obj
doesn’t have a sort attribute.

10. Is the following Python code valid?

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

8. Is the following Python code valid?

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

Downloaded From: www.EasyEngineering.net 106


Downloaded From: www.EasyEngineering.net

1. Which of the following statements create a a) True


dictionary? b) False
a) d = {} c) None
b) d = {“john”:40, “peter”:45} d) Error
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned Answer: b
Explanation: If d2 was initialized as d2 = d1
Answer: d the answer would be true.
Explanation: Dictionaries are created by
specifying keys and values. 5. What will be the output of the following
Python code snippet?
2. What will be the output of the following
Python code snippet? 1. d1 = {"john":40, "peter":45}

ww 1. d = {"john":40, "peter":45}

a) “john”, 40, 45, and “peter”


2. d2 = {"john":466, "peter":45}
3. d1 > d2

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

of keys and values. En


Explanation: Dictionaries appear in the form Answer: c
Explanation: Arithmetic > operator cannot

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)

Downloaded From: www.EasyEngineering.net 107


Downloaded From: www.EasyEngineering.net

Answer: c b) The keys of a dictionary can be accessed


Explanation: Execute in the shell to verify. using values
c) Dictionaries aren’t ordered
8. Suppose d = {“john”:40, “peter”:45}. To d) Dictionaries are mutable
obtain the number of entries in dictionary
which command do we use? Answer: b
a) d.size() Explanation: The values of a dictionary can
b) len(d) be accessed using keys but the keys of a
c) size(d) dictionary can’t be accessed using values.
d) d.len()
2. Which of the following is not a declaration
Answer: b of the dictionary?
Explanation: Execute in the shell to verify. a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])

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

a) [“john”, “peter”] asy dictionary.

3. What will be the output of the following


b) [“john”:40, “peter”:45]
c) (“john”, “peter”)
En Python code snippet?
d) (“john”:40, “peter”:45)

Answer: a gin a={1:"A",2:"B",3:"C"}


for i,j in a.items():
print(i,j,end=" ")

dictionary d, in the form of a list.


ee
Explanation: The output of the code shown
above is a list containing only keys of the a) 1 A 2 B 3 C
b) 1 2 3
c) A B C rin
10. Suppose d = {“john”:40, “peter”:45},
what happens when we try to retrieve a value
d) 1:”A” 2:”B” 3:”C”
g.n
using the expression d[“susan”]?
a) Since “susan” is not a value in the set,
Python raises a KeyError exception
b) It is executed fine and no exception is
Answer: a
et
Explanation: In the above code, variables i
and j iterate over the keys and values of the
dictionary respectively.
raised, and it returns None
c) Since “susan” is not a key in the set, 4. What will be the output of the following
Python raises a KeyError exception Python code snippet?
d) Since “susan” is not a key in the set, a={1:"A",2:"B",3:"C"}
Python raises a syntax error print(a.get(1,4))

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

Downloaded From: www.EasyEngineering.net 108


Downloaded From: www.EasyEngineering.net

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)

a) {1: ‘A’, 2: ‘B’, 3: ‘C’}

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?

a={1:"A",2:"B",3:"C"} gin Execute in python shell to verify.

print(a.setdefault(3))

a) {1: ‘A’, 2: ‘B’, 3: ‘C’}


b) C
ee 9. What will be the output of the following
Python code?

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

Downloaded From: www.EasyEngineering.net 109


Downloaded From: www.EasyEngineering.net

a={1:"A",2:"B",3:"C"} c) Too many arguments for pop() method


a.clear() d) 4
print(a)
Answer: a
a) None
Explanation: pop() method returns the value
b) { None:None, None:None, None:None}
when the key is passed as an argument and
c) {1:None, 2:None, 3:None}
otherwise returns the default value(second
d) { }
argument) if the key isn’t present in the
Answer: d dictionary.
Explanation: The clear() method clears all
14. What will be the output of the following
the key-value pairs in the dictionary.
Python code?
11. Which of the following isn’t true about a={1:"A",2:"B",3:"C"}

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: c asy d) Error, it should be: for i in a.items():

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

Python code? gin


12. What will be the output of the following printed.

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

a) Syntax error g.n


c) Error, syntax error for pop() method
d) {1: 5, 3: 4} c) dict_items([(1,2,3)]) et
b) dict_items([(‘A’), (‘B’), (‘C’)])

d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])


Answer: b
Explanation: pop() method removes the key- Answer: d
value pair for the key mentioned in the pop() Explanation: The method items() returns list
method. of tuples with each tuple having a key-value
pair.
13. What will be the output of the following
Python code? 1. Which of the statements about dictionary
values if false?
a={1:5,2:3,3:4} a) More than one key can have the same
print(a.pop(4,9))
value
a) 9 b) The values of the dictionary can be
b) 3 accessed as dict[key]

Downloaded From: www.EasyEngineering.net 110


Downloaded From: www.EasyEngineering.net

c) Values of a dictionary must be unique a) 3


d) Values of a dictionary can be a mixture of b) 1
letters and numbers c) 2
d) 0
Answer: c
Explanation: More than one key can have the Answer: c
same value. Explanation: The insert() function counts the
number of occurrences of the item being
2. What will be the output of the following inserted into the dictionary. There are only 2
Python code snippet? keys present since the key ‘Apple’ is
repeated. Thus, the length of the dictionary is
>>> a={1:"A",2:"B",3:"C"} 2.
>>> del a
5. What will be the output of the following

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)

pairs, what does a.popitem() do?


a) Removes an arbitrary element gin a) 1
b) 2
c) 4
b) Removes all the key-value pairs

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.

4. What will be the output of the following


et
6. What will be the output of the following
Python code snippet?

Python code snippet? numbers = {}


letters = {}
total={} comb = {}
def insert(items): numbers[1] = 56
if items in total: numbers[3] = 7
total[items] += 1 letters[4] = 'B'
else: comb['Numbers'] = numbers
total[items] = 1 comb['Letters'] = letters
insert('Apple') print(comb)
insert('Ball')
insert('Apple') a) Error, dictionary in a dictionary can’t exist
print (len(total)) b) ‘Numbers’: {1: 56, 3: 7}
c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}}

Downloaded From: www.EasyEngineering.net 111


Downloaded From: www.EasyEngineering.net

d) {‘Numbers’: {1: 56, 3: 7}, ‘Letters’: {4: count = 0


‘B’}} for i in a:
count += a[i]
print(count)
Answer: d
Explanation: Dictionary in a dictionary can a) An exception is thrown
exist. b) 3
c) 6
7. What will be the output of the following d) 2
Python code snippet?
Answer: c
test = {1:'A', 2:'B', 3:'C'}
test = {} Explanation: The value of key 1 is 4 since 1
print(len(test)) and 1.0 are the same. Then, the function
count() gives the sum of all the values of the

ww
a) 0
b) None
c) 3
keys (2+4).

10. What will be the output of the following

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

Downloaded From: www.EasyEngineering.net 112


Downloaded From: www.EasyEngineering.net

count of times the number appears as the Answer: a


value. Explanation: a|b returns the pair of keys and
the highest recurring value.
12. What will be the output of the following
Python code snippet? 15. What will be the output of the following
Python code snippet?
>>>import collections
>>> b=collections.Counter([2,2,3,4,4,4]) >>> import collections
>>> b.most_common(1) >>> a=collections.Counter([3,3,4,5])
>>> b=collections.Counter([3,4,4,5,5,5])
a) Counter({4: 3, 2: 2, 3: 1}) >>> a&b
b) {3:1}
c) {4:3} a) Counter({3: 12, 4: 1, 5: 1})
d) [(4, 3)] b) Counter({3: 1, 4: 1, 5: 1})

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.

Python code snippet? asy


13. What will be the output of the following
1. The following Python code is invalid.

>>>import collections
En
>>> b=collections.Counter([2,2,3,4,4,4])
class demo(dict):
def __test__(self,key):
>>> b.most_common(1)

a) Counter({4: 3, 2: 2, 3: 1}) gin return []


a = demo()
a['test'] = 7
b) {3:1}
c) {4:3}
d) [(4, 3)]
ee print(a)

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.

14. What will be the output of the following


{‘test’:7}.
et
2. What will be the output of the following
Python code?
Python code snippet?
count={}
>>> import collections count[(1,2,4)] = 5
>>> a=collections.Counter([2,2,3,3,3,4]) count[(4,2,1)] = 7
>>> b=collections.Counter([2,2,3,4,4]) count[(1,2)] = 6
>>> a|b count[(4,2,1)] = 2
tot = 0
a) Counter({3: 3, 2: 2, 4: 2}) for i in count:
b) Counter({2: 2, 3: 1, 4: 1}) tot=tot+count[i]
c) Counter({3: 2}) print(len(count)+tot)
d) Counter({4: 1})
a) 25
b) 17

Downloaded From: www.EasyEngineering.net 113


Downloaded From: www.EasyEngineering.net

c) 16 c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}


d) Tuples can’t be made keys of a dictionary d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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.

7. What will be the output of the following

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}

Downloaded From: www.EasyEngineering.net 114


Downloaded From: www.EasyEngineering.net

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?

>>> a={"a":1,"b":2,"c":3} >>> import collections


>>> b=dict(zip(a.values(),a.keys())) >>> a=dict()
>>> b >>> a=collections.defaultdict(int)
>>> a[1]
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown a) 1

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)

Explanation: Dictionary comprehension and


string concatenation is implemented in the
above piece of code.
is empty
b) ‘ ‘
c) ‘A’
et
a) An exception is thrown since the dictionary

11. What will be the output of the following d) 0


Python code?
Answer: b
>>> a=dict() Explanation: The statement
>>> a[1] a=collections.defaultdict(str) gives the default
value of ‘ ‘ even if the keys don’t exist in the
a) An exception is thrown since the dictionary dictionary.
is empty
b) ‘ ‘ 14. What will be the output of the following
c) 1 Python code?
d) 0

Downloaded From: www.EasyEngineering.net 115


Downloaded From: www.EasyEngineering.net

>>> import collections a) infile = open(“c:\scores.txt”, “r”)


>>> b=dict() b) infile = open(“c:\scores.txt”, “r”)
>>> b=collections.defaultdict(lambda: 7)
>>> b[4]
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\scores.txt”, “r”)
a) 4
b) 0 Answer: b
c) An exception is thrown Explanation: Execute help(open) to get more
d) 7 details.

Answer: d 2. To open a file c:\scores.txt for writing, we


Explanation: The statement use ____________
a=collections.defaultdict(lambda: x) gives the a) outfile = open(“c:\scores.txt”, “w”)
default value of x even if the keys don’t exist b) outfile = open(“c:\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)

ww
in the dictionary.

15. What will be the output of the following


d) outfile = open(file = “c:\scores.txt”, “w”)

w.E
Python code?

>>> import collections


Answer: b
Explanation: w is used to indicate that file is
to be written to.
>>>
for
>>>
x in range(3))
a asy
a=collections.OrderedDict((str(x),x)
3. To open a file c:\scores.txt for appending
data, we use ____________
a) {‘2’:2, ‘0’:0, ‘1’:1}
En a) outfile = open(“c:\scores.txt”, “a”)
b) outfile = open(“c:\scores.txt”, “rw”)
c) An exception is thrown
d) ‘ ‘ gin
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)]) c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\scores.txt”, “w”)

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

TOPIC 5.1 TEXT FILES, Answer: d


READING AND WRITING Explanation: The program will throw an
FILES, FORMAT OPERATOR error.

5. To read two characters from a file object


1. To open a file c:\scores.txt for reading, we infile, we use ____________
use _____________

Downloaded From: www.EasyEngineering.net 116


Downloaded From: www.EasyEngineering.net

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.

10. The readlines() method returns


w.E
Answer: b
Explanation: read function is used to read all
the lines in a file.
____________
a) str

Python code? asy


7. What will be the output of the following
b) a list of lines
c) a list of single characters
d) a list of integers

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

Downloaded From: www.EasyEngineering.net 117


Downloaded From: www.EasyEngineering.net

a) Enter your input: [x*5 for x in range(2,1


0,2)]
Enter your input: Hello Python
Received input is : [10, 10, 30, 40]
Received input is : Hello Python
d) None of the mentioned
b)
Answer: a
Enter your input: Hello Python Explanation: None.
Received input is : Hello 4. Which one of the following is not attributes
of file?
c) a) closed
Enter your input: Hello Python b) softspace

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

1. str = input("Enter your input: ");


file.name Returns name of the file.

rin
file.softspace Returns false if space ex
plicitly required with print, true otherw

2. print "Received input is : ", str


ise.
g.n
5. What is the use of tell() method in python?
a)

Enter your input: [x*5 for x in range(2,1


0,2)]
et
a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned
Received input is : [x*5 for x in range
(2,10,2)] Answer: a
Explanation: The tell() method tells you the
b) current position within the file; in other
words, the next read or write will occur at that
Enter your input: [x*5 for x in range(2,1
many bytes from the beginning of the file.
0,2)]

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)

Downloaded From: www.EasyEngineering.net 118


Downloaded From: www.EasyEngineering.net

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

Line No 0 - This is 1st line

En
8. What will be the output of the following
Python code?

1. fo = open("foo.txt", "rw+") gin Line No 1 - This is 2nd line

2. print "Name of the file: ", fo.name


3.
ee rin
Line No 2 - This is 3rd line

4. # Assuming file has following 5 lin


es
g.n
Line No 3 - This is 4th line

5. # This is 1st line


6. # This is 2nd line Line No 4 - This is 5th line
et
7. # This is 3rd line 9. What is the use of seek() method in files?
a) sets the file’s current position at the offset
8. # This is 4th line b) sets the file’s previous position at the offset
9. # This is 5th line c) sets the file’s current position within the
file
10. d) none of the mentioned

11. for index in range(5): Answer: a


Explanation: Sets the file’s current position
12. line = fo.next() at the offset. The method seek() sets the file’s
13. print "Line No %d - %s" % (index
current position at the offset.
, line)

Downloaded From: www.EasyEngineering.net 119


Downloaded From: www.EasyEngineering.net

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)

Parameters 1. import sys


offset — This is the position of the read/write
pointer within the file. 2. print 'Enter your name: ',
3. name = ''
whence — This is optional and defaults to 0
which means absolute file positioning, other 4. while True:
values are 1 which means seek relative to the
current position and 2 means seek relative to 5. c = sys.stdin.read(1)
the file’s end.
6. if c == '\n':
10. What is the use of truncate() method in

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.

Enter your name: sanfoundry


Your name is: sanfoundry
Answer: d
Explanation: Standard input, standard output 3. What will be the output of the following
and standard error. Standard input is the data Python code?
that goes to the program. The standard input
comes from a keyboard. Standard output is 1. import sys
where we print our data with the print 2. sys.stdout.write(' Hello\n')
keyword. Unless redirected, it is the terminal
console. The standard error is a stream where 3. sys.stdout.write('Python\n')
programs write their error messages. It is
usually the text terminal. a) Compilation Error
b) Runtime Error

Downloaded From: www.EasyEngineering.net 120


Downloaded From: www.EasyEngineering.net

c) Hello Python 6. What is unpickling?


d) a) It is used for object serialization
b) It is used for object deserialization
Hello c) None of the mentioned
d) All of the mentioned
Python

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.

7. What is the correct syntax of open()


d) b

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]

b) It is used for object deserialization


c) None of the mentioned
d) All of the mentioned
Here is parameters’ detail:
et
file_name: The file_name argument is a string
value that contains the name of the file that
you want to access.
Answer: a access_mode: The access_mode determines
Explanation: Pickle is the standard the mode in which the file has to be opened,
mechanism for object serialization. Pickle i.e., read, write, append, etc. A complete list
uses a simple stack-based virtual machine that of possible values is given below in the table.
records the instructions used to reconstruct This is optional parameter and the default file
the object. This makes pickle vulnerable to access mode is read (r).
security risks by malformed or maliciously buffering: If the buffering value is set to 0, no
constructed data, that may cause the buffering will take place. If the buffering
deserializer to import arbitrary modules and value is 1, line buffering will be performed
instantiate any object. while accessing a file. If you specify the
buffering value as an integer greater than 1,
then buffering action will be performed with

Downloaded From: www.EasyEngineering.net 121


Downloaded From: www.EasyEngineering.net

the indicated buffer size. If negative, the Answer: a


buffer size is the system default(default Explanation: The method readlines() reads
behavior). until EOF using readline() and returns a list
containing the lines. If the optional sizehint
8. What will be the output of the following argument is present, instead of reading up to
Python code? EOF, whole lines totalling approximately
sizehint bytes (possibly after rounding up to
1. fo = open("foo.txt", "wb") an internal buffer size) are read.
Syntax

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

gin Explanation: r- reading, a-appending.


LO

9. Correct syntax of file.writelines() is?


a) file.writelines(sequence)
b) fileObject.writelines()
ee 2. What is the use of “w” in file handling?
a) Read

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

Downloaded From: www.EasyEngineering.net 122


Downloaded From: www.EasyEngineering.net

the end of the file. Answer: a


fh =open(“filename_here”, “a”). Explanation: With the writeline function you
can write a list of strings to a file
4. Which function is used to read all the fh = open(“hello.txt”, “w”)
characters? lines_of_text = [“a line of text”, “another line
a) Read() of text”, “a third line”]
b) Readcharacters() fh.writelines(lines_of_text).
c) Readall()
d) Readchar() 8. Which function is used to close a file in
python?
Answer: a a) Close()
Explanation: The read function reads all b) Stop()
characters fh = open(“filename”, “r”) c) End()
content = fh.read(). d) Closefile()
ww
5. Which function is used to read single line Answer: a

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

Downloaded From: www.EasyEngineering.net 123


Downloaded From: www.EasyEngineering.net

format. Overwrites the file if the file exists. If object.


the file does not exist, creates a new file for
writing. 4. Which of the following is not a valid
“w+” Opens a file for both writing and attribute of a file object (fp)?
reading. Overwrites the existing file if the file a) fp.name
exists. If the file does not exist, creates a new b) fp.closed
file for reading and writing. c) fp.mode
“wb+” Opens a file for both writing and d) fp.size
reading in binary format. Overwrites the
existing file if the file exists. If the file does Answer: d
not exist, creates a new file for reading and Explanation: fp.size has not been
writing. implemented.

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

Downloaded From: www.EasyEngineering.net 124


Downloaded From: www.EasyEngineering.net

Answer: c class foo:


Explanation: os.remove() is used to delete def __init__(self, x):
self.x = x
files. def __lt__(self, other):
if self.x < other.x:
9. How do you change the file position to an return False
offset value from the start? else:
a) fp.seek(offset, 0) return True
b) fp.seek(offset, 1)
c) fp.seek(offset, 2) b)
d) none of the mentioned class foo:
def __init__(self, x):
Answer: a self.x = x
Explanation: 0 indicates that the offset is def __less__(self, other):
with respect to the start. if self.x > other.x:

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

def __less__(self, other):


b) __format__()
c) str()
d) __str__()
if self.x < other.x:
return False
else:
return True
et
Answer: d Answer: c
Explanation: Both str(f) and format(f) call Explanation: __lt__ overloads the <
f.__str__(). operator>.

2. Which of the following Python code will


print True?
3. Which function overloads the + operator?
a = foo(2) a) __add__()
b = foo(3) b) __plus__()
print(a < b)
c) __sum__()
a) d) none of the mentioned

Downloaded From: www.EasyEngineering.net 125


Downloaded From: www.EasyEngineering.net

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

5. Which function overloads the == operator? Answer: b

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

d) none of the mentioned

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

Downloaded From: www.EasyEngineering.net 126


Downloaded From: www.EasyEngineering.net

Answer: c 6. When is the finally block executed?


Explanation: The else part is executed when a) when there is no exception
no exception occurs. b) when there is an exception
c) only if some condition that has been
3. Is the following Python code valid? specified is satisfied
d) always
try:
# Do something
Answer: d
except:
# Do something Explanation: The finally block is always
finally: executed.
# Do something
7. What will be the output of the following
a) no, there is no such thing as finally Python code?
b) no, finally cannot be used with except

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

a) no, there is no such thing as else


b) no, else cannot be used with except
ee Answer: b

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.

5. Can one block of except statements handle


Python code?

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

Downloaded From: www.EasyEngineering.net 127


Downloaded From: www.EasyEngineering.net

so 1 is printed. Then the finally block is AssertionError: Spanish


executed and 2 is printed. Hence, this statement is true.

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.

3. What will be the output of the following


such inheritance here.
En Python code?

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’

Downloaded From: www.EasyEngineering.net 128


Downloaded From: www.EasyEngineering.net

a) Error This is because we have used next(g) twice.


b) test Had we not used next, there would be no
c) output.

test 6. What will be the output of the following


Python code?
10
def a():
12
try:
f(x, 4)
d) No output finally:
print('after f')
Answer: d print('after f?')
Explanation: The code shown above will not a()
yield any output. This is because when we try

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)

Downloaded From: www.EasyEngineering.net 129


Downloaded From: www.EasyEngineering.net

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.

9. Which of the following is not an exception


input file in not found, then the statement:
“Input file not found” is printed on the screen.

w.E
handling keyword in Python?
a) try
b) except
The user is then prompted to reenter the file
name. Error is not thrown.

2. What will be the output of the following


c) accept
d) finally asy Python code?

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

Downloaded From: www.EasyEngineering.net 130


Downloaded From: www.EasyEngineering.net

results in a name error. This is because the ctorial you want to find"))
name ‘t’ is not defined. print(math.factorial(num))

4. What will be the output of the following a) ValueError, NameError


Python code, if the time module has already b) AttributeError, ValueError
been imported? c) NameError, TypeError
d) TypeError, ValueError
4 + '3'
Answer: a
a) NameError Explanation: The first code results in a
b) IndexError ValueError. This is because when we enter the
c) ValueError input as -6, we are trying to find the factorial
d) TypeError of a negative number, which is not possible.
The second code results in a NameError. This

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

Downloaded From: www.EasyEngineering.net 131


Downloaded From: www.EasyEngineering.net

a) Bye (printed once) syntax error is thrown. The only true


b) No output statement above is: The standard exceptions
c) Invalid (printed once) are automatically imported into Python
d) Bye (printed infinite number of times) programs.

Answer: d 11. Which of the following is not a standard


Explanation: The code shown above results exception in Python?
in the word “Bye” being printed infinite a) NameError
number of times. This is because an even b) IOError
number has been given as input. If an odd c) AssignmentError
number had been given as input, then there d) ValueError
would have been no output.
Answer: c
9. Identify the type of error in the following Explanation: NameError, IOError and

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.

12. Syntax errors are also known as parsing


b) Semantic, Syntax
c) Semantic, Semantic asy errors.
a) True
b) False
d) Syntax, Semantic
En Answer: a
Answer: b
gin
Explanation: The first code shows an error
detected during execution. This might occur
Explanation: Syntax errors are known as
parsing errors. Syntax errors are raised when
occasionally. The second line of code
represents a syntax error. When there isee
deviation from the rules of a language, a
there is a deviation from the rules of a
language. Hence the statement is true.

rin
13. An exception is ____________
syntax error is thrown.

10. Which of the following statements is true?


a) an object
b) a special function
c) a standard module
g.n
a) The standard exceptions are automatically
imported into Python programs
b) All raised standard exceptions must be
handled in Python
d) a module

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

Downloaded From: www.EasyEngineering.net 132


Downloaded From: www.EasyEngineering.net

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.

TOPIC 5.3 MODULES AND


PACKAGES asy 4. ______ is a string literal denoted by triple
quotes for providing the specifications of
certain program elements.

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

b) Design and implementation of specific


functionality to be incorporated into a
program
ee
specification of certain program elements
Answer: d

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

Downloaded From: www.EasyEngineering.net 133


Downloaded From: www.EasyEngineering.net

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.

a top-down design process.


asy
8. What will be the output of the following
10. Which of the following is not a valid
namespace?
a) Global namespace
Python code?
En b) Public namespace
c) Built-in namespace
#mod1
def change(a):
b=[x*2 for x in a] gin d) Local namespace

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.

11. Which of the following is false about


#main
s=[1,2,3]
change(s) et
“import modulename” form of import?
a) The namespace of imported module
becomes part of importing module
a) [2,4,6] b) This form of import prevents name clash
b) [1,4,9] c) The namespace of imported module
c) becomes available to importing module
d) The identifiers in module are accessed as:
[2,4,6]
modulename.identifier
[1,4,9]
Answer: a
d) There is a name clash Explanation: In the “import modulename”
form of import, the namespace of imported
Answer: d module becomes available to, but not part of,
Explanation: A name clash is when two the importing module.
different entities with the same identifier

Downloaded From: www.EasyEngineering.net 134


Downloaded From: www.EasyEngineering.net

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.

15. What is the order of namespaces in which

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

private or public are imported gin


identifiers regardless of whether they are c) Python first searches the built-in
namespace, then the global namespace and
finally the local namespace
d) When a module is loaded, a compiled

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.

14. What will be the output of the following


namespace. et
local, then the global and finally the built-in

Python code?

Downloaded From: www.EasyEngineering.net 135


Downloaded From: www.EasyEngineering.net

ww
w.E
a syE
ngi
nee
rin
g.n
et

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials, Students & Graduates if You Find the Same Materials with
EasyEngineering.net Watermarks or Logo, Kindly report us to
easyengineeringnet@gmail.com
Downloaded From: www.EasyEngineering.net

You might also like