You are on page 1of 135

First Semester MCQ for Regulations 2017

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

M
word algorithm refers to a special method
usable by a computer for the solution to a
problem. The statement of the problem

O
SEMESTER - I specifies in general terms the desired
input/output relationship.

C
3. This characteristic often draws the line

T.
MCQ - Regulations between what is feasible and what is
impossible.
2017

O
a) Performance
b) System Evaluation

Department of CSE SPc) Modularity


d) Reliability
G
Answer: a
Explanation: Algorithms help us to
LO

understand scalability. Performance often


draws the line between what is feasible and
UNIT I ALGORITHMIC what is impossible.
PROBLEM SOLVING
.B

4. The time that depends on the input: an


already sorted sequence that is easier to sort.
TOPIC 1.1 ALGORITHMS a) Process
17

b) Evaluation
1. The word ____________comes from the c) Running
name of a Persian mathematician Abu Ja’far d) Input
-R

Mohammed ibn-i Musa al Khowarizmi.


Answer: c
a) Flowchart
Explanation: The running time depends on
SE

b) Flow
the input: an already sorted sequence is easier
c) Algorithm
to sort. The running time is given by the size
d) Syntax
of the input, since short sequences are easier
C

Answer: c to sort than the longer ones. Generally, we


Explanation: The word algorithm comes seek upper bounds on the running time,
from the name of a Persian mathematician because it is reliable.
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: https://cse-r17.blogspot.com 1


First Semester MCQ for Regulations 2017

c) as programs b) Lists
d) as flowcharts c) Horizontal array
d) Vertical array
Answer: b
Explanation: Representation of algorithms: Answer: a
-As programs Explanation: Linear arrays are the 1-
-As flowcharts Dimensional arrays wherein only one row is
-As pseudo codes. present and the items are inserted.

M
6. When an algorithm is written in the form of 10. A data structure that follows the FIFO
a programming language, it becomes a principle.

O
_________ a) Queue
a) Flowchart b) LL

C
b) Program c) Stack
c) Pseudo code d) Union

T.
d) Syntax
Answer: a
Answer: b Explanation: The answer is Queue. A Queue

O
Explanation: An algorithm becomes a follows the FIFO principle. FIFO stands for
program when it is written in the form of a First In First Out.
programming language. Thus, any program is
an algorithm.
SP
TOPIC 1.2 FLOW CHARTS
G
7. Any algorithm is a program.
a) True 1. The symbol denotes _______
LO

b) False

Answer: b
a) I/O
Explanation: The statement is false. An
.B

b) Flow
algorithm is represented in the form of a
c) Terminal
programming language is called a program.
d) Decision
17

Any program is an algorithm but the reverse


is not true. Answer: c
Explanation: The symbol denotes a terminal.
8. A system wherein items are added from
-R

It is used for indication of start and stop


one and removed from the other end.
nodes of a program.
a) Stack
SE

b) Queue 2. In computer science, algorithm refers to a


c) Linked List pictorial representation of a flowchart.
d) Array a) True
b) False
C

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: https://cse-r17.blogspot.com 2


First Semester MCQ for Regulations 2017

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.

M
flowchart is nothing but a pictorial a) True
representation of an algorithm. b) False

O
4. Actual instructions in flowcharting are Answer: b

C
represented in __________ Explanation: The statement is false. There
a) Circles should be no set standards on the amount of

T.
b) Boxes details that should be provided in a flowchart.
c) Arrows
d) Lines 8. A detailed flowchart is called ______

O
a) Stack
Answer: b b) Macro
Explanation: The actual instructions are
written in boxes. Boxes are connected by
using arrows to indicate the exact flow of a
SP
c) Micro
d) Union
G
flowchart and the order in which they are to Answer: c
be executed. Explanation: A detailed flowchart or a
LO

flowchart with more details is called as micro


5. The following box denotes? flowchart. It represents all the components of
the algorithm that is followed.
.B

9. Which of the following is not an advantage


of a flowchart?
a) Decision
17

a) Better communication
b) Initiation b) Efficient coding
c) Initialization c) Systematic testing
d) I/O d) Improper documentation
-R

Answer: a Answer: d
Explanation: A diamond shape box denotes
SE

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

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: https://cse-r17.blogspot.com 3


First Semester MCQ for Regulations 2017

Answer: b a) Process
Explanation: The answer is Macro b) Sequence
Flowchart. A macro flowchart outlines the c) Repetition
important components of a program. It d) Case
therefore shows fewer details.
Answer: a
Explanation: There are basically four
TOPIC 1.3 DESIGNING flowcharting structures:
FLOWCHARTS • Decision

M
• Repetition
1. A ______________ is diagram that depicts • Case

O
the flow of a program. • Sequence.
a) Algorithm

C
b) Hash Table 5. The action performed by a ___________
c) Graph structure must eventually cause the loop to

T.
d) Flowchart terminate.
a) sequence
b) case

O
Answer: d
Explanation: A flowchart is a diagram that c) repetition
d) process
helps us determine the flow of the program.
Other options are irrelevant.

2. Terminals are represented by diagonals in a


SP
Answer: c
Explanation: The action performed by a
G
flowchart. repetition structure must eventually cause the
a) True loop to terminate. Otherwise, an infinite loop
LO

b) False is created.

Answer: b 6. The following symbol denotes:


.B

Explanation: The statement is false.


Terminals are represented by rounded
rectangles. They indicate the starting or
17

ending point in a flowchart. a) Module


b) Terminal
3. The operation represented by c) Process
d) i/o operation
-R

parallelograms.
a) Input/Output
b) Assignment Answer: a
SE

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

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 4


First Semester MCQ for Regulations 2017

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

10. The following box denotes?

a) sequence

M
b) case a) Decision
c) repetition b) Input/Output
c) Process

O
d) process
d) Module

C
Answer: c
Explanation: This is a repetition structure. Answer: a
Explanation: The answer is decision.

T.
The action performed by a repetition structure
must eventually cause the loop to terminate. Conditions are given in this box and then the
Otherwise, an infinite loop is created. result is checked accordingly if the condition

O
is true or false.
8. What type of a structure is this?

SP
TOPIC 1.4 PSEUDO CODE

1. Keep the statement language


G
______________ while writing a pseudo
code.
LO

a) Dependent
b) Independent
a) sequence c) Case sensitive
.B

b) case d) Capitalized
c) repetition
d) process Answer: b
17

Explanation: The statement’s language


Answer: b should be independent. Other rules are to
Explanation: This is a case structure. Certain write only one statement per line and end
-R

cases are given along with a default case in multiline structures.


the case structure.
2. Capitalize initial keyword – This is a rule
SE

9. A _______ is a connector showing the while writing a pseudo code.


relationship between the representative a) True
shapes. b) False
a) line
C

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: https://cse-r17.blogspot.com 5


First Semester MCQ for Regulations 2017

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

M
4. ______________ is used to show hierarchy c) Tokens
in a pseudo code. d) Functions

O
a) Indentation
b) Curly Braces Answer: b

C
c) Round Brackets Explanation: Variables begin with a
d) Semicolon lowercase. They contain no spaces. They also

T.
involve the consistent use of names.
Answer: a
Explanation: Each design structure uses a 8. Another notation for exponentiation.

O
particular indentation pattern. a) *
Indentation should be considered in the b) **
following cases:
Sequence
Selection
SP
c) ***
d) *^
G
Loop. Answer: b
Explanation: Double asterisk sign is also
LO

5. The statement that tells the computer to get used for exponentiation. The general notation
a value from an input device and store it in a is ^ sign.
memory location.
a) read 9. A symbol used for grouping.
.B

b) write a) ()
c) READ b) {}
17

d) WRITE c) [].
d) ” ”
Answer: c
Explanation: The READ statement is used to Answer: a
-R

take the input. READ being a keyword should Explanation: Parenthesis is used for
be in capital letters. grouping while working with fields. There are
SE

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
C

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: https://cse-r17.blogspot.com 6


First Semester MCQ for Regulations 2017

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

M
STATEMENTS with an underscore discouraged?
a) they are used to indicate a private variables

O
of a class
TOPIC 2.1 VARIABLES b) they confuse the interpreter

C
c) they are used to indicate global variables
1. Is Python case sensitive when dealing with d) they slow down execution

T.
identifiers?
a) yes Answer: a
Explanation: As Python has no concept of

O
b) no
c) machine dependent private variables, leading underscores are
used to indicate variables that must not be
d) none of the mentioned

Answer: a
SP
accessed from outside the class.

6. Which of the following is not a keyword?


Explanation: Case is always significant.
G
a) eval
2. What is the maximum possible length of an b) assert
LO

identifier? c) nonlocal
a) 31 characters d) pass
b) 63 characters
Answer: a
.B

c) 79 characters
d) none of the mentioned Explanation: eval can be used as a variable.
17

Answer: d 7. All keywords in Python are in _________


Explanation: Identifiers can be of any length. a) lower case
b) UPPER CASE
c) Capitalized
-R

3. Which of the following is invalid?


a) _a = 1 d) None of the mentioned
b) __a = 1
Answer: d
SE

c) __str__ = 1
d) none of the mentioned Explanation: True, False and None are
capitalized while the others are in lower case.
Answer: d
C

Explanation: All the statements will execute 8. Which of the following is true for variable
successfully but at the cost of reduced names in Python?
readability. a) unlimited length
b) all private members must have leading and
4. Which of the following is an invalid trailing underscores
variable? c) underscore and ampersand are the only two
a) my_string_1

Downloaded From: https://cse-r17.blogspot.com 7


First Semester MCQ for Regulations 2017

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.

M
a) abc = 1,000,000
b) a b c = 1000 2000 3000 3. What is the order of precedence in python?

O
c) a,b,c = 1000, 2000, 3000 i) Parentheses
d) a_b_c = 1,000,000 ii) Exponential

C
iii) Multiplication
Answer: b iv) Division

T.
Explanation: Spaces are not allowed in v) Addition
variable names. vi) Subtraction

O
a) i,ii,iii,iv,v,vi
10. Which of the following cannot be a b) ii,i,iii,iv,v,vi
variable?
a) __init__
b) in
c) it
SP c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v

Answer: a
G
d) on Explanation: For order of precedence, just
remember this PEMDAS (similar to
LO

Answer: b BODMAS).
Explanation: in is a keyword.
4. What is the answer to this expression, 22 %
.B

TOPIC 2.2 OPERATORS 3 is?


a) 7
b) 1
17

1. Which is the correct operator for c) 0


power(xy)? d) 5
a) X^y
-R

b) X**y Answer: b
c) X^^y Explanation: Modulus operator gives the
d) None of the mentioned remainder. So, 22%3 gives the remainder, that
SE

is, 1.
Answer: b
Explanation: In python, power operator is 5. Mathematical operations can be performed
x**y i.e. 2**3=8. on a string.
C

a) True
2. Which one of these is floor division? b) False
a) /
b) // Answer: b
c) % Explanation: You can’t perform
d) None of the mentioned mathematical operation on string even if the
string is in the form: ‘1234…’.

Downloaded From: https://cse-r17.blogspot.com 8


First Semester MCQ for Regulations 2017

6. Operators with the same precedence are 10. Which one of the following has the
evaluated in which manner? highest precedence in the expression?
a) Left to Right a) Exponential
b) Right to Left b) Addition
c) Can’t say c) Multiplication
d) None of the mentioned d) Parentheses

Answer: a Answer: d
Explanation: None. Explanation: Just remember: PEMDAS, that

M
is, Parenthesis, Exponentiation, Division,
7. What is the output of this expression, Multiplication, Addition, Subtraction. Note

O
3*1**3? that the precedence order of Division and
a) 27 Multiplication is the same. Likewise, the

C
b) 9 order of Addition and Subtraction is also the
c) 3 same.

T.
d) 1

Answer: c TOPIC 2.3 DATA TYPES

O
Explanation: First this expression will solve
1**3 because exponential has higher 1. Which of these in not a core data type?
precedence than multiplication, so 1**3 = 1
and 3*1 = 3. Final answer is 3.
SP
a) Lists
b) Dictionary
c) Tuples
G
8. Which one of the following has the same d) Class
precedence level?
LO

a) Addition and Subtraction Answer: d


b) Multiplication, Division and Addition Explanation: Class is a user defined data
c) Multiplication, Division, Addition and type.
Subtraction
.B

d) Addition and Multiplication 2. Given a function that does not return any
value, What value is thrown by default when
17

Answer: a executed in shell.


Explanation: “Addition and Subtraction” are a) int
at the same precedence level. Similarly, b) bool
“Multiplication and Division” are at the same
-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: https://cse-r17.blogspot.com 9


First Semester MCQ for Regulations 2017

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

M
c) ValueError
4. Which of the following will run without d) TypeError

O
errors?
a) round(45.8) Answer: b

C
b) round(6352.898,2,5) Explanation: Mango is not defined hence
c) round() name error.

T.
d) round(7463.123,2,1)
8. What will be the output of the following
Answer: a Python code snippet?

O
Explanation: Execute help(round) in the
1. def example(a):
shell to get details of the parameters that are
passed into the round function.

5. What is the return type of function id?


SP 2.
3.
a = a + '2'

a = a*2
G
a) int
b) float 4. return a
LO

c) bool
5. >>>example("hello")
d) dict
a) indentation Error
Answer: a
.B

b) cannot perform mathematical operation on


Explanation: Execute help(id) to find out
strings
details in python shell.id returns a integer
c) hello2
17

value that is unique.


d) hello2hello2
6. In python we do not specify types, it is
Answer: a
directly interpreted by the compiler, so
-R

Explanation: Python codes have to be


consider the following operation to be
indented properly.
performed.
SE

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
C

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: https://cse-r17.blogspot.com 10


First Semester MCQ for Regulations 2017

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

M
Answer: d
Explanation: Dictionary stores values in 2. >>>grade2 = 90

O
terms of keys and values.
3. >>>average = (grade1 + grade2) / 2

C
11. Which of the following results in a
a) 85.0
SyntaxError?
b) 85.1

T.
a) ‘”Once upon a time…”, she said.’
c) 95.0
b) “He said, ‘Yes!'”
d) 95.1
c) ‘3\’

O
d) ”’That’s okay”’ Answer: a
Answer: c
Explanation: Carefully look at the colons. SP
Explanation: Cause a decimal value of 0 to
appear as output.

14. Select all options that print.


G
12. The following is displayed by a print
function call. Select all of the function calls hello-how-are-you
LO

that result in this output.


a) print(‘hello’, ‘how’, ‘are’, ‘you’)
1. tom b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c) print(‘hello-‘ + ‘how-are-you’)
.B

2. dick
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ +
3. harry ‘you’)
17

a) Answer: c
Explanation: Execute in the shell.
-R

print('''tom
15. What is the return value of trunc()?
\ndick a) int
b) bool
SE

\nharry''')
c) float
b) print(”’tomdickharry”’) d) None
c) print(‘tom\ndick\nharry’)
C

Answer: a
d)
Explanation: Execute help(math.trunc) to get
print('tom details.

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

Downloaded From: https://cse-r17.blogspot.com 11


First Semester MCQ for Regulations 2017

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

M
be represented accurately in binary. The c) x = 19023
round off errors from 0.1 and 0.2 accumulate d) x = 03964

O
and hence there is a difference of 5.5511e-17
between (0.1 + 0.2) and 0.3. Answer: d

C
Explanation: Numbers starting with a 0 are
2. Which of the following is not a complex octal numbers but 9 isn’t allowed in octal

T.
number? numbers.
a) k = 2 + 3j
b) k = complex(2, 3) 7. What is the result of cmp(3, 1)?

O
c) k = 2 + 3l a) 1
d) k = 2 + 3J b) 0

Answer: c
Explanation: l (or L) stands for long.
SP
c) True
d) False
G
Answer: a
3. What is the type of inf? Explanation: cmp(x, y) returns 1 if x > y, 0 if
LO

a) Boolean x == y and -1 if x < y.


b) Integer
c) Float 8. Which of the following is incorrect?
d) Complex a) float(‘inf’)
.B

b) float(‘nan’)
Answer: c c) float(’56’+’78’)
17

Explanation: Infinity is a special case of d) float(’12+34′)


floating point numbers. It can be obtained by
float(‘inf’). Answer: d
Explanation: ‘+’ cannot be converted to a
-R

4. What does ~4 evaluate to? float.


a) -5
9. What is the result of round(0.5) –
SE

b) -4
c) -3 round(-0.5)?
d) +3 a) 1.0
b) 2.0
C

Answer: a c) 0.0
Explanation: ~x is equivalent to -(x+1). d) Value depends on Python version

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: https://cse-r17.blogspot.com 12


First Semester MCQ for Regulations 2017

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

M
Python 2.7.17 (default, Nov 7 2019, 10:0
7:09) c) 0.75
d) 7

O
>>> round(0.5)
Answer: d

C
1.0 Explanation: ^ is the Binary XOR operator.

T.
>>> round(-0.5)

-1.0
TOPIC 2.5 PRECEDENCE OF
OPERATORS

O
>>>

In the above output, you can see that the


round() functions on 0.5 and -0.5 are moving
SP
1. The value of the expressions 4/(3*(2-1))
and 4/3*(2-1) is the same.
a) True
b) False
G
away from 0 and hence “round(0.5) –
(round(-0.5)) = 1 – (-1) = 2”
Answer: a
LO

$ python3 Explanation: Although the presence of


parenthesis does affect the order of
Python 3.6.8 (default, Oct 7 2019, 12:5 precedence, in the case shown above, it is not
9:55)
.B

making a difference. The result of both of


>>> round(0.5) these expressions is 1.333333333. Hence the
statement is true.
17

0
2. What will be the value of the following
>>> round(-0.5) Python expression?
-R

0 4 + 3 % 5
>>> round(2.5)
a) 4
SE

2 b) 7
c) 2
>>> round(3.5) d) 0
C

4
Answer: b
>>> Explanation: The order of precedence is: %,
+. Hence the expression above, on
simplification results in 4 + 3 = 7. Hence the
In the above output, you can see that the result is 7.
round() functions on 0.5 and -0.5 are moving

Downloaded From: https://cse-r17.blogspot.com 13


First Semester MCQ for Regulations 2017

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

M
decimal place.
Answer: b

O
Explanation: The above expression is 7. Which of the following is the truncation
evaluated as: 16%15//16, which is equal to division operator?

C
1//16, which results in 0. a) /
b) %

T.
4. Which of the following operators has its c) //
associativity from right to left? d) |
a) +

O
b) // Answer: c
c) % Explanation: // is the operator for truncation
d) **

Answer: d
SP
division. It is called so because it returns only
the integer part of the quotient, truncating the
decimal part. For example: 20//3 = 6.
G
Explanation: All of the operators shown
above have associativity from left to right, 8. What are the values of the following
LO

except exponentiation operator (**) which Python expressions?


has its associativity from right to left.
2**(3**2)
5. What will be the value of x in the (2**3)**2
.B

following Python expression? 2**3**2

x = int(43.55+2/2) a) 64, 512, 64


17

b) 64, 64, 64
a) 43 c) 512, 512, 512
b) 44 d) 512, 64, 512
-R

c) 22
d) 23 Answer: d
Explanation: Expression 1 is evaluated as:
SE

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 **
C

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: https://cse-r17.blogspot.com 14


First Semester MCQ for Regulations 2017

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?

M
a) 4.7 – 1.5
10. What is the value of the following b) 7.9 * 6.3

O
expression? c) 1.7 % 2
d) 3.4 + 4.6

C
float(22//3+3/3)
Answer: c

T.
a) 8 Explanation: Coercion is the implicit
b) 8.0 (automatic) conversion of operands to a
c) 8.3 common type. Coercion is automatically

O
d) 8.33 performed on mixed-type expressions. The
expression 1.7 % 2 is evaluated as 1.7 % 2.0
Answer: b
Explanation: The expression shown above is
evaluated as: float( 7+1) = float(8) = 8.0.
SP
(that is, automatic conversion of int to float).

4. What will be the output of the following


G
Hence the result of this expression is 8.0. Python expression?
LO

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


Python expression?
a) (1,3)
print(4.00/(2.0+2.0)) b) (0,3)
.B

c) (1,0)
a) Error
d) (3,1)
b) 1.0
17

c) 1.00 Answer: a
d) 1 Explanation: The expressions are evaluated
as: 4%3 and 6//2 respectively. This results in
-R

Answer: b
the answer (1,3). This is because the
Explanation: The result of the expression
associativity of both of the expressions shown
shown above is 1.0 because print rounds off
above is left to right.
SE

digits.
5. Which among the following list of
2. What will be the value of X in the
operators has the highest precedence?
following Python expression?
C

+, -, **, %, /, <<, >>, |


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: https://cse-r17.blogspot.com 15


First Semester MCQ for Regulations 2017

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

M
a) 5.0
b) 5 Answer: b

O
c) 4.0 Explanation: The order of precedence is: **,
d) 4 //, +. The expression 4+2**5//10 is evaluated

C
as 4+32//10, which is equal to 4+3 = 7. Hence
Answer: c the result of the expression shown above is 7.

T.
Explanation: The above expression is an
example of explicit conversion. It is evaluated 10. The expression 2**2**3 is evaluates as:
as: float(4+int(2.39)%2) = float(4+2%2) = (2**2)**3.

O
float(4+0) = 4.0. Hence the result of this a) True
expression is 4.0. b) False

7. Which of the following expressions is an


example of type conversion?
SP
Answer: b
Explanation: The value of the expression
G
a) 4.0 + float(3) (2**2)**3 = 4**3 = 64. When the expression
b) 5.3 + 6.3 2**2**3 is evaluated in python, we get the
LO

c) 5.0 + 3 result as 256, because this expression is


d) 3 + 7 evaluated as 2**(2**3). This is because the
associativity of exponentiation operator (**)
Answer: a is from right to left and not from left to right.
.B

Explanation: Type conversion is nothing but


explicit conversion of operands to a specific
type. Options 5.3 + 6.3 and 5.0 + 3 are TOPIC 2.6 BITWISE OPERATOR
17

examples of implicit conversion whereas


option 4.0 + float(3) is an example of explicit 1. What will be the output of the following
conversion or type conversion. Python code snippet if x=1?
-R

8. Which of the following expressions results x<<2


in an error?
SE

a) float(‘10’) a) 8
b) int(‘10’) b) 1
c) float(’10.8’) c) 2
d) 4
C

d) int(’10.8’)

Answer: d Answer: d
Explanation: All of the above examples Explanation: The binary form of 1 is 0001.
show explicit conversion. However the The expression x<<2 implies we are
expression int(’10.8’) results in an error. performing bitwise left shift on x. This shift
yields the value: 0100, which is the binary
form of the number 4.

Downloaded From: https://cse-r17.blogspot.com 16


First Semester MCQ for Regulations 2017

2. What will be the output of the following 5. To find the decimal value of 1111, that is
Python expression? 15, we can use the function:
a) int(1111,10)
bin(29) b) int(‘1111’,10)
c) int(1111,2)
a) ‘0b10111’ d) int(‘1111’,2)
b) ‘0b11101’
c) ‘0b11111’ Answer: d
d) ‘0b11011’ Explanation: The expression int(‘1111’,2)

M
gives the result 15. The expression int(‘1111’,
Answer: b 10) will give the result 1111.

O
Explanation: The binary form of the number
29 is 11101. Hence the output of this 6. What will be the output of the following

C
expression is ‘0b11101’. Python expression if x=15 and y=12?

T.
3. What will be the value of x in the x & y
following Python expression, if the result of
that expression is 2? a) b1101

O
b) 0b1101
x>>2 c) 12
a) 8
b) 4
SP
d) 1101

Answer: c
c) 2
G
Explanation: The symbol ‘&’ represents
d) 1 bitwise AND. This gives 1 if both the bits are
LO

equal to 1, else it gives 0. The binary form of


Answer: a 15 is 1111 and that of 12 is 1100. Hence on
Explanation: When the value of x is equal to performing the bitwise AND operation, we
8 (1000), then x>>2 (bitwise right shift) get 1100, which is equal to 12.
.B

yields the value 0010, which is equal to 2.


Hence the value of x is 8. 7. Which of the following expressions results
in an error?
17

4. What will be the output of the following a) int(1011)


Python expression? b) int(‘1011’,23)
c) int(1011,2)
-R

int(1011)?
d) int(‘1011’)
a) 1011
Answer: c
SE

b) 11
c) 13 Explanation: The expression int(1011,2)
d) 1101 results in an error. Had we written this
expression as int(‘1011’,2), then there would
C

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: https://cse-r17.blogspot.com 17


First Semester MCQ for Regulations 2017

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

M
a) ‘0bx1000’ Answer: a

O
b) 8 Explanation: The one’s complement of a
c) 1000 value is obtained by simply changing all the

C
d) ‘0b1000’ 1’s to 0’s and all the 0’s to 1’s. Hence the
one’s complement of 110010101 is

T.
Answer: d 001101010.
Explanation: The prefix 0x specifies that the
value is hexadecimal in nature. When we 3. Bitwise _________ gives 1 if either of the

O
convert this hexadecimal value to binary bits is 1 and 0 when both of the bits are 1.
form, we get the result as: ‘0b1000’. a) OR
10. What will be the output of the following
Python expression?
SP
b) AND
c) XOR
d) NOT
G
0x35 | 0x75
Answer: c
LO

a) 115 Explanation: Bitwise XOR gives 1 if either


b) 116 of the bits is 1 and 0 when both of the bits are
c) 117 1.
.B

d) 118
4. What will be the output of the following
Answer: c Python expression?
17

Explanation: The binary value of 0x35 is


4^12
110101 and that of 0x75 is 1110101. On OR-
ing these two values we get the output as: a) 2
-R

1110101, which is equal to 117. Hence the b) 4


result of the above expression is 117. c) 8
d) 12
SE

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
C

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: https://cse-r17.blogspot.com 18


First Semester MCQ for Regulations 2017

a) 10 a=a^b
b) 2 print(a,b)
c) 1
d) 0 a) 10 20
b) 10 10
Answer: c c) 20 10
Explanation: Any odd number on being d) 20 20
AND-ed with 1 always gives 1. Any even
number on being AND-ed with this value Answer: c

M
always gives 0. Explanation: The code shown above is used
to swap the contents of two memory locations

O
6. What will be the value of the following using bitwise X0R operator. Hence the output
Python expression? of the code shown above is: 20 10.

C
bin(10-2)+bin(12^4) 9. What is the two’s complement of -44?

T.
a) 1011011
a) 0b10000 b) 11010100
b) 0b10001000 c) 11101011

O
c) 0b1000b1000 d) 10110011
d) 0b10000b1000

Answer: d
Explanation: The output of bin(10-2) =
SP
Answer: b
Explanation: The binary form of -44 is
00101100. The one’s complement of this
G
0b1000 and that of bin(12^4) is ob1000. value is 11010011. On adding one to this we
Hence the output of the above expression is: get: 11010100 (two’s complement).
LO

0b10000b1000.
10. What will be the output of the following
7. Which of the following expressions can be Python expression?
used to multiply a given number ‘a’ by 4?
.B

a) a<<2 ~100?
b) a<<4
a) 101
c) a>>2
17

b) -101
d) a>>4
c) 100
Answer: a d) -100
-R

Explanation: Let us consider an example


Answer: b
wherein a=2. The binary form of 2 is 0010.
Explanation: Suppose we have an expression
When we left shift this value by 2, we get
SE

~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
can use the expression: a<<2. which is equal to -101.
C

8. What will be the output of the following Sanfoundry Global Education & Learning
Series – Python.
Python code if a=10 and b =20?
a=10 TOPIC 2.7 BOOLEAN
b=20
a=a^b
b=a^b

Downloaded From: https://cse-r17.blogspot.com 19


First Semester MCQ for Regulations 2017

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?

M
True
not(3>4)

O
b) not(1&1)

a)

C
False

T.
True True

c) True

O
False b)

d)
False
SP True

False
G
True c)
LO

False False

Answer: d True
Explanation: The Boolean function returns
.B

true if the argument passed to the bool d)


function does not amount to zero. In the first
False
17

example, the string ‘False’ is passed to the


function bool. This does not amount to zero False
and hence the output is true. In the second
function, an empty list is passed to the Answer: b
-R

function bool. Hence the output is false. Explanation: The function not returns true if
the argument amounts to false, and false if the
argument amounts to true. Hence the first
SE

function returns false, and the second


2. What will be the output of the following function returns false.
Python code snippet?
C

['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: https://cse-r17.blogspot.com 20


First Semester MCQ for Regulations 2017

a) t {}
b) f
[]
c) No output
d) Error d)
Answer: a {}
Explanation: The line of code can be
translated to state that ‘f’ is printed if the {}
argument passed to the Boolean function

M
amount to zero. Else ‘t’ is printed. The Answer: c
argument given to the Boolean function in the Explanation: The code shown above shows

O
above case is ‘spam’, which does not amount two functions. In both the cases the right
to zero. Hence the output is t. operand is returned. This is because each

C
function is evaluated from left to right. Since
5. What will be the output of the following the left operand is false, it is assumed that the

T.
Python code? right operand must be true and hence the right
operand is returned in each of the above case.
l=[1, 0, 2, 0, 'hello', '', []]

O
list(filter(bool, l))

a) Error
b) [1, 0, 2, 0, ‘hello’, ”, []]
c) [1, 0, 2, ‘hello’, ”, []]
SP
7. What will be the output of the following
Python code?
G
d) [1, 2, ‘hello’] class Truth:
pass
x=Truth()
LO

Answer: d
bool(x)
Explanation: The code shown above returns
a new list containing only those elements of a) pass
the list l which do not amount to zero. Hence b) true
.B

the output is: [1, 2, ‘hello’]. c) false


d) error
6. What will be the output of the following
17

Python code if the system date is 21st June, Answer: b


2017 (Wednesday)? Explanation: If the truth method is not
defined, the object is considered true. Hence
-R

[] or {}
{} or [] the output of the code shown above is true.

8. What will be the output of the following


SE

a)
Python code?
[]
if (9 < 0) and (0 < -9):
C

{} print("hello")
elif (9 > 0) or False:
b) print("good")
else:
[] print("bad")

[] a) error
b) hello
c)

Downloaded From: https://cse-r17.blogspot.com 21


First Semester MCQ for Regulations 2017

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

M
9. Which of the following Boolean
1. What will be the output of the following

O
expressions is not logically equivalent to the
Python code?
other three?

C
a) not(-6<0 or-6>10) x = ['ab', 'cd']
b) -6>=0 and -6<=10 for i in x:

T.
c) not(-6<10 or-6==10) i.upper()
d) not(-6>10 or-6==10) print(x)

O
Answer: d a) [‘ab’, ‘cd’]
Explanation: The expression not(-6<0 or b) [‘AB’, ‘CD’]
-6>10) returns the output False.
The expression -6>=0 and -6<=10 returns the
output False.
SP
c) [None, None]
d) none of the mentioned
G
The expression not(-6<10 or -6==10) returns Answer: a
the output False. Explanation: The function upper() does not
LO

The expression not(-6>10 or -6==10) returns modify a string in place, it returns a new
the output True. string which isn’t being stored anywhere.

10. What will be the output of the following 2. What will be the output of the following
.B

Python code snippet? Python code?

x = ['ab', 'cd']
17

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


for i in x:
x.append(i.upper())
a) True print(x)
b) False
-R

c) Error a) [‘AB’, ‘CD’]


d) No output b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
SE

Answer: b d) none of the mentioned


Explanation: The expression not(10<20)
returns false. The expression not(10>30) Answer: d
C

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: https://cse-r17.blogspot.com 22


First Semester MCQ for Regulations 2017

i = 1 Answer: b
while True: Explanation: 0O11 is an octal number.
if i%3 == 0:
break
print(i) 6. What will be the output of the following
Python code?
i + = 1
i = 5
a) 1 2 while True:
if i%0O9 == 0:
b) 1 2 3

M
break
c) error print(i)
d) none of the mentioned i += 1

O
Answer: c a) 5 6 7 8

C
Explanation: SyntaxError, there shouldn’t be b) 5 6 7 8 9
a space between + and = in +=. c) 5 6 7 8 9 10 11 12 13 14 15 ….

T.
d) error
4. What will be the output of the following
Python code? Answer: d

O
Explanation: 9 isn’t allowed in an octal
i = 1 number.
while True:
if i%0O7 == 0:
break
print(i)
SP
7. What will be the output of the following
Python code?
G
i += 1
i = 1
LO

a) 1 2 3 4 5 6 while True:
if i%2 == 0:
b) 1 2 3 4 5 6 7
break
c) error print(i)
d) none of the mentioned i += 2
.B

Answer: a a) 1
Explanation: Control exits the loop when i
17

b) 1 2
becomes 7. c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
5. What will be the output of the following
-R

Python code? Answer: d


Explanation: The loop does not terminate
i = 5 since i is never an even number.
SE

while True:
if i%0O11 == 0:
break 8. What will be the output of the following
print(i) Python code?
C

i += 1
i = 2
a) 5 6 7 8 9 10 while True:
if i%3 == 0:
b) 5 6 7 8 break
c) 5 6 print(i)
d) error i += 2

Downloaded From: https://cse-r17.blogspot.com 23


First Semester MCQ for Regulations 2017

a) 2 4 6 8 10 … i = 0
b) 2 4 while i < 5:
print(i)
c) 2 3 i += 1
d) error if i == 3:
break
Answer: b else:
Explanation: The numbers 2 and 4 are print(0)
printed. The next value of i is 6 which is
divisible by 3 and hence control exits the a) 0 1 2 0

M
loop. b) 0 1 2
c) error

O
9. What will be the output of the following d) none of the mentioned
Python code?

C
Answer: b
i = 1 Explanation: The else part is not executed if

T.
while False: control breaks out of the loop.
if i%2 == 0:
break 2. What will be the output of the following

O
print(i)
i += 2
Python code?

a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
SP
i = 0
while i < 3:
print(i)
i += 1
G
d) none of the mentioned else:
print(0)
LO

Answer: d
Explanation: Control does not enter the loop a) 0 1 2 3 0
because of False. b) 0 1 2 0
c) 0 1 2
.B

10. What will be the output of the following d) error


Python code?
Answer: b
17

True = False Explanation: The else part is executed when


while True: the condition in the while statement is false.
print(True)
-R

break 3. What will be the output of the following


Python code?
a) True
SE

b) False x = "abcdef"
c) None while i in x:
d) none of the mentioned print(i, end=" ")
C

Answer: d a) a b c d e f
Explanation: SyntaxError, True is a keyword b) abcdef
and it’s value cannot be changed. c) i i i i i i …
d) error
1. What will be the output of the following
Python code? Answer: d
Explanation: NameError, i is not defined.

Downloaded From: https://cse-r17.blogspot.com 24


First Semester MCQ for Regulations 2017

4. What will be the output of the following evaluate to True. But also here we use a
Python code? citation marks on “i”, so, here i treated as a
string, not like a variable.
x = "abcdef"
i = "i" 7. What will be the output of the following
while i in x:
print(i, end=" ")
Python code?

x = "abcdef"
a) no output i = "a"

M
b) i i i i i i … while i in x:
c) a b c d e f x = x[:-1]
d) abcdef print(i, end = " ")

O
Answer: a a) i i i i i i

C
Explanation: “i” is not in “abcdef”. b) a a a a a a
c) a a a a a

T.
5. What will be the output of the following d) none of the mentioned
Python code?
Answer: b

O
x = "abcdef" Explanation: The string x is being shortened
i = "a" by one character in each iteration.
while i in x:
print(i, end = " ") SP
8. What will be the output of the following
Python code?
a) no output
G
b) i i i i i i … x = "abcdef"
c) a a a a a a …
LO

i = "a"
d) a b c d e f while i in x[:-1]:
print(i, end = " ")
Answer: c
.B

Explanation: As the value of i or x isn’t a) a a a a a


changing, the condition will always evaluate b) a a a a a a
to True. c) a a a a a a …
17

d) a
6. What will be the output of the following
Python code? Answer: c
-R

Explanation: String x is not being altered and


x = "abcdef" i is in x[:-1].
i = "a"
SE

while i in x: 9. What will be the output of the following


print('i', end = " ")
Python code?
a) no output x = "abcdef"
C

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: https://cse-r17.blogspot.com 25


First Semester MCQ for Regulations 2017

c) no output c) a B C D
d) error d) error

Answer: b Answer: b
Explanation: The string x is being shortened Explanation: The instance of the string
by one character in each iteration. returned by upper() is being printed.

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

M
x = "abcdef" x = 'abcd'

O
i = "a" for i in range(x):
while i in x[1:]: print(i)
print(i, end = " ")

C
a) a b c d
a) a a a a a a b) 0 1 2 3

T.
b) a c) error
c) no output d) none of the mentioned

O
d) error
Answer: c
Answer: c
Explanation: i is not in x[1:].

1. What will be the output of the following


SP
Explanation: range(str) is not allowed.

4. What will be the output of the following


Python code?
G
Python code?
x = 'abcd'
LO

x = 'abcd' for i in range(len(x)):


for i in x: print(i)
print(i)
x.upper() a) a b c d
.B

b) 0 1 2 3
a) a B C D c) error
b) a b c d d) 1 2 3 4
17

c) A B C D
d) error Answer: b
Explanation: i takes values 0, 1, 2 and 3.
-R

Answer: b
Explanation: Changes do not happen in- 5. What will be the output of the following
place, rather a new instance of the string is Python code?
SE

returned.
x = 'abcd'
2. What will be the output of the following for i in range(len(x)):
Python code? print(i.upper())
C

x = 'abcd' a) a b c d
for i in x: b) 0 1 2 3
print(i.upper()) c) error
d) 1 2 3 4
a) a b c d
b) A B C D

Downloaded From: https://cse-r17.blogspot.com 26


First Semester MCQ for Regulations 2017

Answer: c Answer: c
Explanation: Objects of type int have no Explanation: Objects of type int aren’t
attribute upper(). subscriptable. However, if the statement was
x[i], an error would not have been thrown.
6. What will be the output of the following
Python code snippet? 9. What will be the output of the following
Python code snippet?
x = 'abcd'
for i in range(len(x)): x = 'abcd'

M
i.upper() for i in range(len(x)):
print (x) x = 'a'
print(x)

O
a) a b c d
b) 0 1 2 3 a) a

C
c) error b) abcd abcd abcd
d) none of the mentioned c) a a a a

T.
d) none of the mentioned
Answer: c

O
Explanation: Objects of type int have no Answer: c
attribute upper(). Explanation: range() is computed only at the

7. What will be the output of the following


Python code snippet?
SP
time of entering the loop.

10. What will be the output of the following


Python code snippet?
G
x = 'abcd'
for i in range(len(x)): x = 'abcd'
LO

x[i].upper() for i in range(len(x)):


print (x) print(x)
x = 'a'
a) abcd
.B

b) ABCD a) a
c) error b) abcd abcd abcd abcd
d) none of the mentioned c) a a a a
17

d) none of the mentioned


Answer: a
Explanation: Changes do not happen in- Answer: d
-R

place, rather a new instance of the string is Explanation: abcd a a a is the output as x is
returned. modified only after ‘abcd’ has been printed
once.
SE

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

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: https://cse-r17.blogspot.com 27


First Semester MCQ for Regulations 2017

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

M
print(i) c) 0 a 1 b 2 c
d) none of the mentioned
a) 0 1 2

O
b) a b c Answer: b
c) 0 a 1 b 2 c Explanation: Loops over the keys and prints

C
d) none of the mentioned the values.

T.
Answer: a 6. What will be the output of the following
Explanation: Loops over the keys of the Python code?

O
dictionary.
d = {0: 'a', 1: 'b', 2: 'c'}
3. What will be the output of the following
Python code?

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


SP
for x in d.values():
print(x)

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

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 values.
.B

d) none of the mentioned


7. What will be the output of the following
Answer: d Python code?
17

Explanation: Error, objects of type int aren’t


iterable. d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
-R

print(d[x])
4. What will be the output of the following
Python code? a) 0 1 2
SE

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
C

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: https://cse-r17.blogspot.com 28


First Semester MCQ for Regulations 2017

print(x) a) 0
b) no output
a) 0 1 2 c) error
b) None None None d) none of the mentioned
c) error
d) none of the mentioned Answer: b
Explanation: range(0) is empty.
Answer: c
Explanation: Objects of type set have no 1. What will be the output of the following

M
attribute values. Python code?

O
9. What will be the output of the following for i in range(2.0):
Python code? print(i)

C
d = {0, 1, 2} a) 0.0 1.0
b) 0 1

T.
for x in d:
print(x) c) error
d) none of the mentioned
a) 0 1 2

O
b) {0, 1, 2} {0, 1, 2} {0, 1, 2} Answer: c
c) error
d) none of the mentioned

Answer: a
SP
Explanation: Object of type float cannot be
interpreted as an integer.

2. What will be the output of the following


G
Explanation: Loops over the elements of the Python code?
set and prints them.
LO

for i in range(int(2.0)):
10. What will be the output of the following print(i)
Python code?
a) 0.0 1.0
.B

d = {0, 1, 2} b) 0 1
for x in d: c) error
print(d.add(x))
17

d) none of the mentioned


a) 0 1 2
Answer: b
b) 0 1 2 0 1 2 0 1 2 …
Explanation: range(int(2.0)) is the same as
-R

c) None None None


range(2).
d) None of the mentioned
3. What will be the output of the following
SE

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

print (i)

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

Downloaded From: https://cse-r17.blogspot.com 29


First Semester MCQ for Regulations 2017

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

M
Explanation: [::-1] reverses the string.
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 … 8. What will be the output of the following

O
c) 0.0 1.0 2.0 3.0 … Python code snippet?
d) none of the mentioned

C
for i in '':
Answer: d print (i)

T.
Explanation: OverflowError, cannot convert
a) None
float infinity to integer.
b) (nothing is printed)

O
5. What will be the output of the following c) error
d) none of the mentioned
Python code snippet?

for i in [1, 2, 3, 4][::-1]:


print (i)
SP
Answer: b
Explanation: The string does not have any
G
character to loop over.
a) 1 2 3 4
LO

b) 4 3 2 1 9. What will be the output of the following


c) error Python code snippet?
d) none of the mentioned
x = 2
.B

Answer: b for i in range(x):


x += 1
Explanation: [::-1] reverses the list. print (x)
17

6. What will be the output of the following a) 0 1 2 3 4 …


Python code snippet? b) 0 1
-R

for i in ''.join(reversed(list('abcd'))):
c) 3 4
print (i) d) 0 1 2 3
SE

a) a b c d Answer: c
b) d c b a Explanation: Variable x is incremented and
c) error printed twice.
C

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: https://cse-r17.blogspot.com 30


First Semester MCQ for Regulations 2017

a) 0 1 2 3 4 … x = (i for i in range(3))
b) 0 -2 for i in x:
print(i)
c) 0
d) error a) 0 1 2
b) error
Answer: b
c) 0 1 2 0 1 2
Explanation: The loop is entered twice.
d) none of the mentioned
1. What will be the output of the following

M
Answer: a
Python code?
Explanation: The first statement creates a
generator object.

O
for i in range(10):
if i == 5:
break 4. What will be the output of the following

C
else: Python code?
print(i)

T.
else: x = (i for i in range(3))
print("Here") for i in x:
print(i)

O
a) 0 1 2 3 4 Here for i in x:
b) 0 1 2 3 4 5 Here print(i)
c) 0 1 2 3 4
d) 1 2 3 4 5 SP
a) 0 1 2
b) error
G
Answer: c c) 0 1 2 0 1 2
Explanation: The else part is executed if d) none of the mentioned
LO

control doesn’t break out of the loop.


Answer: a
2. What will be the output of the following Explanation: We can loop over a generator
Python code? object only once.
.B

for i in range(5): 5. What will be the output of the following


if i == 5: Python code?
17

break
else: string = "my name is x"
print(i) for i in string:
else: print (i, end=", ")
-R

print("Here")
a) m, y, , n, a, m, e, , i, s, , x,
a) 0 1 2 3 4 Here b) m, y, , n, a, m, e, , i, s, , x
SE

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
C

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: https://cse-r17.blogspot.com 31


First Semester MCQ for Regulations 2017

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
d) none of the mentioned

M
Answer: c
Explanation: Variable i takes the value of
one word at a time. Answer: c

O
Explanation: SyntaxError, not in isn’t
7. What will be the output of the following allowed in for loops.

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

T.
a = [0, 1, 2, 3] Python code snippet?
for a[-1] in a:
print(a[-1]) string = "my name is x"

O
for i in ' '.join(string.split()):
a) 0 1 2 3 print (i, end=", ")
b) 0 1 2 2
c) 3 3 3 3
d) error
SP
a) m, y, , n, a, m, e, , i, s, , x,
b) m, y, , n, a, m, e, , i, s, , x
G
c) my, name, is, x,
Answer: b d) error
LO

Explanation: The value of a[-1] changes in


each iteration. Answer: a
Explanation: Variable i takes the value of
8. What will be the output of the following one character at a time.
.B

Python code snippet?

a = [0, 1, 2, 3]
TOPIC 3.2 PYTHON STRINGS
17

for a[0] in a:
print(a[0]) 1. What will be the output of the following
Python statement?
-R

a) 0 1 2 3
b) 0 1 2 2 1. >>>"a"+"bc"
c) 3 3 3 3
SE

d) error a) a
b) bc
Answer: a c) bca
Explanation: The value of a[0] changes in d) abc
C

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: https://cse-r17.blogspot.com 32


First Semester MCQ for Regulations 2017

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

M
string. a) a new line and hello
b) \nhello

O
3. The output of executing string.ascii_letters c) the letter r and then hello
can also be achieved by: d) error

C
a) string.ascii_lowercase_string.digits
b) Answer: b

T.
string.ascii_lowercase+string.ascii_uppercase Explanation: When prefixed with the letter
c) string.letters ‘r’ or ‘R’ a string literal becomes a raw string
d) string.lowercase_string.uppercase and the escape sequences such as \n are not

O
converted.
Answer: b
Explanation: Execute in shell and check.

4. What will be the output of the following


SP
7. What will be the output of the following
Python statement?
G
Python code? 1. >>>print('new' 'line')
LO

1. >>> str1 = 'hello' a) Error


b) Output equivalent to print ‘new\nline’
2. >>> str2 = ',' c) newline
d) new line
.B

3. >>> str3 = 'world'


4. >>> str1[-1:] Answer: c
Explanation: String literal separated by
17

a) olleh whitespace are allowed. They are


b) hello concatenated.
c) h
-R

d) o 8. What will be the output of the following


Python statement?
Answer: d
SE

Explanation: -1 corresponds to the last index. 1. >>> print('x\97\x98')

5. What arithmetic operators cannot be used a) Error


C

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

Downloaded From: https://cse-r17.blogspot.com 33


First Semester MCQ for Regulations 2017

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

M
c) 22 None
2. >>>str1[::-1]
d) Error is generated

O
a) dlrowolleh
Answer: d

C
b) hello
c) world Explanation: self.o1 was never created.

T.
d) helloworld
2. What will be the output of the following
Python code?
Answer: a

O
Explanation: Execute in shell to verify.
1. class tester:
10. What will be the output of the following
Python code? SP 2.
3.
def __init__(self, id):

self.id = str(id)
G
print(0xA + 0xB + 0xC)
4. id="224"
a) 0xA0xB0xC
LO

b) Error 5.
c) 0x22
6. >>>temp = tester(12)
d) 33
.B

7. >>>print(temp.id)
Answer: d
Explanation: 0xA and 0xB and 0xC are a) 224
17

hexadecimal integer literals representing the b) Error


decimal values 10, 11 and 12 respectively. c) 12
There sum is 33. d) None
-R

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


Python code? Explanation: Id in this case will be the
SE

attribute of the class.


1. class father:
3. What will be the output of the following
2. def __init__(self, param):
Python code?
C

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: https://cse-r17.blogspot.com 34


First Semester MCQ for Regulations 2017

c) sn 1. >>>example = "helle"
d) rl
2. >>>example.find("e")
Answer: a
Explanation: Execute in the shell and verify. a) Error
b) -1
4. What will be the output of the following c) 1
Python code? d) 0

M
1. >>>example = "snow world" Answer: c
Explanation: Returns lowest index.
2. >>>example[3] = 's'

O
8. What will be the output of the following
3. >>>print example

C
Python code?
a) snow

T.
1. >>>example = "helle"
b) snow world
c) Error 2. >>>example.rfind("e")

O
d) snos world
a) -1
Answer: c
Explanation: Strings cannot be modified.

5. What will be the output of the following


SP
b) 4
c) 3
d) 1
G
Python code? Answer: b
Explanation: Returns highest index.
LO

1. >>>max("what are you")


9. What will be the output of the following
a) error Python code?
b) u
.B

c) t 1. >>>example="helloworld"
d) y
17

2. >>>example[::-1].startswith("d")
Answer: d
Explanation: Max returns the character with a) dlrowolleh
the highest ascii value. b) True
-R

c) -1
6. Given a string example=”hello” what is the d) None
SE

output of example.count(‘l’)?
a) 2 Answer: b
b) 1 Explanation: Starts with checks if the given
c) None string starts with the parameter that is passed.
C

d) 0
10. To concatenate two strings to a third what
Answer: a statements are applicable?
Explanation: l occurs twice in hello. a) s3 = s1 . s2
b) s3 = s1.add(s2)
7. What will be the output of the following c) s3 = s1.__add__(s2)
Python code? d) s3 = s1 * s2

Downloaded From: https://cse-r17.blogspot.com 35


First Semester MCQ for Regulations 2017

Answer: c Answer: d
Explanation: __add__ is another method that Explanation: Execute help(string.strip) to
can be used for concatenation. find details.

1. What will be the output of the following 5. The format function, when applied on a
Python statement? string returns ___________
a) Error
1. >>>chr(ord('A')) b) int
c) bool

M
a) A d) str
b) B

O
c) a Answer: d
d) Error Explanation: Format function returns a

C
string.
Answer: a

T.
Explanation: Execute in shell to verify. 6. What will be the output of the “hello”
+1+2+3?
2. What will be the output of the following a) hello123

O
Python statement? b) hello
c) Error
1. >>>print(chr(ord('b')+1))

a) a
SP
d) hello6

Answer: c
G
b) b Explanation: Cannot concatenate str and int
c) c objects.
LO

d) A
7. What will be the output of the following
Answer: c Python code?
Explanation: Execute in the shell to verify.
.B

1. >>>print("D", end = ' ')


3. Which of the following statement prints
hello\example\test.txt? 2. >>>print("C", end = ' ')
17

a) print(“hello\example\test.txt”)
b) print(“hello\example\test.txt”) 3. >>>print("B", end = ' ')
c) print(“hello\”example\”test.txt”)
-R

4. >>>print("A", end = ' ')


d) print(“hello”\example”\test.txt”)
a) DCBA
Answer: b
SE

b) A, B, C, D
Explanation: \is used to indicate that the next
c) D C B A
\ is not an escape sequence.
d) D, C, B, A will be displayed on four lines
C

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: https://cse-r17.blogspot.com 36


First Semester MCQ for Regulations 2017

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

M
command do we execute?
Answer: d
a) s.__len__()
Explanation: Execute in the shell to verify.

O
b) len(s)
9. What will be displayed by print(ord(‘b’) – c) size(s)

C
ord(‘a’))? d) s.size()
a) 0

T.
Answer: a
b) 1
Explanation: Execute in shell to verify.
c) -1

O
d) 2 4. If a class defines the __str__(self) method,
for an object obj for the class, you can use
Answer: b
Explanation: ASCII value of b is one more
than a. Hence the output of this code is 98-97,
SP
which command to invoke the __str__
method.
a) obj.__str__()
G
which is equal to 1.
b) str(obj)
c) print obj
10. Say s=”hello” what will be the return
LO

d) all of the mentioned


value of type(s)?
a) int
Answer: d
b) bool
Explanation: Execute in shell to verify.
.B

c) str
d) String 5. To check whether string s1 contains
17

another string s2, use ________


Answer: c
a) s1.__contains__(s2)
Explanation: str is used to represent strings b) s2 in s1
in python. c) s1.contains(s2)
-R

d) si.in(s2)
1. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
Answer: a
SE

b) Heelo
Explanation: s2 in s1 works in the same way
c) Heleo
as calling the special function __contains__ .
d) None
C

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
string s=”Hello” what command do we c) i.__Add(j)
execute (multiple answers allowed)? d) i.__ADD(j)
a) s[]

Downloaded From: https://cse-r17.blogspot.com 37


First Semester MCQ for Regulations 2017

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

M
)
3. self.__count = count

O
a) Peter Pan
4.
b) John Pan

C
5. c1 = Count(2) c) Peter Smith
d) John Smith

T.
6. c2 = Count(2)
Answer: b
7. print(id(c1) == id(c2), end = " ") Explanation: Execute in the shell to verify.

O
8. 9. What function do you use to read a string?
9. s1 = "Good"
10. s2 = "Good"
SP
a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
G
d) eval(enter(“Enter a string”))
11. print(id(s1) == id(s2))
LO

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

d) False False “10.3f”) (_ indicates space).


a) __345.355
Answer: c b) ___345.355
17

Explanation: Execute in the shell objects c) ____345.355


cannot have same id, however in the case of d) _____345.354
strings its different.
-R

Answer: b
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?
SE

1. What will be the output of the following


1. class Name: Python code?
2. def __init__(self, firstName, m print("abc DEF".capitalize())
C

i, lastName):

3. self.firstName = firstName
a) abc def
b) ABC DEF
4. self.mi = mi c) Abc def
d) Abc Def
5. self.lastName = lastName

6.

Downloaded From: https://cse-r17.blogspot.com 38


First Semester MCQ for Regulations 2017

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*

M
a) abc. def Answer: b

O
b) ABC. DEF Explanation: Padding is done towards the
c) Abc. def left-hand-side first when the final string is of

C
d) Abc. Def odd length. Extra spaces are present since we
haven’t overridden the value of sep.

T.
Answer: c
Explanation: The first letter of the string is 6. What will be the output of the following
converted to uppercase and the others are Python code?

O
converted to lowercase.
print('*', "abcdef".center(7), '*', sep=
3. What will be the output of the following
Python code? SP
'')

a) * abcdef *
b) * abcdef *
G
print("abcdef".center())
c) *abcdef *
a) cd d) * abcdef*
LO

b) abcdef
c) error Answer: d
d) none of the mentioned Explanation: Padding is done towards the
.B

left-hand-side first when the final string is of


Answer: c odd length.
Explanation: The function center() takes at
17

least one parameter. 7. What will be the output of the following


Python code?
4. What will be the output of the following
-R

Python code? print('*', "abcde".center(6), '*', sep=''


)
print("abcdef".center(0))
a) * abcde *
SE

a) cd b) * abcde *
b) abcdef c) *abcde *
c) error d) * abcde*
C

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: https://cse-r17.blogspot.com 39


First Semester MCQ for Regulations 2017

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

M
must be a character, not an int. a) 2
b) 0

O
9. What will be the output of the following c) 1
Python code? d) none of the mentioned

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

T.
Explanation: Counts the number of times the
a) 1abcdef substring ‘yy’ is present in the given string,
b) abcdef1 starting from position 1.

O
c) abcdef
d) error 3. What will be the output of the following
Answer: a
Explanation: The character ‘1’ is used for
SP
Python code?

print("xyyzxyzxzxyy".count('yy', 2))
padding instead of a space.
G
a) 2
10. What will be the output of the following b) 0
LO

Python code? c) 1
d) none of the mentioned
print("abcdef".center(10, '12'))
.B

Answer: c
a) 12abcdef12 Explanation: Counts the number of times the
b) abcdef1212 substring ‘yy’ is present in the given string,
17

c) 1212abcdef starting from position 2.


d) error
4. What will be the output of the following
Answer: d
-R

Python code?
Explanation: The fill character must be
exactly one character long. print("xyyzxyzxzxyy".count('xyy', 0, 100)
SE

)
1. What will be the output of the following
Python code? a) 2
b) 0
C

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

Downloaded From: https://cse-r17.blogspot.com 40


First Semester MCQ for Regulations 2017

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

M
Python code?
Answer: b

O
Explanation: Counts the number of times the print("xyyzxyzxzxyy".endswith("xyy"))
substring ‘xyy’ is present in the given string,

C
starting from position 2 and ending at a) 1
position 11. b) True

T.
c) 3
6. What will be the output of the following d) 2
Python code?

O
Answer: b
print("xyyzxyzxzxyy".count('xyy', -10, -1 Explanation: The function returns True if the
))

a) 2
b) 0
SP
given string ends with the specified substring.

10. What will be the output of the following


G
Python code?
c) 1
d) error
LO

print("xyyzxyzxzxyy".endswith("xyy", 0, 2
))
Answer: b
Explanation: Counts the number of times the a) 0
.B

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


starting from position 2 and ending at c) True
position 11. d) False
17

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


Python code? Explanation: The function returns False if
-R

the given string does not end with the


print('abc'.encode()) specified substring.
a) abc
SE

1. What will be the output of the following


b) ‘abc’ Python code?
c) b’abc’
d) h’abc’ print("ab\tcd\tef".expandtabs())
C

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: https://cse-r17.blogspot.com 41


First Semester MCQ for Regulations 2017

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

M
c) ab\tcd\tef string at which the substring can be found is
d) ab cd ef returned.

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

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

T.
print("ccdcddcd".find("c"))
3. What will be the output of the following
Python code? a) 4

O
b) 0
print("ab\tcd\tef".expandtabs('+')) c) Error

a) ab+cd+ef
b) ab++++++++cd++++++++ef
SP
d) True

Answer: b
c) ab cd ef Explanation: The first position in the given
G
d) none of the mentioned string at which the substring can be found is
returned.
LO

Answer: d
Explanation: TypeError, an integer should be 7. What will be the output of the following
passed as an argument. Python code?
.B

4. What will be the output of the following print("Hello {0} and {1}".format('foo',
Python code? 'bin'))
17

print("abcdef".find("cd") == "cd" in "abc a) Hello foo and bin


def") b) Hello {0} and {1} foo bin
c) Error
-R

a) True d) Hello 0 and 1


b) False
c) Error Answer: a
SE

d) None of the mentioned Explanation: The numbers 0 and 1 represent


the position at which the strings are present.
Answer: b
C

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: https://cse-r17.blogspot.com 42


First Semester MCQ for Regulations 2017

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
Python code? a) Hello foo and foo

M
b) Hello ‘foo’ and foo
print("Hello {} and {}".format('foo', 'bi c) Hello foo and ‘bin’
d) Error

O
n'))

a) Hello foo and bin Answer: b

C
b) Hello {} and {} Explanation: !r causes the characters ‘ or ” to
c) Error be printed as well.

T.
d) Hello and
3. What will be the output of the following

O
Answer: a Python code?
Explanation: It is the same as Hello {0} and
{1}.

10. What will be the output of the following


SP
print("Hello {0} and {1}".format(('foo',
'bin')))

a) Hello foo and bin


Python code?
G
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
print("Hello {name1} and {name2}".format( c) Error
LO

'foo', 'bin')) d) None of the mentioned

a) Hello foo and bin Answer: c


b) Hello {name1} and {name2} Explanation: IndexError, the tuple index is
.B

c) Error out of range.


d) Hello and
17

4. What will be the output of the following


Answer: c Python code?
Explanation: The arguments passed to the
function format aren’t keyword arguments. print("Hello {0[0]} and {0[1]}".format((
-R

'foo', 'bin')))
1. What will be the output of the following
Python code? a) Hello foo and bin
SE

b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)


print("Hello {name1} and {name2}".format( c) Error
name1='foo', name2='bin')) d) None of the mentioned
C

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: https://cse-r17.blogspot.com 43


First Semester MCQ for Regulations 2017

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

M
Explanation: The arguments passed to the b) 111,222,333,4
function format can be integers also. c) 1112223334

O
d) Error
6. What will be the output of the following
Python code snippet?

C
Answer: d
Explanation: $ is an invalid format code.

T.
print('The sum of {0:b} and {1:x} is {2:
o}'.format(2, 10, 12)) 10. What will be the output of the following
Python code snippet?
a) The sum of 2 and 10 is 12

O
b) The sum of 10 and a is 14 print('{:#}'.format(1112223334))
c) The sum of 10 and a is c
d) Error

Answer: b
SP
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
G
Explanation: 2 is converted to binary, 10 to d) Error
hexadecimal and 12 to octal.
LO

Answer: c
7. What will be the output of the following Explanation: The number is printed as it is.
Python code snippet?
.B

1. What will be the output of the following


print('{:,}'.format(1112223334)) Python code?
a) 1,112,223,334
17

print('{0:.2}'.format(1/3))
b) 111,222,333,4
c) 1112223334 a) 0.333333
d) Error b) 0.33
-R

c) 0.333333:.2
Answer: a d) Error
Explanation: A comma is added after every
SE

third digit from the right. Answer: b


Explanation: .2 specifies the precision.
8. What will be the output of the following
C

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: https://cse-r17.blogspot.com 44


First Semester MCQ for Regulations 2017

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

M
Python code?
Answer: b

O
print('ab12'.isalnum()) Explanation: Space is not a letter.

C
a) True 7. What will be the output of the following
b) False Python code snippet?

T.
c) None
d) Error print('0xa'.isdigit())

O
Answer: a a) True
Explanation: The string has only letters and b) False
digits.

4. What will be the output of the following


SP
c) None
d) Error

Answer: b
G
Python code?
Explanation: Hexadecimal digits aren’t
considered as digits (a-f).
LO

print('ab,12'.isalnum())

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


b) False Python code snippet?
.B

c) None
d) Error print(''.isdigit())
17

Answer: b a) True
Explanation: The character , is not a letter or b) False
a digit. c) None
d) Error
-R

5. What will be the output of the following


Python code? Answer: b
Explanation: If there are no characters then
SE

print('ab'.isalpha()) False is returned.

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


C

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: https://cse-r17.blogspot.com 45


First Semester MCQ for Regulations 2017

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

M
b) False print('11'.isnumeric())
c) None
a) True

O
d) Error
b) False

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

T.
1. What will be the output of the following Answer: a
Python code snippet? Explanation: All the character are numeric.

O
print('for'.isidentifier()) 5. What will be the output of the following
a) True
b) False
SP
Python code snippet?

print('1.1'.isnumeric())
c) None
G
d) Error a) True
b) False
LO

Answer: a c) None
Explanation: Even keywords are considered d) Error
as valid identifiers.
.B

Answer: b
2. What will be the output of the following Explanation: The character . is not a numeric
Python code snippet? character.
17

print('abc'.islower()) 6. What will be the output of the following


Python code snippet?
a) True
-R

b) False print('125erdE a'.isprintable())


c) None
d) Error a) True
SE

b) False
Answer: a c) None
Explanation: There are no uppercase letters. d) Error
C

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: https://cse-r17.blogspot.com 46


First Semester MCQ for Regulations 2017

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

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

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

C
print('\t'.isspace()) 2. What will be the output of the following
Python code?
a) True

T.
b) False print('GYMK'.lower())
c) None

O
d) Error a) n
b) gymk
Answer: a
Explanation: Tab Spaces are considered as
spaces.
SP
c) rn
d) r

Answer: b
G
9. What will be the output of the following Explanation: Uppercase letters are converted
Python code snippet? to lowercase. The other characters are left
LO

unchanged.
print('HelloWorld'.istitle())
3. What will be the output of the following
a) True
.B

Python code?
b) False
c) None print('''
17

d) Error \tfoo'''.lstrip())

Answer: b a) \tfoo
Explanation: The letter W is uppercased. b) foo
-R

c)   foo
10. What will be the output of the following d) none of the mentioned
Python code snippet?
SE

Answer: b
print('Hello World'.istitle()) Explanation: All leading whitespace is
removed.
C

a) True
b) False 4. What will be the output of the following
c) None Python code?
d) Error
print('xyyzxxyxyy'.lstrip('xyy'))
Answer: a
Explanation: It is in title form. a) error
b) zxxyxyy

Downloaded From: https://cse-r17.blogspot.com 47


First Semester MCQ for Regulations 2017

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

M
b) (‘abef’)
print('xyxxyyzxxy'.lstrip('xyy')) c) (‘ab’, ‘cd’, ‘ef’)

O
d) 2
a) zxxy

C
b) xyxxyyzxxy Answer: c
c) xyxzxxy Explanation: The string is split into three

T.
d) none of the mentioned parts by partition.

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

O
Explanation: All combinations of the Python code?
characters passed as an argument are removed
from the left hand side.

6. What will be the output of the following


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

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


b) (‘ab’, ‘cd’, ‘efcdgh’)
G
Python code?
c) (‘abcdef’, ‘cd’, ‘gh’)
d) error
LO

print('cba'.maketrans('abc', '123'))

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


b) {65: 49, 66: 50, 67: 51} Explanation: The string is partitioned at the
.B

c) 321 point where the separator first appears.


d) 123
10. What will be the output of the following
17

Answer: a Python code?


Explanation: A translation table is returned
by maketrans. print('abcd'.partition('cd'))
-R

7. What will be the output of the following a) (‘ab’, ‘cd’, ”)


Python code? b) (‘ab’, ‘cd’)
c) error
SE

print('a'.maketrans('ABC', '123')) d) none of the mentioned

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


C

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: https://cse-r17.blogspot.com 48


First Semester MCQ for Regulations 2017

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

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

O
Python code snippet? b) abcefd
c) ab1efd

C
print('abef'.partition('cd')) d) ab12ed2

T.
a) (‘abef’) Answer: b
b) (‘abef’, ‘cd’, ”) Explanation: The first substring is not
c) (‘abef’, ”, ”) present in the given string and hence nothing

O
d) error is replaced.

Answer: c
Explanation: The separator is not present in
the string hence the second and the third
SP
6. What will be the output of the following
Python code snippet?
G
elements of the tuple are null strings. print('xyyxyyxyxyxxy'.replace('xy', '12',
0))
LO

3. What will be the output of the following


a) xyyxyyxyxyxxy
Python code snippet?
b) 12y12y1212x12
print('abcdef12'.replace('cd', '12')) c) 12yxyyxyxyxxy
.B

d) xyyxyyxyxyx12
a) ab12ef12
b) abcdef12 Answer: a
17

c) ab12efcd Explanation: The first 0 occurrences of the


d) none of the mentioned given substring are replaced.
-R

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


Explanation: All occurrences of the first Python code snippet?
substring are replaced by the second
SE

print('xyyxyyxyxyxxy'.replace('xy', '12',
substring. 100))

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


Python code snippet?
C

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: https://cse-r17.blogspot.com 49


First Semester MCQ for Regulations 2017

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

M
2. What will be the output of the following
Answer: b Python code snippet?

O
Explanation: The given string is split and a
list of substrings is returned. print('ab\ncd\nef'.splitlines())

C
9. What will be the output of the following a) [‘ab’, ‘cd’, ‘ef’]

T.
Python code snippet? b) [‘ab\n’, ‘cd\n’, ‘ef\n’]
c) [‘ab\n’, ‘cd\n’, ‘ef’]
print('abcdefcdghcd'.split('cd', 0)) d) [‘ab’, ‘cd’, ‘ef\n’]

O
a) [‘abcdefcdghcd’] Answer: a
b) ‘abcdefcdghcd’
c) error
d) none of the mentioned
SP
Explanation: It is similar to calling
split(‘\n’).
G
3. What will be the output of the following
Answer: a Python code snippet?
Explanation: The given string is split at 0
LO

occurances of the specified substring. print('Ab!2'.swapcase())

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


.B

Python code snippet? b) ab12


c) aB!2
print('abcdefcdghcd'.split('cd', -1)) d)
17

a) [‘ab’, ‘ef’, ‘gh’] Answer: c


b) [‘ab’, ‘ef’, ‘gh’, ”] Explanation: Lowercase letters are converted
c) (‘ab’, ‘ef’, ‘gh’)
-R

to uppercase and vice-versa.


d) (‘ab’, ‘ef’, ‘gh’, ”)
4. What will be the output of the following
Answer: b
SE

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
C

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: https://cse-r17.blogspot.com 50


First Semester MCQ for Regulations 2017

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

M
c) Ab Cd-Ef Explanation: The function translate expects a
d) None of the mentioned dictionary of integers. Use maketrans()

O
instead of doing the above.
Answer: c
9. What will be the output of the following

C
Explanation: The first letter of every word is
capitalized. Special symbols terminate a Python code snippet?

T.
word.
print('ab'.zfill(5))
6. What will be the output of the following

O
Python code snippet? a) 000ab
b) 00ab0
print('abcd'.translate('a'.maketrans('ab
c', 'bcd')))

a) bcde
SP
c) 0ab00
d) ab000

Answer: a
G
b) abcd Explanation: The string is padded with zeros
c) error on the left hand side. It is useful for
LO

d) bcdd formatting numbers.

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


.B

Explanation: The output is bcdd since no Python code snippet?


translation is provided for d.
print('+99'.zfill(5))
17

7. What will be the output of the following


Python code snippet? a) 00+99
b) 00099
print('abcd'.translate({97: 98, 98: 99, 9 c) +0099
-R

9: 100})) d) +++99
a) bcde Answer: c
SE

b) abcd Explanation: zeros are filled in between the


c) error first sign and the rest of the string.
d) none of the mentioned
C

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: https://cse-r17.blogspot.com 51


First Semester MCQ for Regulations 2017

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

M
which is present in the random module. The any one of the elements of the iterable is zero
functions sqrt and factorial are a part of the and true if all the elements of the iterable are

O
math module. The print function is a built-in non zero. Hence the output of this function
function which prints a value directly to the will be false.

C
system output.
5. What will be the output of the following

T.
2. What will be the output of the following Python expression?
Python expression?
round(4.5676,2)?

O
round(4.576)
a) 4.5
a) 4.5
b) 5
c) 4
SP
b) 4.6
c) 4.57
d) 4.56
G
d) 4.6
Answer: c
Explanation: The function round is used to
LO

Answer: b
Explanation: This is a built-in function round off the given decimal number to the
which rounds a number to give precision in specified decimal places. In this case, the
decimal digits. In the above case, since the number should be rounded off to two decimal
.B

number of decimal places has not been places. Hence the output will be 4.57.
specified, the decimal number is rounded off
6. What will be the output of the following
17

to a whole number. Hence the output will be


5. Python function?

any([2>8, 4>2, 1>2])


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

a) (x**y)**z a) Error
b) (x**y) / z b) True
c) (x**y) % z
SE

c) False
d) (x**y)*z d) 4>2
Answer: c Answer: b
C

Explanation: The built-in function pow() can Explanation: The built-in function any()
accept two or three arguments. When it takes returns true if any or more of the elements of
in two arguments, they are evaluated as x**y. the iterable is true (non zero), If all the
When it takes in three arguments, they are elements are zero, it returns false.
evaluated as (x**y)%z.
7. What will be the output of the following
4. What will be the output of the following Python function?
Python function?

Downloaded From: https://cse-r17.blogspot.com 52


First Semester MCQ for Regulations 2017

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

M
Explanation: The abs() function prints the used to find the maximum value from among
absolute value of the argument passed. For -3, -4 and false. Since false amounts to the

O
example: abs(-5)=5. Hence, in this case we value zero, hence we are left with min(0, 2, 7)
get abs(5.0)=5.0. Hence the output is 0 (false).

C
8. What will be the output of the following 1. What will be the output of the following

T.
Python function? Python functions?
sum(2,4,6) chr(‘97’)

O
sum([1,2,3]) chr(97)

a) Error, 6
b) 12, Error
c) 12, 6
d) Error, Error
SP
a)
a
G
Error
Answer: a
LO

b)
Explanation: The first function will result in
an error because the function sum() is used to ‘a’
find the sum of iterable numbers. Hence the
.B

outcomes will be Error and 6 respectively. a

9. What will be the output of the following c)


17

Python function?
Error
all(3,0,4.2)
a
-R

a) True
b) False d)
c) Error
SE

Error
d) 0
Error
Answer: c
C

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: https://cse-r17.blogspot.com 53


First Semester MCQ for Regulations 2017

a)

(2.00, 0.50)
2. What will be the output of the following
(2.00, 0.00)
Python function?

complex(1+2j)
b)

(2, 0.5)
a) Error

M
b) 1 (2, 0)
c) 2j

O
d) 1+2j c)

C
Answer: d (2.0, 0.5)
Explanation: The built-in function complex()
(2.0, 0.0)

T.
returns the argument in a complex form.
Hence the output of the function shown above
d)
will be 1+2j.

O
(2, 0.5)
3. What is the output of the function
complex()?
a) 0j
b) 0+0j
SP
(2)

Answer: c
Explanation: See python documentation for
G
c) 0
d) Error the function divmod.
LO

Answer: a
Explanation: The complex function returns
0j if both of the arguments are omitted, that 6. The function complex(‘2-3j’) is valid but
.B

is, if the function is in the form of complex() the function complex(‘2 – 3j’) is invalid.
or complex(0), then the output will be 0j. a) True
b) False
17

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


and ‘b’ are integers is evaluated as: Answer: a
a) (a%b, a//b) Explanation: When converting from a string,
-R

b) (a//b, a%b) the string must not contain any blank spaces
c) (a//b, a*b) around the + or – operator. Hence the
d) (a/b, a%b) function complex(‘2 – 3j’) will result in an
SE

error.
Answer: b
Explanation: The function divmod(a,b) is 7. What will be the output of the following
Python function?
C

evaluated as a//b, a%b, if both ‘a’ and ‘b’ are


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: https://cse-r17.blogspot.com 54


First Semester MCQ for Regulations 2017

Answer: c Error
Explanation: The built-in function
2003
enumerate() accepts an iterable as an
argument. The function shown in the above Answer: b
case returns containing pairs of the numbers Explanation: The output of the first function
given, starting from 0. Hence the output will will be 0.001 and that of the second function
be: [(0, 2), (1,3)]. will be 2000.0. The first function created a
floating point number up to 3 decimal places
8. What will be the output of the following

M
and the second function adds 3 zeros after the
Python functions? given number.

O
x=3
eval('x^2')

C
a) Error 10. Which of the following functions does not
necessarily accept only iterables as

T.
b) 1
c) 9 arguments?
d) 6 a) enumerate()

O
b) all()
Answer: b c) chr()
Explanation: The function eval is use to
evaluate the expression that it takes as an
argument. In the above case, the eval()
SP
d) max()

Answer: c
Explanation: The functions enumerate(), all()
G
function is used to perform XOR operation
between 3 and 2. Hence the output is 1. and max() accept iterables as arguments
whereas the function chr() throws an error on
LO

9. What will be the output of the following receiving an iterable as an argument. Also
Python functions? note that the function chr() accepts only
integer values.
.B

float('1e-003')
float('2e+003') 1. Which of the following functions accepts
only integers as arguments?
17

a) a) ord()
3.00
b) min()
c) chr()
-R

300 d) any()

b) Answer: c
SE

Explanation: The function chr() accepts only


0.001 integers as arguments. The function ord()
accepts only strings. The functions min() and
2000.0
C

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: https://cse-r17.blogspot.com 55


First Semester MCQ for Regulations 2017

b) list(reverse[(l)]) c)
c) reversed(l)
d) list(reversed(l)) A

Error
Answer: d
Explanation: The built-in function reversed() d)
can be used to reverse the elements of a list.
This function accepts only an iterable as an Error
argument. To print the output in the form of a

M
list, we use: list(reversed(l)). The output will Error
be: [4,3,2].
Answer: b

O
3. What will be the output of the following Explanation: The built-in function ord() is

C
Python function? used to return the ASCII value of the alphabet
passed to it as an argument. Hence the first

T.
float(' -12345\n') function results in an error and the output of
the second function is 65.
(Note that the number of blank spaces before

O
the number is 5)
a)   -12345.0 (5 blank spaces before the
number)
b) -12345.0
c) Error
SP
5. What will be the output of the following
Python function?
G
d) -12345.000000000…. (infinite decimal float(‘-infinity’)
float(‘inf’)
places)
LO

a)
Answer: b
Explanation: The function float() will –inf
remove all the blank spaces and convert the
.B

integer to a floating point number. Hence the inf


output will be: -12345.0.
b)
17

4. What will be the output of the following


–infinity
Python function?
-R

inf
ord(65)
ord(‘A’)
c)
SE

a)
Error
A Error
C

65
d)
b)
Error
Error Junk value
65 Answer: a
Explanation: The output of the first function

Downloaded From: https://cse-r17.blogspot.com 56


First Semester MCQ for Regulations 2017

will be –inf and that of the second function throw errors. However the function ord(‘ ‘)
will be inf. does not throw an error because in this case,
we are actually passing a blank space as an
argument. The output of ord(‘ ‘) is 32 (ASCII
value corresponding to blank space).
6. Which of the following functions will not
result in an error when no arguments are 9. What will be the output of the following
passed to it? Python function?
a) min()

M
b) divmod() len(["hello",2, 4, 6])
c) all()

O
d) float() a) 4
b) 3

C
Answer: d c) Error
Explanation: The built-in functions min(), d) 6

T.
max(), divmod(), ord(), any(), all() etc throw
an error when no arguments are passed to Answer: a
them. However there are some built-in Explanation: The function len() returns the

O
functions like float(), complex() etc which do length of the number of elements in the
not throw an error when no arguments are iterable. Therefore the output of the function
passed to them. The output of float() is 0.0.

7. What will be the output of the following


SP
shown above is 4.

10. What will be the output of the following


G
Python function? Python function?
LO

oct(7)
hex(15)
oct(‘7’)
a) f a)
b) 0xF
.B

c) 0Xf Error
d) 0xf
17

07
Answer: d
Explanation: The function hex() is used to b)
convert the given argument into its
-R

0o7
hexadecimal representation, in lower case.
Hence the output of the function hex(15) is Error
0xf.
SE

c)
8. Which of the following functions does not
throw an error? 0o7
C

a) ord()
b) ord(‘ ‘) Error
c) ord(”)
d)
d) ord(“”)
07
Answer: b
Explanation: The function ord() accepts a 0o7
character. Hence ord(), ord(”) and ord(“”)

Downloaded From: https://cse-r17.blogspot.com 57


First Semester MCQ for Regulations 2017

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

M
c)
TOPIC 3.3.2 USER DEFINED

O
FUNCTIONS Hello

Hello

C
1. Which of the following is the use of
function in python? d) None of the mentioned

T.
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity Answer: a

O
for your application Explanation: Functions are defined using the
c) you can’t also create your own functions def keyword. After this keyword comes an
d) All of the mentioned

Answer: a
SP
identifier name for the function, followed by
a pair of parentheses which may enclose
some names of variables, and by the final
colon that ends the line. Next follows the
Explanation: Functions are reusable pieces
G
of programs. They allow you to give a name block of statements that are part of this
to a block of statements, allowing you to run function.
LO

that block using the specified name anywhere


in your program and any number of times. 1. def sayHello():
2. print('Hello World!') # block b
.B

2. Which keyword is used for function?


elonging to the function
a) Fun
b) Define 3. # End of function #
17

c) Def
d) Function 4.
5. sayHello() # call the function
-R

Answer: c
Explanation: None.
6. sayHello() # call the function agai
n
SE

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

2. print('Hello World!')
1. def printMax(a, b):
2. if a > b:
3. sayHello()
4. sayHello() 3. print(a, 'is maximum')

4. elif a == b:
a)

Downloaded From: https://cse-r17.blogspot.com 58


First Semester MCQ for Regulations 2017

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

M
c) 4 is maximum Answer: a
d) None of the mentioned Explanation: The first time that we print the

O
value of the name x with the first line in the
Answer: c function’s body, Python uses the value of the

C
Explanation: Here, we define a function parameter declared in the main block, above
called printMax that uses two parameters the function definition.

T.
called a and b. We find out the greater Next, we assign the value 2 to x. The name x
number using a simple if..else statement and is local to our function. So, when we change

O
then print the bigger number. the value of x in the function, the x defined in
the main block remains unaffected.
5. What will be the output of the following
Python code?

1. x = 50
SP
With the last print function call, we display
the value of x as defined in the main block,
thereby confirming that it is actually
unaffected by the local assignment within the
G
previously called function.
2. def func(x):
LO

6. What will be the output of the following


3. print('x is', x)
Python code?
4. x = 2
.B

1. x = 50
5. print('Changed local x to', x)
2. def func():
17

6. func(x)
3. global x
7. print('x is now', x)
4. print('x is', x)
-R

a)
5. x = 2
x is 50
6.
SE

print('Changed global x to', x)


Changed local x to 2
7. func()
x is now 50
8. print('Value of x is', x)
C

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: https://cse-r17.blogspot.com 59


First Semester MCQ for Regulations 2017

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

M
use default values in case the user does not
x is 50
want to provide values for them. This is done
with the help of default argument values. You

O
Changed global x to 50
can specify default argument values for
Value of x is 50 parameters by appending to the parameter

C
name in the function definition the
d) None of the mentioned assignment operator (=) followed by the

T.
default value.
Answer: b The function named say is used to print a
Explanation: The global statement is used to

O
string as many times as specified. If we don’t
declare that x is a global variable – hence, supply a value, then by default, the string is
when we assign a value to x inside the
function, that change is reflected when we use
the value of x in the main block.
SP
printed just once. We achieve this by
specifying a default argument value of 1 to
the parameter times.
G
In the first usage of say, we supply only the
7. What will be the output of the following
string and it prints the string once. In the
Python code?
LO

second usage of say, we supply both the


string and an argument 5 stating that we want
1. def say(message, times = 1):
to say the string message 5 times.
2. print(message * times)
.B

3. say('Hello')
8. What will be the output of the following
17

4. say('World', 5) Python code?


a) 1. def func(a, b=5, c=10):
-R

Hello 2. print('a is', a, 'and b is', b,


'and c is', c)
WorldWorldWorldWorldWorld
SE

3.
b)
4. func(3, 7)
C

Hello
5. func(25, c = 24)
World 5
6. func(c = 50, a = 100)
c)
a)
Hello
a is 7 and b is 3 and c is 10
World,World,World,World,World

Downloaded From: https://cse-r17.blogspot.com 60


First Semester MCQ for Regulations 2017

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:

M
a is 50 and b is 100 and c is 5
3. return x
c)

O
4. elif x == y:
a is 3 and b is 7 and c is 10

C
5. return 'The numbers are equ
a is 25 and b is 5 and c is 24 al'

T.
a is 100 and b is 5 and c is 50 6. else:

O
d) None of the mentioned 7. return y

8.
Answer: c
Explanation: If you have some functions
with many parameters and you want to
SP 9. print(maximum(2, 3))
G
specify only some of them, then you can give a) 2
values for such parameters by naming them – b) 3
LO

this is called keyword arguments – we use the c) The numbers are equal
name (keyword) instead of the position d) None of the mentioned
(which we have been using all along) to
specify the arguments to the function. Answer: b
.B

The function named func has one parameter Explanation: The maximum function returns
without a default argument value, followed the maximum of the parameters, in this case
by two parameters with default argument the numbers supplied to the function. It uses a
17

values. simple if..else statement to find the greater


value and then returns that value.
In the first usage, func(3, 7), the parameter a
-R

gets the value 3, the parameter b gets the 10. Which of the following is a feature of
value 7 and c gets the default value of 10. DocString?
a) Provide a convenient way of associating
SE

In the second usage func(25, c=24), the documentation with Python modules,
variable a gets the value of 25 due to the functions, classes, and methods
position of the argument. Then, the parameter b) All functions should have a docstring
C

c gets the value of 24 due to naming i.e. c) Docstrings can be accessed by the __doc__
keyword arguments. The variable b gets the attribute on objects
default value of 5. d) All of the mentioned

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: https://cse-r17.blogspot.com 61


First Semester MCQ for Regulations 2017

are an important tool that you should make 5. Which of the following is the use of id()
use of since it helps to document the program function in python?
better and makes it easier to understand. a) Id returns the identity of the object
b) Every object doesn’t have a unique id
1. Which are the advantages of functions in c) All of the mentioned
python? d) None of the mentioned
a) Reducing duplication of code
b) Decomposing complex problems into Answer: a
simpler pieces Explanation: Each object in Python has a

M
c) Improving clarity of the code unique id. The id() function returns the
d) All of the mentioned object’s id.

O
Answer: d 6. Which of the following refers to

C
Explanation: None. mathematical function?
a) sqrt

T.
2. What are the two main types of functions? b) rhombus
a) Custom function c) add
b) Built-in function & User defined function d) rhombus

O
c) User function
d) System function Answer: a

Answer: b
Explanation: Built-in functions and user
SP
Explanation: Functions that are always
available for usage, functions that are
contained within external modules, which
G
defined ones. The built-in functions are part must be imported and functions defined by a
of the Python language. Examples are: dir(), programmer with the def keyword.
LO

len() or abs(). The user defined functions are Eg: math import sqrt
functions created with the def keyword. A sqrt() function is imported from the math
module.
3. Where is function defined?
.B

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


b) Class Python code?
17

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

Answer: d 2. return x * x * x
-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: https://cse-r17.blogspot.com 62


First Semester MCQ for Regulations 2017

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

M
32
2. return c * 9/5 + 32

O
b)
3. print C2F(100)

C
9
4. print C2F(0)
27

T.
a)
c)
212

O
567
32

b) SP
98

d) None of the mentioned


314
G
Answer: b
24
LO

Explanation: The arguments in Python


c) functions may have implicit values. An
implicit value is used, if no value is provided.
567 Here we created a power function. The
.B

function has one argument with an implicit


98 value. We can call the function with one or
two arguments.
17

d) None of the mentioned


10. What will be the output of the following
Answer: a Python code?
-R

Explanation: The code shown above is used


to convert a temperature in degree celsius to 1. def sum(*args):
fahrenheit.
SE

2. '''Function returns the sum


9. What will be the output of the following
Python code? 3. of all values'''
C

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: https://cse-r17.blogspot.com 63


First Semester MCQ for Regulations 2017

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

M
a) 48
b) b) 14
c) 64

O
6
d) None of the mentioned

C
100
Answer: a
c) Explanation: The lambda keyword creates an

T.
anonymous function. The x is a parameter,
123 that is passed to the lambda function. The

O
parameter is followed by a colon character.
12345
The code next to the colon is the expression
d) None of the mentioned

Answer: a
SP
that is executed, when the lambda function is
called. The lambda function is assigned to the
z variable.
G
Explanation: We use the * operator to The lambda function is executed. The number
indicate, that the function will accept 8 is passed to the anonymous function and it
LO

arbitrary number of arguments. The sum() returns 48 as the result. Note that z is not a
function will return the sum of all arguments. name for this function. It is only a variable to
The first string in the function body is called which the anonymous function was assigned.
the function documentation string. It is used
.B

to document the function. The string must be 3. What will be the output of the following
in triple quotes. Python code?
17

1. Python supports the creation of anonymous 1. lamb = lambda x: x ** 3


functions at runtime, using a construct called 2. print(lamb(5))
__________
-R

a) lambda a) 15
b) pi b) 555
c) anonymous
SE

c) 125
d) none of the mentioned d) None of the mentioned
Answer: a Answer: c
C

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: https://cse-r17.blogspot.com 64


First Semester MCQ for Regulations 2017

Answer: b 5.
Explanation: lambda definition does not
include a return statement. it always contains 6. who = writer()
an expression which is returned. Also note
7. who('Arthur')
that we can put a lambda definition anywhere
a function is expected. We don’t have to a) Arthur Sir
assign it to a variable at all. b) Sir Arthur
c) Arthur
5. Lambda is a statement.

M
d) None of the mentioned
a) True
b) False Answer: b

O
Explanation: None.
Answer: b

C
Explanation: lambda is an anonymous 9. What will be the output of the following
function in Python. Hence this statement is Python code?

T.
false.
1. L = [lambda x: x ** 2,
6. Lambda contains block of statements.

O
a) True 2. lambda x: x ** 3,
b) False

Answer: b
Explanation: None.
SP 3.
4.
lambda x: x ** 4]
G
5. for f in L:
7. What will be the output of the following
LO

Python code? 6. print(f(3))

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


.B

2. f(2, 30, 400) 27

a) 432 81
17

b) 24000
c) 430 343
d) No output
b)
-R

Answer: a 6
Explanation: None.
SE

9
8. What will be the output of the following
Python code? 12
C

1. def writer(): c)

2. title = 'Sir' 9

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


' + x)
81
4. return name

Downloaded From: https://cse-r17.blogspot.com 65


First Semester MCQ for Regulations 2017

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

M
y) d) An exception is thrown
2. min(101*99, 102*98)

O
Answer: c
a) 9997 Explanation: Any change made in to an

C
b) 9999 immutable data type in a function isn’t
c) 9996 reflected outside the function.

T.
d) None of the mentioned
4. What will be the output of the following
Python code?

O
Answer: c
Explanation: None.
def a(b):

1. What is a variable defined outside a


function referred to as?
SP b = b + [5]

c = [1, 2, 3, 4]
a) A static variable a(c)
G
b) A global variable print(len(c))
c) A local variable
LO

a) 4
d) An automatic variable
b) 5
Answer: b c) 1
d) An exception is thrown
.B

Explanation: The value of a variable defined


outside all function definitions is referred to
Answer: b
as a global variable and can be used by
17

Explanation: Since a list is mutable, any


multiple functions of the program.
change made in the list in the function is
2. What is a variable defined inside a function reflected outside the function.
-R

referred to as?
5. What will be the output of the following
a) A global variable
Python code?
b) A volatile variable
SE

c) A local variable a=10


d) An automatic variable b=20
def change():
Answer: c global b
C

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: https://cse-r17.blogspot.com 66


First Semester MCQ for Regulations 2017

10 a) Integer
b) Tuple
56
c) Dictionary
b) d) An exception is thrown

45 Answer: b
Explanation: The parameter two is a variable
56 parameter and consists of (2,3,4). Hence the
data type is tuple.

M
c)
8. If a function doesn’t have a return

O
10 statement, which of the following does the
20 function return?

C
a) int
d) Syntax Error b) null

T.
c) None
Answer: a d) An exception is thrown without the return
statement

O
Explanation: The statement “global b”
allows the global value of b to be accessed
Answer: c
and changed. Whereas the variable a is local
and hence the change isn’t reflected outside
the function.
SP
Explanation: A function can exist without a
return statement and returns None if the
function doesn’t have a return statement.
G
6. What will be the output of the following
Python code? 9. What will be the output of the following
LO

Python code?
def change(i = 1, j = 2):
i = i + j def display(b, n):
j = j + 1 while n > 0:
.B

print(i, j) print(b,end="")
change(j = 1, i = 2) n=n-1
display('z',3)
17

a) An exception is thrown because of


conflicting values a) zzz
b) 1 2 b) zz
-R

c) 3 3 c) An exception is executed
d) 3 2 d) Infinite loop
SE

Answer: d Answer: a
Explanation: The values given during Explanation: The loop runs three times and
function call is taken into consideration, that ‘z’ is printed each time.
is, i=2 and j=1.
C

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: https://cse-r17.blogspot.com 67


First Semester MCQ for Regulations 2017

a) String Answer: b
b) Tuple Explanation: Lists are passed by reference.
c) Dictionary
d) An exception is thrown 4. How are keyword arguments specified in
the function heading?
Answer: c a) one-star followed by a valid identifier
Explanation: b combines the remaining b) one underscore followed by a valid
parameters into a dictionary. identifier
c) two stars followed by a valid identifier

M
d) two underscores followed by a valid
TOPIC 3.3 ARGUMENTS AND identifier

O
PARAMETERS
Answer: c

C
1. What is the type of each element in Explanation: Refer documentation.
sys.argv?

T.
a) set 5. How many keyword arguments can be
b) list passed to a function in a single function call?
a) zero

O
c) tuple
d) string b) one
c) zero or more
Answer: d
Explanation: It is a list of strings.
SP
d) one or more

Answer: c
G
2. What is the length of sys.argv? Explanation: Zero keyword arguments may
a) number of arguments be passed if all the arguments have default
LO

b) number of arguments + 1 values.


c) number of arguments – 1
d) none of the mentioned 6. What will be the output of the following
Python code?
.B

Answer: b
def foo(fname, val):
Explanation: The first argument is the name
print(fname(val))
17

of the program itself. Therefore the length of foo(max, [1, 2, 3])


sys.argv is one more than the number foo(min, [1, 2, 3])
arguments.
-R

a) 3 1
3. What will be the output of the following b) 1 3
Python code? c) error
SE

d) none of the mentioned


def foo(k):
k[0] = 1 Answer: a
q = [0]
Explanation: It is possible to pass function
C

foo(q)
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: https://cse-r17.blogspot.com 68


First Semester MCQ for Regulations 2017

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]
d) [1] [1, 2] [1, 2, 3]

M
Explanation: It is possible to read the value
of a global variable directly.
Answer: b

O
8. What will be the output of the following Explanation: When a list is a default value,
Python code? the same list will be reused.

C
1. What will be the output of the following

T.
def foo():
total += 1 Python code?
return total
total = 0 def foo(k):

O
print(foo()) k = [1]
q = [0]
a) 0
b) 1
c) error
SP
foo(q)
print(q)

a) [0]
G
d) none of the mentioned
b) [1]
c) [1, 0]
LO

Answer: c
Explanation: It is not possible to change the d) [0, 1]
value of a global variable without explicitly
Answer: a
specifying it.
.B

Explanation: A new list object is created in


9. What will be the output of the following the function and the reference is lost. This can
Python code? be checked by comparing the id of k before
17

and after k = [1].


def foo(x):
x = ['def', 'abc'] 2. How are variable length arguments
-R

return id(x) specified in the function heading?


q = ['abc', 'def'] a) one star followed by a valid identifier
print(id(q) == foo(q))
b) one underscore followed by a valid
SE

a) True identifier
c) two stars followed by a valid identifier
b) False
d) two underscores followed by a valid
c) None
identifier
C

d) Error
Answer: a
Answer: b
Explanation: A new object is created in the Explanation: Refer documentation.
function. 3. Which module in the python standard
library parses options received from the
10. What will be the output of the following
Python code? command line?

Downloaded From: https://cse-r17.blogspot.com 69


First Semester MCQ for Regulations 2017

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?

M
4. What is the type of sys.argv? def foo(x):
x[0] = ['def']
a) set
x[1] = ['abc']

O
b) list return id(x)
c) tuple q = ['abc', 'def']

C
d) string print(id(q) == foo(q))

T.
Answer: b a) True
Explanation: It is a list of elements. b) False
c) None

O
5. What is the value stored in sys.argv[0]? d) Error
a) null
b) you cannot access it
c) the program’s name
d) the first argument
SP
Answer: a
Explanation: The same object is modified in
the function.
G
Answer: c 9. Where are the arguments received from the
LO

Explanation: Refer documentation. command line stored?


a) sys.argv
6. How are default arguments specified in the b) os.argv
function heading? c) argv
.B

a) identifier followed by an equal to sign and d) none of the mentioned


the default value
17

b) identifier followed by the default value Answer: a


within backticks (“) Explanation: Refer documentation.
c) identifier followed by the default value
within square brackets ([]) 10. What will be the output of the following
-R

d) identifier Python code?

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


SE

x.append(x.append(i))
Explanation: Refer documentation. return x
for i in range(3):
7. How are required arguments specified in y = foo(i)
C

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: https://cse-r17.blogspot.com 70


First Semester MCQ for Regulations 2017

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

M
def f1(): Answer: a

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

C
x=12
f1() incremented by one and printed. Hence the
output of the code shown above is 13.

T.
a) Error
b) 12 4. What will be the output of the following

O
c) 15 Python code?
d) 1512
def f1():
Answer: c
Explanation: In the code shown above, x=15
SP global x
x+=1
print(x)
is a local variable whereas x=12 is a global
G
x=12
variable. Preference is given to local variable print("x")
over global variable. Hence the output of the
LO

code shown above is 15. a) Error


b) 13
2. What will be the output of the following c)
.B

Python code?
13
def f1():
x
17

x=100
print(x)
x=+1 d) x
f1()
-R

Answer: d
a) Error Explanation: In the code shown above, the
b) 100 variable ‘x’ is declared as global within the
SE

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
C

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: https://cse-r17.blogspot.com 71


First Semester MCQ for Regulations 2017

x+=1 a = "world"
print(x) f()
f1(15) print(a)
print("hello")
a)
a) error
b) hello hello
c) 16
hello
d)

M
world
16
b)

O
hello

Answer: a world

C
Explanation: The code shown above will
hello

T.
result in an error because ‘x’ is a global
variable. Had it been a local variable, the hello
output would be: 16

O
hello c)

6. What will be the output of the following


SP hello

world
G
Python code? world
LO

x=12 d)
def f1(a,b=x):
print(a,b) world
x=15
f1(4)
.B

hello

a) Error world
b) 12 4
17

c) 4 12 Answer: b
d) 4 15 Explanation: Since the variable ‘a’ has been
explicitly specified as a global variable, the
-R

Answer: c value of a passed to the function is ‘world’.


Explanation: At the time of leader Hence the output of this code is:
processing, the value of ‘x’ is 12. It is not world
SE

modified later. The value passed to the hello


function f1 is 4. Hence the output of the code hello
shown above is 4 12.
C

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: https://cse-r17.blogspot.com 72


First Semester MCQ for Regulations 2017

return b error
print(f1(2,[3,4]))
b)
a) [3,2,4]
b) [2,3,4] inner
c) Error
error
d) [3,4,2]
c)
Answer: d

M
Explanation: In the code shown above, the outer
integer 2 is appended to the list [3,4]. Hence

O
the output of the code is [3,4,2]. Both the inner
variables a and b are local variables.
d) error

C
9. What will be the output of the following
Answer: a

T.
Python code?
Explanation: The error will be caused due to
def f(p, q, r): the statement f1(1) because the function is

O
global s nested. If f1(1) had been called inside the
p = 10
function, the output would have been
q = 20
r = 30
s = 40
print(p,q,r,s)
SP
different and there would be no error.

11. What will be the output of the following


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

a) 1 2 3 4 def f1():
b) 5 10 15 4 global x
c) 10 20 30 40 x = 4
def f2(a,b):
.B

d) 5 10 15 40 global x
return a+b+x
Answer: c f1()
17

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


combination of local and global variables. print(total)
The output of this code is: 10 20 30 40
a) Error
-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")
print(a,x)
variable ‘x’ has been declared as a global
f(3) variable under both the functions f1 and f2.
f1(1) The value returned is a+b+x = 1+2+4 = 7.

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


Python code?
outer

Downloaded From: https://cse-r17.blogspot.com 73


First Semester MCQ for Regulations 2017

x=100 Answer: c
def f1(): Explanation: Both the functions, that is,
global x
x=90
globals() and locals() return value of the data
def f2(): structure dictionary.
global x
x=80 2. What will be the output of the following
print(x) Python code?
a) 100 x=1

M
b) 90 def cg():
c) 80 global x
x=x+1

O
d) Error
cg()
x

C
Answer: a
Explanation: The output of the code shown a) 2

T.
above is 100. This is because the variable ‘x’ b) 1
has been declared as global within the c) 0
functions f1 and f2. d) Error

O
13. Read the following Python code carefully Answer: a
and point out the global variables?

y, z = 1, 2
SP
Explanation: Since ‘x’ has been declared a
global variable, it can be modified very easily
within the function. Hence the output is 2.
G
def f():
global x
x = y+z 3. On assigning a value to a variable inside a
LO

function, it automatically becomes a global


a) x variable.
b) y and z a) True
c) x, y and z b) False
.B

d) Neither x, nor y, nor z


Answer: b
17

Answer: c Explanation: On assigning a value to a


Explanation: In the code shown above, x, y variable inside a function, t automatically
and z are global variables inside the function becomes a local variable. Hence the above
f. y and z are global because they are not statement is false.
-R

assigned in the function. x is a global variable


because it is explicitly specified so in the 4. What will be the output of the following
Python code?
SE

code. Hence, x, y and z are global variables.

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


def f(a): print(a)+e
returned by the functions globals() and
C

f("bitter")
locals()?
a) list a) error
b) set b)
c) dictionary
d) tuple butter

error

Downloaded From: https://cse-r17.blogspot.com 74


First Semester MCQ for Regulations 2017

c) def f(): x=4


x=1
bitter f()
x
error
a) Error
d) bitterbutter b) 4
c) Junk value
Answer: c d) 1

M
Explanation: The output of the code shown
above will be ‘bitter’, followed by an error. Answer: d
The error is because the operand ‘+’ is Explanation: In the code shown above, when

O
unsupported on the types used above. we call the function f, a new namespace is
created. The assignment x=4 is performed in

C
5. What happens if a local variable exists with the local namespace and does not affect the
the same name as the global variable you global namespace. Hence the output is 1.

T.
want to access?
a) Error 8. ______________ returns a dictionary of

O
b) The local variable is shadowed the module namespace.
c) Undefined behavior ________________ returns a dictionary of
d) The global variable is shadowed

Answer: d
SP
the current namespace.
a)

locals()
Explanation: If a local variable exists with
G
the same name as the local variable that you
globals()
want to access, then the global variable is
LO

shadowed. That is, preference is given to the b)


local variable.
locals()
.B

6. What will be the output of the following


Python code? locals()
17

a=10 c)
globals()['a']=25
print(a) globals()
-R

a) 10 locals()
b) 25
c) Junk value d)
SE

d) Error
globals()
Answer: b globals()
C

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: https://cse-r17.blogspot.com 75


First Semester MCQ for Regulations 2017

Sanfoundry Global Education & Learning 4. Fill in the line of the following Python
Series – Python. code for calculating the factorial of a number.

def fact(num):
TOPIC 3.5 RECURSION if num == 0:
return 1
else:
1. Which is the most appropriate definition return _____________________
for recursion?
a) A function that calls itself a) num*fact(num-1)

M
b) A function execution instance that calls b) (num-1)*(num-2)
another execution instance of the same c) num*(num-1)

O
function d) fact(num)*fact(num-1)
c) A class method that calls another class

C
method Answer: a
d) An in-built method that is automatically Explanation: Suppose n=5 then, 5*4*3*2*1

T.
called is returned which is the factorial of 5.

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

O
Explanation: The appropriate definition for a Python code?
recursive function is a function execution
instance that calls another execution instance
of the same function either directly or
indirectly.
SP
def test(i,j):
if(i==0):
return j
G
else:
return test(i-1,i+j)
2. Only problems that are recursively defined print(test(4,7))
LO

can be solved using recursion.


a) True a) 13
b) False b) 7
c) Infinite loop
.B

Answer: b d) 17
Explanation: There are many other problems
17

can also be solved using recursion. Answer: d


Explanation: The test(i-1,i+j) part of the
3. Which of these is false about recursion? function keeps calling the function until the
a) Recursive function can be replaced by a base condition of the function is satisfied.
-R

non-recursive function
b) Recursive functions usually take more 6. What will be the output of the following
Python code?
SE

memory space than non-recursive function


c) Recursive functions run faster than non-
recursive function l=[]
def convert(b):
d) Recursion makes programs easier to
C

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: https://cse-r17.blogspot.com 76


First Semester MCQ for Regulations 2017

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

M
7. What is tail recursion? Answer: d
a) A recursive function that has two base Explanation: A recursive function needn’t

O
cases have a return value.
b) A function where the recursive functions

C
leads to an infinite loop 10. What will be the output of the following
c) A recursive function where the function Python code?

T.
doesn’t return anything and just prints the
values def fun(n):
if (n > 100):
d) A function where the recursive call is the

O
return n - 5
last thing executed by the function return fun(fun(n+11));

Answer: d
Explanation: A recursive function is tail
recursive when recursive call is executed by
SP
print(fun(45))

a) 50
G
the function in the last. b) 100
c) 74
LO

8. Observe the following Python code? d) Infinite loop

def a(n): Answer: b


if n == 0: Explanation: The fun(fun(n+11)) part of the
.B

return 0
else:
code keeps executing until the value of n
return n*a(n - 1) becomes greater than 100, after which n-5 is
17

def b(n, tot): returned and printed.


if n == 0:
return tot 11. Recursion and iteration are the same
else: programming approach.
-R

return b(n-2, tot-2)


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

b) Both a() and b() are tail recursive


c) b() is tail recursive but a() isn’t Answer: b
d) a() is tail recursive but b() isn’t Explanation: In recursion, the function calls
itself till the base condition is reached
C

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: https://cse-r17.blogspot.com 77


First Semester MCQ for Regulations 2017

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
d) Sequence generation is easier than a nested
DICTIONARIES

T.
iteration
TOPIC 4.1 LISTS ( LIST
Answer: c

O
Explanation: Recursive calls take up a lot of
OPERATIONS, LIST SLICES,
memory and time as memory is taken up each LIST METHODS, LIST LOOP,
time the function is called.

14. Which of these is not true about


SP
MUTABILITY, ALIASING,
CLONING LISTS, LIST
PARAMETERS)
G
recursion?
a) It’s easier to code some real-world
LO

problems using recursion than non-recursive 1. Which of the following commands will
equivalent create a list?
b) Recursive functions are easy to debug a) list1 = list()
c) Recursive calls take up a lot of memory b) list1 = []
.B

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


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

Answer: b Answer: d
Explanation: Recursive functions may be Explanation: Execute in the shell to verify
hard to debug as the logic behind recursion
-R

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: https://cse-r17.blogspot.com 78


First Semester MCQ for Regulations 2017

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

M
a) 2445 Explanation: Slicing is allowed in lists just
b) 133 as in the case of strings.

O
c) 12454
d) 123 9. Suppose list1 is [2, 33, 222, 14, 25], What

C
is list1[-1]?
Answer: c a) Error

T.
Explanation: Max returns the maximum b) None
element in the list. c) 25
d) 2

O
5. Suppose list1 is [3, 5, 25, 1, 3], what is
min(list1)? Answer: c
a) 3
b) 5
c) 25
SP
Explanation: -1 corresponds to the last index
in the list.
G
d) 1 10. Suppose list1 is [2, 33, 222, 14, 25], What
is list1[:-1]?
LO

Answer: d a) [2, 33, 222, 14]


Explanation: Min returns the minimum b) Error
element in the list. c) 25
d) [25, 14, 222, 33, 2]
.B

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


sum(list1)? Answer: a
17

a) 1 Explanation: Execute in the shell to verify.


b) 9
c) 15 1. What will be the output of the following
d) Error Python code?
-R

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


Explanation: Sum returns the sum of all on', 'Daman']
SE

elements in the list.


2. >>>print(names[-1][-1])
7. To shuffle the list(say list1) what function
a) A
C

do we use?
a) list1.shuffle() b) Daman
b) shuffle(list1) c) Error
c) random.shuffle(list1) d) n
d) random.shuffleList(list1)
Answer: d
Answer: c Explanation: Execute in the shell to verify.
Explanation: Execute in the shell to verify.

Downloaded From: https://cse-r17.blogspot.com 79


First Semester MCQ for Regulations 2017

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]

M
4. b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]

O
5. names2[0] = 'Alice' d) [0.0, 0.5, 1.0, 1.5, 2.0]
6. names3[1] = 'Bob'

C
Answer: c
7. Explanation: Execute in the shell to verify.

T.
8. sum = 0 5. What will be the output of the following
Python code?

O
9. for ls in (names1, names2, names3):
1. >>>list1 = [11, 2, 23]
10.
11.
if ls[0] == 'Alice':

sum += 1
SP 2. >>>list2 = [11, 2, 2]
3. >>>list1 < list2 is
G
12. if ls[1] == 'Bob':
a) True
LO

13. sum += 10
b) False
14. c) Error
d) None
.B

15. print sum


Answer: b
a) 11 Explanation: Elements are compared one by
17

b) 12 one.
c) 21
d) 22 6. To add a new element to a list we use
-R

which command?
Answer: b a) list1.add(5)
Explanation: When assigning names1 to b) list1.append(5)
SE

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
C

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: https://cse-r17.blogspot.com 80


First Semester MCQ for Regulations 2017

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

M
b) list1.remove(hello) 3. Suppose listExample is [3, 4, 5, 20, 5, 25,
c) list1.removeAll(“hello”) 1, 3], what is list1 after listExample.pop(1)?

O
d) list1.removeOne(“hello”) a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]

C
Answer: a c) [3, 5, 20, 5, 25, 1, 3]
Explanation: Execute in the shell to verify. d) [1, 3, 4, 5, 20, 5, 25]

T.
9. Suppose list1 is [3, 4, 5, 20, 5], what is Answer: c
list1.index(5)? Explanation: pop() removes the element at

O
a) 0 the position specified in the parameter.
b) 1
c) 4
d) 2 SP
4. Suppose listExample is [3, 4, 5, 20, 5, 25,
1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
G
Answer: d b) [1, 3, 3, 4, 5, 5, 20, 25]
Explanation: Execute help(list.index) to get c) [3, 5, 20, 5, 25, 1, 3]
LO

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

10. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], Answer: a


what is list1.count(5)? Explanation: pop() by default will remove
.B

a) 0 the last element.


b) 4
17

c) 1 5. What will be the output of the following


d) 2 Python code?

Answer: d 1. >>>"Welcome to Python".split()


-R

Explanation: Execute in the shell to verify.


a) [“Welcome”, “to”, “Python”]
1. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], b) (“Welcome”, “to”, “Python”)
SE

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

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: https://cse-r17.blogspot.com 81


First Semester MCQ for Regulations 2017

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

M
Python code? Python code?

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

C
2. max = myList[0] 2. >>>list2 = list1
3. indexOfMax = 0 3. >>>list1[0] = 4

T.
4. for i in range(1, len(myList)): 4. >>>print(list2)

O
5. if myList[i] > max: a) [1, 3]
b) [4, 3]
6.
7.
max = myList[i]

indexOfMax = i
SP
c) [1, 4]
d) [1, 3, 4]
G
8. Answer: b
Explanation: Lists should be copied by
LO

9. >>>print(indexOfMax) executing [:] operation.


a) 1 10. What will be the output of the following
b) 2 Python code?
.B

c) 3
d) 4 1. def f(values):
17

Answer: a 2. values[0] = 44
Explanation: First time the highest number is
encountered is at index 1. 3.
-R

4. v = [1, 2, 3]
8. What will be the output of the following
Python code? 5. f(v)
SE

1. myList = [1, 2, 3, 4, 5, 6] 6. print(v)


2. for i in range(1, 6):
C

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: https://cse-r17.blogspot.com 82


First Semester MCQ for Regulations 2017

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.

M
a) None
5. f(1) b) a

O
c) b
6. f(2) d) c

C
7. v = f(3) Answer: d

T.
8. print(v) Explanation: List Comprehension are a
shorthand for creating new lists.

O
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3] 4. What will be the output of the following
Python code?
c) [1, 2, 3]
d) 1 2 3

Answer: c
SP 1. numbers = [1, 2, 3, 4]
G
2.
Explanation: Execute in the shell to verify
3. numbers.append([5,6,7,8])
LO

2. What will be the output of the following


Python code? 4.

1. names1 = ['Amir', 'Bala', 'Chales'] 5. print(len(numbers))


.B

2. a) 4
b) 5
17

3. if 'amir' in names1: c) 8
d) 12
4. print(1)
-R

5. else: Answer: b
Explanation: A list is passed in append so the
6. print(2) length is 5.
SE

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

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: https://cse-r17.blogspot.com 83


First Semester MCQ for Regulations 2017

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

M
8. print(increment_items(values, 2))
a) 2 9. print(values)

O
b) 4
c) 5 a)

C
d) 8
None

T.
Answer: d
Explanation: + appends all the elements [3, 4, 5]

O
individually into a new list.
b)
7. What will be the output of the following
Python code?

1. def addItem(listParam):
SP None

[1, 2, 3]
G
c)
2. listParam += [1]
LO

[3, 4, 5]
3.
[1, 2, 3]
4. mylist = [1, 2, 3, 4]
.B

d)
5. addItem(mylist)
[3, 4, 5]
17

6. print(len(mylist))
None
a) 1
b) 4 Answer: a
-R

c) 5 Explanation: Execute in the shell to verify.


d) 8
SE

Answer: c
Explanation: + will append the element to 9. What will be the output of the following
the list. Python code?
C

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: https://cse-r17.blogspot.com 84


First Semester MCQ for Regulations 2017

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]]
8. i = i + 3
c) [1, 2, 3, 4, 5, 6, 7, 8, 9]
d) [0, 1, 2, 1, 2, 3, 2, 3, 4]
9. return result
Answer: b

M
a) Return a list containing every third item Explanation: Execute in the shell to verify.
from L starting at index 0

O
b) Return an empty list 2. How many elements are in m?
c) Return a list containing every third index

C
from L starting at index 0 1. m = [[x, y] for x in range(0, 4) fo
r y in range(0, 4)]
d) Return a list containing the items from L

T.
starting from index 0, omitting every third a) 8
item b) 12

O
c) 16
Answer: a
d) 32
Explanation: Run the code to get a better
understanding with many arguments.

10. What will be the output of the following


SP
Answer: c
Explanation: Execute in the shell to verify.
G
Python code? 3. What will be the output of the following
Python code?
LO

1. veggies = ['carrot', 'broccoli', 'p


otato', 'asparagus']
1. values = [[3, 4, 5, 1], [33, 6, 1,
2. veggies.insert(veggies.index('brocc 2]]
.B

oli'), 'celery')
2.
3. print(veggies)
3. v = values[0][0]
17

a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, 4. for row in range(0, len(values)):


‘asparagus’] Correct 1.00
b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’]
-R

5. for column in range(0, len(valu


es[row])):
c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’,
6. if v < values[row][column]:
SE

‘asparagus’]
7. v = values[row][column]
d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’,
‘asparagus’] 8.
C

Answer: a 9. print(v)
Explanation: Execute in the shell to verify.
a) 3
1. What will be the output of the following b) 5
Python code? c) 6
d) 33

Downloaded From: https://cse-r17.blogspot.com 85


First Semester MCQ for Regulations 2017

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.

M
2.
6. What will be the output of the following
3. v = values[0][0] Python code?

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

C
5. for element in lst: 2. [4, 5, 6, 7],

T.
6. if v > element: 3. [8, 9, 10, 11],

O
7. v = element 4. [12, 13, 14, 15]]

8. 5.

9. print(v) SP 6. for i in range(0, 4):


7.
G
a) 1 print(matrix[i][1], end = " ")
b) 3
a) 1 2 3 4
LO

c) 5
d) 6 b) 4 5 6 7
c) 1 3 8 12
Answer: a d) 2 5 9 13
.B

Explanation: Execute in the shell to verify.


Answer: d
5. What will be the output of the following Explanation: Execute in the shell to verify.
17

Python code?
7. What will be the output of the following
1. values = [[3, 4, 5, 1 ], [33, 6, 1, Python code?
-R

2]]
1. def m(list):
2.
2.
SE

v = list[0]
3. for row in values:
3. for e in list:
4. row.sort()
4.
C

if v < e: v = e
5. for element in row:
5. return v
6. print(element, end = " ")
6.
7. print()
7. values = [[3, 4, 5, 1], [33, 6, 1,
a) The program prints two rows 3 4 5 1 2]]
followed by 33 6 1 2

Downloaded From: https://cse-r17.blogspot.com 86


First Semester MCQ for Regulations 2017

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

M
d) 5 33
c) 4
Answer: d d) 5

O
Explanation: Execute in the shell to verify.
Answer: c

C
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?

T.
10. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?

O
[7, 8]]]
1. points = [[1, 2], [3, 1.5], [0.5,
2. 0.5]]

3. print(data[1][0][0]) SP 2. points.sort()
3. print(points)
G
a) 1
b) 2
a) [[1, 2], [3, 1.5], [0.5, 0.5]]
LO

c) 4
d) 5 b) [[3, 1.5], [1, 2], [0.5, 0.5]]
c) [[0.5, 0.5], [1, 2], [3, 1.5]]
Answer: d d) [[0.5, 0.5], [3, 1.5], [1, 2]]
.B

Explanation: Execute in the shell to verify.


Answer: c
9. What will be the output of the following Explanation: Execute in the shell to verify.
17

Python code?
1. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?
-R

[7, 8]]]
a=[10,23,56,[78]]
2. b=list(a)
a[3][0]=95
SE

3. def ttt(m): a[1]=34


print(b)
4. v = m[0][0]
a) [10,34,56,[95]]
C

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: https://cse-r17.blogspot.com 87


First Semester MCQ for Regulations 2017

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

M
)))) a=list(s.partition("@"))
print(a)
a) b=list(s.split("@",3))

O
print(b)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)]

C
a)
[(2,4),(‘b’,’c’),(‘yy’,’xx’)]

T.
[‘a’,’b’,’c’,’d’]
b)
[‘a’,’b’,’c’,’d’]

O
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’
‘)] b)
[(2, 'b', 'yy'), (4, 'c', 'xx')]

c) Syntax error
SP
[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]

[‘a’,’b’,’c’,’d’]
G
d)
c)
LO

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


[‘a’,’@’,’@d’]
[(2, 'b', 'yy'), (4, 'c', 'xx')]
[‘a’,’b’,’c’,’d’]
Answer: d
.B

Explanation: The zip function combines the d)


individual attributes of the lists into a list of
17

tuples. [‘a’,’@’,’@d’]

[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
-R

Answer: c
3. What will be the output of the following Explanation: The partition function only
Python code? splits for the first parameter along with the
SE

import copy
separator while split function splits for the
a=[10,23,56,[78]] number of times given in the second
b=copy.deepcopy(a) argument but without the separator.
C

a[3][0]=95
a[1]=34
print(b)
5. What will be the output of the following
a) [10,34,56,[95]]
Python code?
b) [10,23,56,[78]]
c) [10,23,56,[95]] a=[1,2,3,4]
d) [10,34,56,[78]] b=[sum(a[0:x+1]) for x in range(0,len(a))

Downloaded From: https://cse-r17.blogspot.com 88


First Semester MCQ for Regulations 2017

] print(a)
print(b)
a) Syntax error
a) 10 b) [[7], [7], [7]]
b) [1,3,5,7] c) [[7], [], []]
c) 4 d) [[],7, [], []]
d) [1,3,6,10]
Answer: b
Answer: d Explanation: The first line of the code

M
Explanation: The above code returns the creates multiple reference copies of sublist.
cumulative sum of elements in a list. Hence when 7 is appended, it gets appended

O
to all the sublists.
6. What will be the output of the following
Python code?

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

T.
a="hello"
b=list((x.upper(),len(x)) for x in a) b=[2,3,4,5]
print(b) a=list(filter(lambda x:x%2,b))

O
print(a)
a) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1)]
b) [(‘HELLO’, 5)] a) [2,4]
c) [(‘H’, 5), (‘E’, 5), (‘L’, 5), (‘L’, 5), (‘O’, 5)]
d) Syntax error
SP
b) [ ]
c) [3,5]
d) Invalid arguments for filter function
G
Answer: a
Explanation: Variable x iterates over each Answer: c
LO

letter in string a hence the length of each Explanation: The filter function gives value
letter is 1. from the list b for which the condition is true,
that is, x%2==1.
7. What will be the output of the following
.B

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


Python code?
17

a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a)) lst=[3,4,6,1,2]
] lst[1:2]=[7,8]
print(b) print(lst)
-R

a) 10 a) [3, 7, 8, 6, 1, 2]
b) [1,3,5,7] b) Syntax error
SE

c) 4 c) [3,[7,8],6,1,2]
d) [1,3,6,10] d) [3,4,6,7,8]
Answer: d Answer: a
C

Explanation: The above code returns the Explanation: In the piece of code, slice
cumulative sum of elements in a list. assignment has been implemented. The sliced
list is replaced by the assigned elements in the
8. What will be the output of the following
list. Type in python shell to verify.
Python code?

a=[[]]*3
1. What will be the output of the following
a[1].append(7) Python code?

Downloaded From: https://cse-r17.blogspot.com 89


First Semester MCQ for Regulations 2017

a=[1,2,3] a.extend([45,67])
b=a.append(4) print(a)
print(a)
print(b) a) [13, 56, 17, [87], 45, 67]
b) [13, 56, 17, 87, 45, 67]
a) c) [13, 56, 17, 87,[ 45, 67]]
d) [13, 56, 17, [87], [45, 67]]
[1,2,3,4]

[1,2,3,4] Answer: a

M
Explanation: The append function simply
b) adds its arguments to the list as it is while

O
extend function extends its arguments and
[1, 2, 3, 4] later appends it.

C
None
4. What is the output of the following piece of

T.
c) Syntax error code?
d) a=list((45,)*4)

O
print((45)*4)
[1,2,3] print(a)

[1,2,3,4]

Answer: b
SP
a)

180
Explanation: Append function on lists
G
doesn’t return anything. Thus the value of b is [(45),(45),(45),(45)]
None.
LO

b)

(45,45,45,45)
.B

2. What will be the output of the following


[45,45,45,45]
Python code?
c)
17

>>> a=[14,52,7]
>>>> b=a.copy()
>>> b is a 180
-R

[45,45,45,45]
a) True
b) False d) Syntax error
SE

Answer: b Answer: c
Explanation: List b is just a copy of the Explanation: (45) is an int while (45,) is a
original list. Any copy made in list b will not tuple of one element. Thus when a tuple is
C

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: https://cse-r17.blogspot.com 90


First Semester MCQ for Regulations 2017

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

M
6. What will be the output of the following Answer: d
Python code? Explanation: unpack(*x) unpacks the list

O
into the separate variables. Now, a=1 and
word1="Apple"
d=4. Thus 5 gets printed.

C
word2="Apple"
list1=[1,2,3]
list2=[1,2,3] 8. What will be the output of the following

T.
print(word1 is word2) Python code?
print(list1 is list2)

O
places = ['Bangalore', 'Mumbai', 'Delhi']
a) <br class="blank" />places1 = places
places2 = places[:]
True

True
SP
<br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
print(places)
G
b) a) [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
LO

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


d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
True
.B

Answer: b
c)
Explanation: places1 is an alias of the list
False places. Hence, any change made to places1 is
17

reflected in places. places2 is a copy of the


False list places. Thus, any change made to places2
isn’t reflected in places.
d)
-R

9. What will be the output of the following


True
Python code?
SE

False
x=[[1],[2]]
Answer: d print(" ".join(list(map(str,x))))
Explanation: In the above case, both the lists
C

a) [1] [2]
are equivalent but not identical as they have
b) [49] [50]
different objects.
c) Syntax error
d) [[1]] [[2]]

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

Downloaded From: https://cse-r17.blogspot.com 91


First Semester MCQ for Regulations 2017

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)

M
a) 561 1
b) 5

O
c) 12 [1,2,3]
d) Syntax error

C
c)
Answer: c

T.
Explanation: First, map converts the number 3
to string and then places the individual digits
[1,2,3]

O
in a list. Then, sum finds the sum of the digits
in the list. The code basically finds the sum of d)
digits in the number.

11. What will be the output of the following


SP
1

Python code? [44,2,3]


G
a= [1, 2, 3, 4, 5] Answer: a
LO

for i in range(1, 5): Explanation: A list is mutable, hence it’s


a[i-1] = a[i] value changes after function call. However,
for i in range(0, 5): integer isn’t mutable. Thus its value doesn’t
print(a[i],end = " ")
change.
.B

a) 5 5 1 2 3
b) 5 1 2 3 4
17

c) 2 3 4 5 1
13. What will be the output of the following
d) 2 3 4 5 5
Python code?
-R

Answer: d a = [1, 5, 7, 9, 9, 1]
Explanation: The items having indexes from <br class="blank" />b=a[0]
1 to 4 are shifted forward by one index due to <br class="blank" />x= 0
SE

the first for-loop and the item of index four is for x in range(1, len(a)):
printed again because of the second for-loop. if a[x] > b:
b = a[x]
b= x
12. What will be the output of the following
C

print(b)
Python code?
a) 5
def change(var, lst):
var = 1
b) 3
lst[0] = 44 c) 4
k = 3 d) 0
a = [1, 2, 3]
change(k, a)

Downloaded From: https://cse-r17.blogspot.com 92


First Semester MCQ for Regulations 2017

Answer: c Answer: c
Explanation: The above piece of code Explanation: print(i) is executed if the given
basically prints the index of the largest character is not a vowel.
element in the list.
2. What is the output of print(k) in the
14. What will be the output of the following following Python code snippet?
Python code?
k = [print(i) for i in my_string if i not
a=["Apple","Ball","Cobra"] in "aeiou"]

M
<br class="blank" />a.sort(key=len) print(k)
print(a)
a) all characters of my_string that aren’t

O
a) [‘Apple’, ‘Ball’, ‘Cobra’] vowels
b) [‘Ball’, ‘Apple’, ‘Cobra’] b) a list of Nones

C
c) [‘Cobra’, ‘Apple’, ‘Ball’] c) list of Trues
d) Invalid syntax for sort() d) list of Falses

T.
Answer: b Answer: b

O
Explanation: The syntax isn’t invalid and the Explanation: print() returns None.
list is sorted according to the length of the
strings in the list since key is given as len.

15. What will be the output of the following


SP
3. What will be the output of the following
Python code snippet?
my_string = "hello world"
Python code?
G
k = [(i.upper(), len(i)) for i in my_stri
num = ['One', 'Two', 'Three'] ng]
LO

for i, x in enumerate(num): print(k)


print('{}: {}'.format(i, x),end=" ")
a) [(‘HELLO’, 5), (‘WORLD’, 5)]
a) 1: 2: 3: b) [(‘H’, 1), (‘E’, 1), (‘L’, 1), (‘L’, 1), (‘O’, 1),
.B

b) Exception is thrown (‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1),
c) One Two Three (‘D’, 1)]
c) [(‘HELLO WORLD’, 11)]
17

d) 0: One 1: Two 2: Three


d) none of the mentioned
Answer: d
Explanation: enumerate(iterator,start=0) is a Answer: b
-R

built-in function which returns (0,lst[0]), Explanation: We are iterating over each letter
(1,lst[1]) and so on where lst is a list(iterator). in the string.
SE

1. What will be the output of the following 4. Which of the following is the correct
Python code snippet? expansion of list_1 = [expr(i) for i in list_0 if
func(i)]?
C

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: https://cse-r17.blogspot.com 93


First Semester MCQ for Regulations 2017

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

M
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
d) none of the mentioned ‘cf’]

O
Answer: c Answer: d

C
Explanation: We have to create an empty list, Explanation: If it were to be executed as a
loop over the contents of the existing list and nested for loop, i would be the outer loop and

T.
check if a condition is satisfied before j the inner loop.
performing some operation and adding it to
the new list. 8. What will be the output of the following

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

x = [i**+1 for i in range(3)]; print(x);


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

a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’,


G
a) [0, 1, 2] ‘fc’]
b) [1, 2, 5] b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’,
LO

c) error, **+ is not a valid operator ‘bf’, ‘cf’]]


d) error, ‘;’ is not allowed c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’,
‘fb’, ‘fc’]]
.B

Answer: a d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,


Explanation: i**+1 is evaluated as (i)**(+1). ‘cf’]
17

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


Python code snippet? Explanation: The inner list is generated once
for each value of j.
-R

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


9. What will be the output of the following
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] Python code snippet?
b) ‘hello’
SE

c) [‘hello’] print([if i%2==0: i; else: i+1; for i in


d) hello range(4)])
C

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: https://cse-r17.blogspot.com 94


First Semester MCQ for Regulations 2017

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

M
1. What will be the output of the following For example if we have a list l=[-65, 2, 7, -99,

O
Python code? -4, 3]
>>> [x for x in l if x<0]

C
l=[1,2,3,4,5] The output would be: [-65, -99, -4].
[x&1 for x in l]

T.
4. What will be the output of the following
a) [1, 1, 1, 1, 1]
Python code?
b) [1, 0, 1, 0, 1]

O
c) [1, 0, 0, 0, 0] s=["pune", "mumbai", "delhi"]
d) [0, 1, 0, 1, 0] [(w.upper(), len(w)) for w in s]

Answer: b
Explanation: In the code shown above, each
SP
a) Error
b) [‘PUNE’, 4, ‘MUMBAI’, 6, ‘DELHI’, 5]
G
of the numbers of the list, that is, 1, 2, 3, 4 c) [PUNE, 4, MUMBAI, 6, DELHI, 5]
and 5 are AND-ed with 1 and the result is d) [(‘PUNE’, 4), (‘MUMBAI’, 6), (‘DELHI’,
LO

printed in the form of a list. Hence the output 5)]


is [1, 0, 1, 0, 1].
Answer: d
2. What will be the output of the following Explanation: If we need to generate two
.B

Python code? results, we need to put it in the form of a


tuple. The code shown above returns each
l1=[1,2,3] word of list in uppercase, along with the
17

l2=[4,5,6]
[x*y for x in l1 for y in l2] length of the word. Hence the output of the
code is: [(‘PUNE’, 4), (‘MUMBAI’, 6),
a) [4, 8, 12, 5, 10, 15, 6, 12, 18] (‘DELHI’, 5)].
-R

b) [4, 10, 18]


c) [4, 5, 6, 8, 10, 12, 12, 15, 18] 5. What will be the output of the following
d) [18, 12, 6, 15, 10, 5, 12, 8, 4] Python code?
SE

l1=[2,4,6]
Answer: c l2=[-2,-4,-6]
Explanation: The code shown above returns for i in zip(l1, l2):
C

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: https://cse-r17.blogspot.com 95


First Semester MCQ for Regulations 2017

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)

M
(6, -6) a) Error
b) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
c)

O
d) [-4, -16, -36]
1 4 7

C
Answer: c
Explanation: The output of the code shown 2 5 8

T.
will be:
(2, -2) 3 6 9
(4, -4)

O
(6, -6) d)
This format is due to the statement print(i).

6. What will be the output of the following


Python code?
SP (1 4 7)

(2 5 8)
G
(3 6 9)
l1=[10, 20, 30]
LO

l2=[-10, -20, -30] Answer: b


l3=[x+y for x, y in zip(l1, l2)] Explanation: In the code shown above, ‘3’ is
l3
the index of the list. Had we used a number
a) Error greater than 3, it would result in an error. The
.B

b) 0 output of this code is: [[1, 4, 7], [2, 5, 8], [3,


c) [-20, -60, -80] 6, 9]].
17

d) [0, 0, 0]

Answer: d
Explanation: The code shown above returns 9. What will be the output of the following
-R

x+y, for x belonging to the list l1 and y Python code?


belonging to the list l2. That is, l3=[10-10,
import math
20-20, 30-20], which is, [0, 0, 0].
SE

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

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: https://cse-r17.blogspot.com 96


First Semester MCQ for Regulations 2017

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

M
l3=[7,8,9]
for x, y, z in zip(l1, l2, l3): Python code?
print(x, y, z)

O
[ord(ch) for ch in 'abc']
a)

C
a) [97, 98, 99]
1 4 7 b) [‘97’, ‘98’, ‘99’]

T.
c) [65, 66, 67]
2 5 8 d) Error

O
3 6 9
Answer: a
b) Explanation: The list comprehension shown

(1 4 7)
SP
above returns the ASCII value of each
alphabet of the string ‘abc’. Hence the output
is: [97, 98, 99]. Had the string been ‘ABC’,
G
(2 5 8) the output would be: [65, 66, 67].
LO

(3 6 9)
3. What will be the output of the following
Python code?
c) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
d) Error t=32.00
.B

[round((x-32)*5/9) for x in t]
Answer: a
Explanation: The output of the code shown a) [0]
17

above is: b) 0
147 c) [0.00]
258 d) Error
-R

369
This is due to the statement: print(x, y,z). Answer: d
Explanation: The value of t in the code
SE

1. Read the information given below carefully shown above is equal to 32.00, which is a
and write a list comprehension such that the floating point value. ‘Float’ objects are not
output is: [‘e’, ‘o’] iterable. Hence the code results in an error.
C

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]
b) [x for x in w if x in v] a) [x in range(1, 1000) if x%3==0]
c) [x for x in v if w in v] b) [x for x in range(1000) if x%3==0]
d) [x for v in w for x in w] c) [x%3 for x in range(1, 1000)]
d) [x%3=0 for x in range(1, 1000)]

Downloaded From: https://cse-r17.blogspot.com 97


First Semester MCQ for Regulations 2017

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

M
for i in range(1, 101): 8. What is the list comprehension equivalent
if int(i*0.5)==i*0.5: for?

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

C
is even} (including zero)
(i*0.5)]
b) [i for i in range(1, 101) if int(i*0.5)== a) [x for x in range(1, 20) if (x%2==0)]

T.
(i*0.5)] b) [x for x in range(0, 20) if (x//2==0)]
c) [i for i in range(1, 101) if int(i*0.5)= c) [x for x in range(1, 20) if (x//2==0)]

O
(i*0.5)] d) [x for x in range(0, 20) if (x%2==0)]
d) [i for i in range(1, 100) if int(i*0.5)=
(i*0.5)]

Answer: b
SP
Answer: d
Explanation: The required list
comprehension will print a whole number,
Explanation: The code shown above prints
G
less than 20, provided that the number is
the value ‘i’ only if it satisfies the condition: even. Since the output list should contain zero
LO

int(i*0.5) is equal to (i*0.5). Hence the as well, the answer to this question is: [x for x
required list comprehension is: [i for i in in range(0, 20) if (x%2==0)].
range(1, 101) if int(i*0.5)==(i*0.5)].
9. What will be the output of the following
.B

6. What is the list comprehension equivalent Python list comprehension?


for: list(map(lambda x:x**-1, [1, 2, 3]))?
a) [1|x for x in [1, 2, 3]] [j for i in range(2,8) for j in range(i*2
17

b) [-1**x for x in [1, 2, 3]] , 50, i)]


c) [x**-1 for x in [1, 2, 3]]
a) A list of prime numbers up to 50
d) [x^-1 for x in range(4)]
b) A list of numbers divisible by 2, up to 50
-R

Answer: c c) A list of non prime numbers, up to 50


Explanation: The output of the function d) Error
SE

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
C

[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: https://cse-r17.blogspot.com 98


First Semester MCQ for Regulations 2017

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’]
2. What will be the output of the following

M
Answer: b
Explanation: The code shown above returns Python code?
a new list containing only strings which do

O
A = [[1, 2, 3],
not have any punctuation in them. The only [4, 5, 6],
string from the list which does not contain

C
[7, 8, 9]]
any punctuation is ‘good’. Hence the output A[1]

T.
of the code shown above is [‘good’].
a) [4, 5, 6]
1. Which of the following matrices will throw b) [3, 6, 9]

O
an error in Python? c) [1, 4, 7]
a) d) [1, 2, 3]

A = [[1, 2, 3],

[4, 5, 6],
SP
Answer: a
Explanation: We can index the rows and
columns using normal index operations. The
G
[7, 8, 9]]
statement A[1] represents the second row,
that is, the middle row. Hence the output of
LO

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

B = [[3, 3, 3] 3. Which of the following Python statements


.B

will result in the output: 6?


[4, 4, 4]
A = [[1, 2, 3],
17

[5, 5, 5]] [4, 5, 6],


[7, 8, 9]]
c)
a) A[2][3]
-R

C = [(1, 2, 4), b) A[2][1]


(5, 6, 7),
c) A[1][2]
d) A[3][2]
SE

(8, 9, 10)]
Answer: c
d) Explanation: The output that is required is 6,
C

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: https://cse-r17.blogspot.com 99


First Semester MCQ for Regulations 2017

[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

M
Explanation: To get a particular column as 7. What will be the output of the following
output, we can simple iterate across the rows Python code?

O
and pull out the desired column, or iterate
through positions in rows and index as we go. A = [[1, 2, 3],

C
Hence the output of the code shown above is: [4, 5, 6],
[2, 5, 8]. [7, 8, 9]]

T.
[[col + 10 for col in row] for row in A]
5. What will be the output of the following
Python code? a) [[11, 12, 13], [14, 15, 16], [17, 18, 19]]

O
A = [[1, 2, 3],
b) Error
c) [11, 12, 13], [14, 15, 16], [17, 18, 19]
[4,
[7,
[A[i][i]
5, 6],
8, 9]]
for i in range(len(A))]
SP
d) [11, 12, 13, 14, 15, 16, 17, 18, 19]

Answer: a
G
a) [1, 5, 9] Explanation: The code shown above shows a
b) [3, 5, 7] list comprehension which adds 10 to each
LO

c) [4, 5, 6] element of the matrix A and prints it row-


d) [2, 5, 8] wise. Hence the output of the code is: [[11,
12, 13], [14, 15, 16], [17, 18, 19]]
Answer: a
.B

Explanation: We can also perform tasks like 8. What will be the output of the following
pulling out a diagonal. The expression shown Python code?
17

above uses range to generate the list of offsets


and the indices with the row and column the A = [[1, 2, 3],
same, picking out A[0][0], then A[1][1] and [4, 5, 6],
[7, 8, 9]]
so on. Hence the output of the code is: [1, 5,
-R

[A[i][len(A)-1-i] for i in range(len(A))]


9].
a) [1, 5, 9]
6. What will be the output of the following
SE

b) [4, 5, 6]
Python code? c) [3, 5, 7]
l=[[1, 2, 3], [4, 5, 6]]
d) [2, 5, 8]
C

for i in range(len(l)):
for j in range(len(l[i])): Answer: c
l[i][j]+=10 Explanation: This expression scales the
l common index to fetch A[0][2], A[1][1], etc.
We assume the matrix has the same number
a) No output of rows and columns.
b) Error

Downloaded From: https://cse-r17.blogspot.com 100


First Semester MCQ for Regulations 2017

9. What will be the output of the following is: [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20,
Python code? 30, 40, 50, 60, 70, 80, 90].
A = [[1, 2, 3], 11. What will be the output of the following
[4, 5, 6], Python code?
[7, 8, 9]]
B = [[3, 3, 3],
A = [[1, 2, 3],
[4, 4, 4],
[4, 5, 6],
[5, 5, 5]]
[7, 8, 9]]
[B[row][col]*A[row][col] for row in range

M
B = [[3, 3, 3],
(3) for col in range(3)]
[4, 4, 4],
[5, 5, 5]]

O
a) [3, 6, 9, 16, 20, 24, 35, 40, 45] [[col1 * col2 for (col1, col2) in zip(row
b) Error 1, row2)] for (row1, row2) in zip(A, B)]

C
c) [0, 30, 60, 120, 160, 200, 300, 350, 400]
d) 0 a) [0, 30, 60, 120, 160, 200, 300, 350, 400]

T.
b) [[3, 6, 9], [16, 20, 24], [35, 40, 45]]
Answer: a c) No output
Explanation: In the code shown above, we d) Error

O
have used list comprehension to combine
values of multiple matrices. We have Answer: b
multiplied the elements of the matrix B with
that of the matrix A, in the range(3). Hence
the output of this code is: [3, 6, 9, 16, 20, 24,
SP
Explanation: The list comprehension shown
above results in the output: [[3, 6, 9], [16, 20,
24], [35, 40, 45]].
G
35, 40, 45].
12. What will be the output of the following
LO

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


Python code?
A = [[1, 2, 3],
r = [11, 12, 13, 14, 15, 16, 17, 18, 19] [4, 5, 6],
.B

A = [[0, 10, 20], [7, 8, 9]]


[30, 40, 50], B = [[3, 3, 3],
[60, 70, 80]] [4, 4, 4],
[5, 5, 5]]
17

for row in A:
for col in row: zip(A, B)
r.append(col+10)
r a) Address of the zip object
-R

b) Address of the matrices A and B


a) [11, 12, 13, 14, 15, 16, 17, 18, 19, 10, 20, c) No output
30, 40, 50, 60, 70, 80, 90] d) [3, 6, 9, 16, 20, 24, 35, 40, 45]
SE

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
C

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: https://cse-r17.blogspot.com 101


First Semester MCQ for Regulations 2017

TOPIC 4.2 TUPLES (TUPLE a) (1, 2)


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.

M
c) {1, 2, 3}
5. What will be the output of the following
d) {}
Python code?

O
Answer: b
1. >>>t = (1, 2, 4, 3, 8, 9)
Explanation: Tuples are represented with

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

T.
2)]
2. Suppose t = (1, 2, 4, 3), which of the
following is incorrect? a) [2, 3, 9]

O
a) print(t[3]) b) [1, 2, 4, 3, 8, 9]
b) t[3] = 45 c) [1, 4, 8]
c) print(max(t))
d) print(len(t)) SP
d) (1, 4, 8)

Answer: c
Answer: b Explanation: Execute in the shell to verify.
G
Explanation: Values cannot be modified in
the case of tuple, that is, tuple is immutable. 6. What will be the output of the following
LO

Python code?
3. What will be the output of the following
Python code? 1. d = {"john":40, "peter":45}
.B

1. >>>t=(1,2,4,3) 2. d["john"]
17

2. >>>t[1:3] a) 40
b) 45
a) (1, 2) c) “john”
b) (1, 2, 4) d) “peter”
-R

c) (2, 4)
d) (2, 4, 3) Answer: a
Explanation: Execute in the shell to verify.
SE

Answer: c
Explanation: Slicing in tuples takes place 7. What will be the output of the following
just as it does in strings. Python code?
C

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: https://cse-r17.blogspot.com 102


First Semester MCQ for Regulations 2017

c) (1, 1, 2, 2) 3. numberGames[(4,2,1)] = 10
d) [1, 1, 2, 2]
4. numberGames[(1,2)] = 12
Answer: a
5. sum = 0
Explanation: * operator concatenates tuple.
6. for k in numberGames:
8. What will be the output of the following
Python code? 7. sum += numberGames[k]

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

2. >>>t2 = (1, 2, 3, 4)

O
a) 30
b) 24
3. >>>t1 < t2

C
c) 33
d) 12
a) True

T.
b) False Answer: c
c) Error Explanation: Tuples can be used for keys

O
d) None into dictionary. The tuples can have mixed
length and the order of the items in the tuple
Answer: b
Explanation: Elements are compared one by
one in this case.
SP
is considered when comparing the equality of
the keys.
G
1. What is the data type of (1)?
9. What will be the output of the following
a) Tuple
Python code?
LO

b) Integer
1. >>>my_tuple = (1, 2, 3, 4) c) List
d) Both tuple and integer
2. >>>my_tuple.append( (5, 6, 7) )
.B

Answer: b
3. >>>print len(my_tuple) Explanation: A tuple of one element must be
created as (1,).
17

a) 1
b) 2 2. If a=(1,2,3,4), a[1:-1] is _________
c) 5 a) Error, tuple slicing doesn’t exist
-R

d) Error b) [2,3]
c) (2,3,4)
Answer: d d) (2,3)
SE

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

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: https://cse-r17.blogspot.com 103


First Semester MCQ for Regulations 2017

a) False c) 12
b) True d) 9
c) Error, < operator is not valid for tuples
d) Error, < operator is valid for tuples but not Answer: c
if there are sub-tuples Explanation: In the above case, 3 is the
starting value to which the sum of the tuple is
Answer: a added to.
Explanation: Since the first element in the
sub-tuple of a is larger that the first element 7. Is the following Python code valid?

M
in the subtuple of b, False is printed.
>>> a=(1,2,3,4)

O
>>> del a
4. What will be the output of the following
Python code?
a) No because tuple is immutable

C
>>> a=("Check")*3 b) Yes, first element in the tuple is deleted
c) Yes, the entire tuple is deleted

T.
>>> a
d) No, invalid syntax for del method
a) (‘Check’,’Check’,’Check’)

O
b) * Operator not valid for tuples Answer: c
c) (‘CheckCheckCheck’) Explanation: The command del a deletes the
d) Syntax error

Answer: c
SP
entire tuple.

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


a) Array of tuples
G
Explanation: Here (“Check”) is a string not a
tuple because there is no comma after the b) List of tuples
c) Tuples of lists
LO

element.
d) Invalid type
5. What will be the output of the following
Python code? Answer: b
.B

Explanation: The variable a has tuples


>>> a=(1,2,3,4) enclosed in a list making it a list of tuples.
>>> del(a[2])
17

9. What will be the output of the following


a) Now, a=(1,2,4) Python code?
b) Now, a=(1,3,4)
c) Now a=(3,4)
-R

>>> a=(0,1,2,3,4)
d) Error as tuple is immutable >>> b=slice(0,2)
>>> a[b]
SE

Answer: d
Explanation: ‘tuple’ object doesn’t support a) Invalid syntax for slicing
item deletion. b) [0,2]
c) (0,1)
C

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: https://cse-r17.blogspot.com 104


First Semester MCQ for Regulations 2017

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

M
Answer: a >>> a,b=1,2,3
Explanation: Zip function combines

O
individual elements of two iterables into a) Yes, this is an example of tuple unpacking.
tuples. Execute in Python shell to verify.

C
a=1 and b=2
b) Yes, this is an example of tuple unpacking.
1. Is the following Python code valid?

T.
a=(1,2) and b=3
c) No, too many values to unpack
>>> a,b,c=1,2,3
d) Yes, this is an example of tuple unpacking.

O
>>> a,b,c
a=1 and b=(2,3)
a) Yes, [1,2,3] is printed
b) No, invalid syntax
c) Yes, (1,2,3) is printed
d) 1 is printed
SP
Answer: c
Explanation: For unpacking to happen, the
number of values of the right hand side must
G
be equal to the number of variables on the left
Answer: c hand side.
LO

Explanation: A tuple needn’t be enclosed in


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

Python code? >>> a=(1,2)


>>> b=(3,4)
>>> c=a+b
17

a = ('check',)
>>> c
n = 2
for i in range(int(n)):
a = (a,) a) (4,6)
b) (1,2,3,4)
-R

print(a)
c) Error as tuples are immutable
a) Error, tuples are immutable d) None
SE

b)
Answer: b
(('check',),) Explanation: In the above piece of code, the
values of the tuples aren’t being changed.
C

((('check',),),)
Both the tuples are simply concatenated.
c) ((‘check’,)’check’,)
5. What will be the output of the following
d)
Python code?
(('check',)’check’,)
>>> a,b=6,7
((('check',)’check’,)’check’,) >>> a,b=b,a
>>> a,b

Downloaded From: https://cse-r17.blogspot.com 105


First Semester MCQ for Regulations 2017

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)

M
c) None
6. What will be the output of the following
d) Error, tuple has no attribute sort
Python code?

O
>>> import collections
Answer: d
Explanation: A tuple is immutable thus it

C
>>> a=collections.namedtuple('a',['i','j'
]) doesn’t have a sort attribute.
>>> obj=a(i=4,j=7)

T.
>>> obj 10. Is the following Python code valid?
a) a(i=4, j=7)

O
>>> a=(1,2,3)
b) obj(i=4, j=7) >>> b=a.update(4,)
c) (4,7)
d) An exception is thrown

Answer: a
SP
a) Yes, a=(1,2,3,4) and b=(1,2,3,4)
b) Yes, a=(1,2,3) and b=(1,2,3,4)
c) No because tuples are immutable
G
Explanation: The above piece of code d) No because wrong syntax for update()
illustrates the concept of named tuples. method
LO

7. Tuples can’t be made keys of a dictionary. Answer: c


a) True Explanation: Tuple doesn’t have any
b) False update() attribute because it is immutable.
.B

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


17

Explanation: Tuples can be made keys of a Python code?


dictionary because they are hashable.
>>> a=[(2,4),(1,2),(3,9)]
>>> a.sort()
8. Is the following Python code valid?
-R

>>> a
>>> a=2,3,4,5
>>> a a) [(1, 2), (2, 4), (3, 9)]
SE

b) [(2,4),(1,2),(3,9)]
a) Yes, 2 is printed c) Error because tuples are immutable
b) Yes, [2,3,4,5] is printed d) Error, tuple has no sort attribute
c) No, too many values to unpack
C

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: https://cse-r17.blogspot.com 106


First Semester MCQ for Regulations 2017

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

M
specifying keys and values. 5. What will be the output of the following
Python code snippet?

O
2. What will be the output of the following
Python code snippet? 1. d1 = {"john":40, "peter":45}

C
1. d = {"john":40, "peter":45} 2. d2 = {"john":466, "peter":45}

T.
3. d1 > d2
a) “john”, 40, 45, and “peter”
b) “john” and “peter”

O
a) True
c) 40 and 45
b) False
d) d = (40:”john”, 45:”peter”)

Answer: b
Explanation: Dictionaries appear in the form
SP
c) Error
d) None

Answer: c
G
of keys and values.
Explanation: Arithmetic > operator cannot
be used with dictionaries.
LO

3. What will be the output of the following


Python code snippet?
6. What will be the output of the following
Python code snippet?
1. d = {"john":40, "peter":45}
.B

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


17

2. d["john"]
a) True
b) False a) 40
c) None b) 45
-R

d) Error c) “john”
d) “peter”
Answer: a
SE

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
C

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: https://cse-r17.blogspot.com 107


First Semester MCQ for Regulations 2017

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.

M
d) d.len()
2. Which of the following is not a declaration

O
Answer: b of the dictionary?
Explanation: Execute in the shell to verify. a) {1: ‘A’, 2: ‘B’}

C
b) dict([[1,”A”],[2,”B”]])
9. What will be the output of the following c) {1,”A”,2”B”}

T.
Python code snippet? d) { }

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

O
Explanation: Option c is a set, not a
2. print(list(d.keys())) dictionary.
a) [“john”, “peter”]
b) [“john”:40, “peter”:45]
SP
3. What will be the output of the following
Python code snippet?
G
c) (“john”, “peter”)
d) (“john”:40, “peter”:45) a={1:"A",2:"B",3:"C"}
LO

for i,j in a.items():


Answer: a print(i,j,end=" ")
Explanation: The output of the code shown
above is a list containing only keys of the a) 1 A 2 B 3 C
.B

dictionary d, in the form of a list. b) 1 2 3


c) A B C
10. Suppose d = {“john”:40, “peter”:45}, d) 1:”A” 2:”B” 3:”C”
17

what happens when we try to retrieve a value


using the expression d[“susan”]? Answer: a
a) Since “susan” is not a value in the set, Explanation: In the above code, variables i
-R

Python raises a KeyError exception and j iterate over the keys and values of the
b) It is executed fine and no exception is dictionary respectively.
raised, and it returns None
SE

c) Since “susan” is not a key in the set, 4. What will be the output of the following
Python raises a KeyError exception Python code snippet?
d) Since “susan” is not a key in the set, a={1:"A",2:"B",3:"C"}
C

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: https://cse-r17.blogspot.com 108


First Semester MCQ for Regulations 2017

Answer: b c) Error
Explanation: The get() method returns the d) [1,3,6,10]
value of the key if the key is present in the
dictionary and the default value(second Answer: a
parameter) if the key isn’t present in the Explanation: setdefault() will set
dictionary. dict[key]=default if key is not already in the
dictionary.
5. What will be the output of the following
Python code snippet? 8. What will be the output of the following

M
Python code?
a={1:"A",2:"B",3:"C"}

O
print(a.get(5,4)) a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a) Error, invalid syntax a.update(b)

C
b) A print(a)

T.
c) 5
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
d) 4
b) Method update() doesn’t exist for

O
Answer: d dictionaries
Explanation: The get() method returns the c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
default value(second parameter) if the key
isn’t present in the dictionary. SP
d) {4: ‘D’, 5: ‘E’}

Answer: c
Explanation: update() method adds
G
6. What will be the output of the following
Python code snippet? dictionary b’s key-value pairs to dictionary a.
Execute in python shell to verify.
LO

a={1:"A",2:"B",3:"C"}
print(a.setdefault(3)) 9. What will be the output of the following
Python code?
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
.B

b) C a={1:"A",2:"B",3:"C"}
c) {1: 3, 2: 3, 3: 3} b=a.copy()
17

b[2]="D"
d) No method called setdefault() exists for print(a)
dictionary
a) Error, copy() method doesn’t exist for
Answer: b
-R

dictionaries
Explanation: setdefault() is similar to get() b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
but will set dict[key]=default if key is not c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
SE

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
C

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: https://cse-r17.blogspot.com 109


First Semester MCQ for Regulations 2017

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

M
Answer: d
Explanation: The clear() method clears all
14. What will be the output of the following
the key-value pairs in the dictionary.

O
Python code?
11. Which of the following isn’t true about

C
a={1:"A",2:"B",3:"C"}
dictionary keys? for i in a:
a) More than one key isn’t allowed

T.
print(i,end=" ")
b) Keys must be immutable
c) Keys must be integers a) 1 2 3

O
d) When duplicate keys encountered, the last b) ‘A’ ‘B’ ‘C’
assignment wins c) 1 ‘A’ 2 ‘B’ 3 ‘C’

Answer: c
Explanation: Keys of a dictionary may be
SP
d) Error, it should be: for i in a.items():

Answer: a
any data type that is immutable. Explanation: The variable i iterates over the
G
keys of the dictionary and hence the keys are
12. What will be the output of the following printed.
LO

Python code?
15. What will be the output of the following
a={1:5,2:3,3:4} Python code?
.B

a.pop(3)
print(a) >>> a={1:"A",2:"B",3:"C"}
>>> a.items()
17

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

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


Answer: b
Explanation: pop() method removes the key- Answer: d
SE

value pair for the key mentioned in the pop() Explanation: The method items() returns list
method. of tuples with each tuple having a key-value
pair.
C

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: https://cse-r17.blogspot.com 110


First Semester MCQ for Regulations 2017

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

M
Python code snippet? keys present since the key ‘Apple’ is
repeated. Thus, the length of the dictionary is

O
>>> a={1:"A",2:"B",3:"C"} 2.
>>> del a

C
5. What will be the output of the following
a) method del doesn’t exist for the dictionary
Python code snippet?
b) del deletes the values in the dictionary

T.
c) del deletes the entire dictionary a = {}
d) del deletes the keys in the dictionary a[1] = 1

O
a['1'] = 2
Answer: c a[1]=a[1]+1
Explanation: del deletes the entire dictionary
and any further attempt to access it will throw
an error.
SP
count = 0
for i in a:
count += a[i]
print(count)
G
3. If a is a dictionary with some key-value a) 1
pairs, what does a.popitem() do?
LO

b) 2
a) Removes an arbitrary element c) 4
b) Removes all the key-value pairs d) Error, the keys can’t be a mixture of letters
c) Removes the key-value pair for the key and numbers
.B

given as an argument
d) Invalid method for dictionary Answer: c
Explanation: The above piece of code
17

Answer: a basically finds the sum of the values of keys.


Explanation: The method popitem() removes
a random key-value pair. 6. What will be the output of the following
-R

Python code snippet?


4. What will be the output of the following
Python code snippet? numbers = {}
SE

letters = {}
total={} comb = {}
def insert(items): numbers[1] = 56
if items in total: numbers[3] = 7
C

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: https://cse-r17.blogspot.com 111


First Semester MCQ for Regulations 2017

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?

M
Answer: c
test = {1:'A', 2:'B', 3:'C'}
Explanation: The value of key 1 is 4 since 1

O
test = {}
print(len(test)) and 1.0 are the same. Then, the function
count() gives the sum of all the values of the

C
a) 0 keys (2+4).
b) None

T.
c) 3 10. What will be the output of the following
d) An exception is thrown Python code snippet?

O
Answer: a a={}
a['a']=1
Explanation: In the second line of code, the
dictionary becomes an empty dictionary.
Thus, length=0.
SP
a['b']=[2,3,4]
print(a)
G
a) Exception is thrown
8. What will be the output of the following b) {‘b’: [2], ‘a’: 1}
Python code snippet?
LO

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' Answer: d
.B

del test[2] Explanation: Mutable members can be used


print(len(test)) as the values of the dictionary but they cannot
be used as the keys of the dictionary.
17

a) 0
b) 2 11. What will be the output of the following
c) Error as the key-value pair of 1:’A’ is Python code snippet?
-R

already deleted
d) 1 >>>import collections
>>> a=collections.Counter([1,1,2,3,3,4,4,
SE

Answer: b 4])
>>> a
Explanation: After the key-value pair of
1:’A’ is deleted, the key-value pair of 1:’D’ is a) {1,2,3,4}
added.
C

b) Counter({4, 1, 3, 2})
c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
9. What will be the output of the following
d) {4: 3, 1: 2, 3: 2, 2: 1}
Python code snippet?

a = {}
Answer: c
a[1] = 1 Explanation: The statement
a['1'] = 2 a=collections.OrderedDict() generates a
a[1.0]=4 dictionary with the number as the key and the

Downloaded From: https://cse-r17.blogspot.com 112


First Semester MCQ for Regulations 2017

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

M
>>> b=collections.Counter([3,4,4,5,5,5])
a) Counter({4: 3, 2: 2, 3: 1}) >>> a&b
b) {3:1}

O
c) {4:3} a) Counter({3: 12, 4: 1, 5: 1})
d) [(4, 3)] b) Counter({3: 1, 4: 1, 5: 1})

C
c) Counter({4: 2})
Answer: d d) Counter({5: 1})

T.
Explanation: The most_common() method
returns the n number key-value pairs where Answer: b

O
the value is the most recurring. Explanation: a&b returns the pair of keys
and the lowest recurring value.
13. What will be the output of the following
Python code snippet?

>>>import collections
SP
1. The following Python code is invalid.

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

a = demo()
a) Counter({4: 3, 2: 2, 3: 1}) a['test'] = 7
print(a)
b) {3:1}
c) {4:3} a) True
.B

d) [(4, 3)] b) False


Answer: d
17

Answer: b
Explanation: The most_common() method Explanation: The output of the code is:
returns the n number key-value pairs where {‘test’:7}.
the value is the most recurring.
-R

2. What will be the output of the following


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

count={}
>>> import collections count[(1,2,4)] = 5
>>> a=collections.Counter([2,2,3,3,3,4]) count[(4,2,1)] = 7
>>> b=collections.Counter([2,2,3,4,4]) count[(1,2)] = 6
C

>>> 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: https://cse-r17.blogspot.com 113


First Semester MCQ for Regulations 2017

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?

M
3. What will be the output of the following
Python code? >>> a={}

O
>>> a.fromkeys([1,2,3],"check")
a={}
a) Syntax error

C
a[2]=1
a[1]=[2,3,4] b) {1:”check”,2:”check”,3:”check”}
print(a[1][1]) c) “check”

T.
d) {1:None,2:None,3:None}
a) [2,3,4]

O
b) 3 Answer: b
c) 2 Explanation: The dictionary takes values of
d) An exception is thrown

Answer: b
Explanation: Now, a={1:[2,3,4],2:1} . a[1]
SP
keys from the list and initializes it to the
default value (value given in the second
parameter). Execute in Python shell to verify.
G
[1] refers to second element having key 1. 7. What will be the output of the following
Python code?
LO

4. What will be the output of the following


Python code? >>> b={}
>>> all(b)
>>> a={'B':5,'A':9,'C':7}
.B

>>> sorted(a) a) { }
b) False
a) [‘A’,’B’,’C’]
17

c) True
b) [‘B’,’C’,’A’] d) An exception is thrown
c) [5,7,9]
d) [9,5,7] Answer: c
-R

Explanation: Function all() returns True if all


Answer: a keys of the dictionary are true or if the
Explanation: Return a new sorted list of keys
SE

dictionary is empty.
in the dictionary.
8. If b is a dictionary, what does any(b) do?
5. What will be the output of the following a) Returns True if any key of the dictionary is
C

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: https://cse-r17.blogspot.com 114


First Semester MCQ for Regulations 2017

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

M
>>> b=dict(zip(a.values(),a.keys())) >>> a=dict()
>>> b >>> a=collections.defaultdict(int)
>>> a[1]

O
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown a) 1

C
c) {‘a’: ‘b’: ‘c’: } b) 0
d) {1: ‘a’, 2: ‘b’, 3: ‘c’} c) An exception is thrown

T.
d) ‘ ‘
Answer: d

O
Explanation: The above piece of code inverts Answer: b
the key-value pairs in the dictionary. Explanation: The statement

10. What will be the output of the following


Python code?
SP
a=collections.defaultdict(int) gives the default
value of 0
(since int data type is given within the
parenthesis) even if the keys don’t exist in the
G
>>> a={i: 'A' + str(i) for i in range(5)} dictionary.
>>> a
LO

13. What will be the output of the following


a) An exception is thrown Python code?
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4:
‘A4’}
.B

>>> import collections


c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’} >>> a=dict()
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’} >>> a=collections.defaultdict(str)
>>> a['A']
17

Answer: b
Explanation: Dictionary comprehension and a) An exception is thrown since the dictionary
string concatenation is implemented in the is empty
-R

above piece of code. b) ‘ ‘


c) ‘A’
11. What will be the output of the following d) 0
SE

Python code?
Answer: b
>>> a=dict() Explanation: The statement
C

>>> 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: https://cse-r17.blogspot.com 115


First Semester MCQ for Regulations 2017

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

M
Answer: d 2. To open a file c:\scores.txt for writing, we
Explanation: The statement use ____________

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

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

T.
15. What will be the output of the following
Python code? Answer: b
Explanation: w is used to indicate that file is

O
>>> import collections to be written to.
>>> a=collections.OrderedDict((str(x),x)
for
>>>
x in range(3))
a SP
3. To open a file c:\scores.txt for appending
data, we use ____________
a) outfile = open(“c:\scores.txt”, “a”)
G
a) {‘2’:2, ‘0’:0, ‘1’:1}
b) outfile = open(“c:\scores.txt”, “rw”)
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
c) outfile = open(file = “c:\scores.txt”, “w”)
LO

c) An exception is thrown
d) outfile = open(file = “c:\scores.txt”, “w”)
d) ‘ ‘
Answer: a
Answer: b
Explanation: a is used to indicate that data is
.B

Explanation: The line of code


to be appended.
a=collections.OrderedDict() generates a
dictionary satisfying the conditions given
17

4. Which of the following statements are


within the parenthesis and in an ascending true?
order of the keys. a) When you open a file for reading, if the file
does not exist, an error occurs
-R

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


does not exist, a new file is created
SE

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
C

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: https://cse-r17.blogspot.com 116


First Semester MCQ for Regulations 2017

a) infile.read(2) c) infile.readline()
b) infile.read() d) infile.readlines()
c) infile.readline()
d) infile.readlines() Answer: c
Explanation: Execute in the shell to verify.
Answer: a
Explanation: Execute in the shell to verify. 9. To read the remaining lines of the file from
a file object infile, we use ____________
6. To read the entire remaining contents of the a) infile.read(2)

M
file as a string from a file object infile, we use b) infile.read()
____________ c) infile.readline()

O
a) infile.read(2) d) infile.readlines()
b) infile.read()

C
c) infile.readline() Answer: d
d) infile.readlines() Explanation: Execute in the shell to verify.

T.
Answer: b 10. The readlines() method returns
Explanation: read function is used to read all ____________

O
the lines in a file. a) str
b) a list of lines
7. What will be the output of the following
Python code? SP
c) a list of single characters
d) a list of integers
G
1. f = None Answer: b
Explanation: Every line is stored in a list and
LO

2. for i in range (5): returned.


3. with open("data.txt", "w") as f
1. Which are the two built-in functions to
:
read a line of text from standard input, which
.B

4. if i > 2: by default comes from the keyboard?


a) Raw_input & Input
5.
17

break b) Input & Scan


c) Scan & Scanner
6. print(f.closed) d) Scanner
-R

a) True
Answer: a
b) False
Explanation: Python provides two built-in
c) None
functions to read a line of text from standard
SE

d) Error input, which by default comes from the


Answer: a keyboard. These functions are:
Explanation: The WITH statement when raw_input and input
C

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: https://cse-r17.blogspot.com 117


First Semester MCQ for Regulations 2017

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.

M
Received input is : Hello 4. Which one of the following is not attributes
of file?

O
c)
a) closed
b) softspace

C
Enter your input: Hello Python
c) rename
Received input is : Python d) mode

T.
d) None of the mentioned Answer: c

O
Explanation: rename is not the attribute of
Answer: a file rest all are files attributes.
Explanation: The raw_input([prompt])
function reads one line from standard input
and returns it as a string. This would prompt
you to enter any string and it would display
SP
Attribute

file.closed
Description

Returns true if file is c


G
losed, false otherwise.
same string on the screen. When I typed
“Hello Python!” file.mode Returns access mode with
LO

which file was opened.


3. What will be the output of the following
file.name Returns name of the file.
Python code?
.B

file.softspace Returns false if space ex


1. str = input("Enter your input: "); plicitly required with print, true otherw
ise.
17

2. print "Received input is : ", str


5. What is the use of tell() method in python?
a) a) tells you the current position within the file
b) tells you the end position within the file
-R

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


0,2)]
c) tells you the file is opened or not
d) none of the mentioned
SE

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
C

words, the next read or write will occur at that


Enter your input: [x*5 for x in range(2,1
0,2)]
many bytes from the beginning of the file.

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: https://cse-r17.blogspot.com 118


First Semester MCQ for Regulations 2017

b) rename(new_file_name, 14.
current_file_name,)
c) rename(()(current_file_name, 15. # Close opened file
new_file_name)) 16. fo.close()
d) none of the mentioned
a) Compilation Error
Answer: a
b) Syntax Error
Explanation: This is the correct syntax which
c) Displays Output
has shown below.

M
d) None of the mentioned
rename(current_file_name, new_file_name)
Answer: c

O
7. What is the current syntax of remove() a
Explanation: It displays the output as shown
file?
below. The method next() is used when a file

C
a) remove(file_name)
is used as an iterator, typically in a loop, the
b) remove(new_file_name, next() method is called repeatedly. This

T.
current_file_name,)
method returns the next input line, or raises
c) remove(() , file_name))
StopIteration when EOF is hit.
d) none of the mentioned

O
Output:
Answer: a
Explanation: remove(file_name)

8. What will be the output of the following


SP
Name of the file: foo.txt

Line No 0 - This is 1st line


G
Python code?
Line No 1 - This is 2nd line
LO

1. fo = open("foo.txt", "rw+")
2. print "Name of the file: ", fo.name
Line No 2 - This is 3rd line
.B

3.
4. # Assuming file has following 5 lin
17

es Line No 3 - This is 4th line

5. # This is 1st line


-R

6. # This is 2nd line Line No 4 - This is 5th line

7. # This is 3rd line 9. What is the use of seek() method in files?


SE

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
C

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: https://cse-r17.blogspot.com 119


First Semester MCQ for Regulations 2017

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

whence — This is optional and defaults to 0 3. name = ''


which means absolute file positioning, other 4. while True:

M
values are 1 which means seek relative to the
current position and 2 means seek relative to 5. c = sys.stdin.read(1)

O
the file’s end.
6. if c == '\n':

C
10. What is the use of truncate() method in
file? 7. break

T.
a) truncates the file size 8. name = name + c
b) deletes the content of the file
c) deletes the file size 9.

O
d) none of the mentioned
10. print 'Your name is:', name
Answer: a
Explanation: The method truncate() truncates
the file size. Following is the syntax for
SP
a) sanfoundry
b) sanfoundry, sanfoundry
G
truncate() method: c) San
fileObject.truncate( [ size ]) d) None of the mentioned
LO

Parameters Answer: a
size — If this optional argument is present, Explanation: In order to work with standard
the file is truncated to (at most) that size. I/O streams, we must import the sys module.
.B

The read() method reads one character from


1. Which is/are the basic I/O connections in the standard input. In our example we get a
prompt saying “Enter your name”. We enter
17

file?
a) Standard Input our name and press enter. The enter key
b) Standard Output generates the new line character: \n.
c) Standard Errors Output:
-R

d) All of the mentioned Enter your name: sanfoundry


Your name is: sanfoundry
Answer: d
SE

Explanation: Standard input, standard output 3. What will be the output of the following
and standard error. Standard input is the data Python code?
that goes to the program. The standard input
C

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: https://cse-r17.blogspot.com 120


First Semester MCQ for Regulations 2017

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
simple textual data. What if we are working

M
Output:
Hello with objects rather than simple text? For such
Python situations, we can use the pickle module. This

O
module serializes Python objects. The Python
objects are converted into byte streams and

C
written to text files. This process is called
4. Which of the following mode will refer to pickling. The inverse operation, reading from

T.
binary data? a file and reconstructing objects is called
a) r deserializing or unpickling.

O
b) w
c) + 7. What is the correct syntax of open()
function?
d) b

Answer:d
SP
a) file = open(file_name [, access_mode][,
buffering])
b) file object = open(file_name [,
Explanation: Mode Meaning is as explained
G
below: access_mode][, buffering])
r Reading c) file object = open(file_name)
LO

w Writing d) none of the mentioned


a Appending
b Binary data Answer: b
.B

+ Updating. Explanation: Open() function correct syntax


with the parameter details as shown below:
5. What is the pickling? file object = open(file_name [, access_mode]
17

a) It is used for object serialization [, buffering])


b) It is used for object deserialization Here is parameters’ detail:
c) None of the mentioned file_name: The file_name argument is a string
-R

d) All of the mentioned value that contains the name of the file that
you want to access.
Answer: a access_mode: The access_mode determines
SE

Explanation: Pickle is the standard the mode in which the file has to be opened,
mechanism for object serialization. Pickle i.e., read, write, append, etc. A complete list
uses a simple stack-based virtual machine that of possible values is given below in the table.
records the instructions used to reconstruct This is optional parameter and the default file
C

the object. This makes pickle vulnerable to access mode is read (r).
security risks by malformed or maliciously buffering: If the buffering value is set to 0, no
constructed data, that may cause the buffering will take place. If the buffering
deserializer to import arbitrary modules and value is 1, line buffering will be performed
instantiate any object. while accessing a file. If you specify the
buffering value as an integer greater than 1,
then buffering action will be performed with

Downloaded From: https://cse-r17.blogspot.com 121


First Semester MCQ for Regulations 2017

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
sizehint — This is the number of bytes to be
a) Compilation Error read from the file.

T.
b) Runtime Error
c) No Output 1. In file handling, what does this terms

O
d) Flushes the file when closing them means “r, a”?
a) read, append
Answer: d
Explanation: The method flush() flushes the
internal buffer. Python automatically flushes
the files when closing them. But you may
SP
b) append, read
c) write, append
d) none of the mentioned
G
want to flush the data before closing any file. Answer: a
Explanation: r- reading, a-appending.
LO

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


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

c) fileObject.writelines(sequence) b) Write
d) none of the mentioned c) Append
d) None of the mentioned
17

Answer: c
Explanation: The method writelines() writes Answer: b
a sequence of strings to the file. The sequence Explanation: This opens the file for writing.
-R

can be any iterable object producing strings, It will create the file if it doesn’t exist, and if
typically a list of strings. There is no return it does, it will overwrite it.
value. fh = open(“filename_here”, “w”).
SE

Syntax
Following is the syntax for writelines() 3. What is the use of “a” in file handling?
method: a) Read
fileObject.writelines( sequence ). b) Write
C

c) Append
10. Correct syntax of file.readlines() is? d) None of the mentioned
a) fileObject.readlines( sizehint );
b) fileObject.readlines(); Answer: c
c) fileObject.readlines(sequence) Explanation: This opens the fhe file in
d) none of the mentioned appending mode. That means, it will be open
for writing and everything will be written to

Downloaded From: https://cse-r17.blogspot.com 122


First Semester MCQ for Regulations 2017

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

M
python?
Answer: a a) Close()

O
Explanation: The read function reads all b) Stop()
characters fh = open(“filename”, “r”) c) End()

C
content = fh.read(). d) Closefile()

T.
5. Which function is used to read single line Answer: a
from file? Explanation: f.close()to close it and free up
a) Readline() any system resources taken up by the open

O
b) Readlines() file.
c) Readstatement()
d) Readfullline()

Answer: b
SP
9. Is it possible to create a text file in python?
a) Yes
b) No
G
Explanation: The readline function reads a c) Machine dependent
single line from the file fh = open(“filename”, d) All of the mentioned
LO

“r”)
content = fh.readline(). Answer: a
Explanation: Yes we can create a file in
6. Which function is used to write all the python. Creation of file is as shown below.
.B

characters? file = open(“newfile.txt”, “w”)


a) write() file.write(“hello world in the new file\n”)
17

b) writecharacters() file.write(“and another line\n”)


c) writeall() file.close().
d) writechar()
10. Which of the following are the modes of
-R

Answer: a both writing and reading in binary format in


Explanation: To write a fixed sequence of file?
SE

characters to a file a) wb+


fh = open(“hello.txt”,”w”) b) w
write(“Hello World”). c) wb
d) w+
C

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: https://cse-r17.blogspot.com 123


First Semester MCQ for Regulations 2017

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

M
existing file if the file exists. If the file does Answer: d
not exist, creates a new file for reading and Explanation: fp.size has not been

O
writing. implemented.

C
1. Which of the following is not a valid mode 5. How do you close a file object (fp)?
to open a file? a) close(fp)

T.
a) ab b) fclose(fp)
b) rw c) fp.close()
d) fp.__close__()

O
c) r+
d) w+
Answer: c
Answer: b
Explanation: Use r+, w+ or a+ to perform
both read and write operations using a single
SP
Explanation: close() is a method of the file
object.
G
file object. 6. How do you get the current position within
the file?
LO

2. What is the difference between r+ and w+ a) fp.seek()


modes? b) fp.tell()
a) no difference c) fp.loc
d) fp.pos
.B

b) in r+ the pointer is initially placed at the


beginning of the file and the pointer is at the
end for w+ Answer: b
17

c) in w+ the pointer is initially placed at the Explanation: It gives the current position as
beginning of the file and the pointer is at the an offset from the start of file.
end for r+
7. How do you rename a file?
-R

d) depends on the operating system


a) fp.name = ‘new_name.txt’
Answer: b b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
SE

Explanation: none.
d) os.set_name(existing_name, new_name)
3. How do you get the name of a file from a
file object (fp)? Answer: b
C

a) fp.name Explanation: os.rename() is used to rename


b) fp.file(name) files.
c) self.__name__(fp)
d) fp.__name__() 8. How do you delete a file?
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: https://cse-r17.blogspot.com 124


First Semester MCQ for Regulations 2017

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)

M
d) none of the mentioned
class foo:
def __init__(self, x):

O
Answer: a self.x = x
Explanation: 0 indicates that the offset is def __less__(self, other):

C
with respect to the start. if self.x > other.x:
return False

T.
10. What happens if no arguments are passed else:
return True
to the seek function?
a) file position is set to the start of file

O
c)
b) file position is set to the end of file
c) file position remains unchanged
d) error

Answer: d
SP
class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
G
if self.x < other.x:
Explanation: seek() takes at least one return True
argument. else:
LO

return False
1. Which function is called when the
following Python code is executed? d)
.B

f = foo() class foo:


format(f) def __init__(self, x):
self.x = x
17

a) format() def __less__(self, other):


b) __format__() if self.x < other.x:
return False
c) str() else:
-R

d) __str__() return True

Answer: d Answer: c
SE

Explanation: Both str(f) and format(f) call Explanation: __lt__ overloads the <
f.__str__(). operator>.

2. Which of the following Python code will


C

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: https://cse-r17.blogspot.com 125


First Semester MCQ for Regulations 2017

Answer: a Answer: a
Explanation: Refer documentation. Explanation: The function __add__() is
called first since it is within the bracket. The
4. Which operator is overloaded by function __str__() is then called on the object
__invert__()? that we received after adding A and B.
a) !
b) ~ 9. Which operator is overloaded by the
c) ^ __or__() function?
d) – a) ||

M
b) |
Answer: b c) //

O
Explanation: __invert__() overloads ~. d) /

C
5. Which function overloads the == operator? Answer: b
a) __eq__() Explanation: The function __or__()

T.
b) __equ__() overloads the bitwise OR operator |.
c) __isequal__()
d) none of the mentioned 10. Which function overloads the // operator?

O
a) __div__()
Answer: a b) __ceildiv__()
Explanation: The other two do not exist.

6. Which operator is overloaded by __lg__()?


SP
c) __floordiv__()
d) __truediv__()
G
a) < Answer: c
b) > Explanation: __floordiv__() is for //.
LO

c) !=
d) none of the mentioned
TOPIC 5.2 EXCEPTION
Answer: d HANDLING
.B

Explanation: __lg__() is invalid.


1. How many except statements can a try-
17

7. Which function overloads the >> operator? except block have?


a) __more__() a) zero
b) __gt__() b) one
c) __ge__()
-R

c) more than one


d) none of the mentioned d) more than zero
Answer: d
SE

Answer: d
Explanation: __rshift__() overloads the >> Explanation: There has to be at least one
operator. except statement.
C

8. Let A and B be objects of class Foo. Which 2. When will the else part of try-except-else
functions are called when print(A + B) is be executed?
executed? a) always
a) __add__(), __str__() b) when an exception occurs
b) __str__(), __add__() c) when no exception occurs
c) __sum__(), __str__() d) when an exception occurs in to except
d) __str__(), __sum__() block

Downloaded From: https://cse-r17.blogspot.com 126


First Semester MCQ for Regulations 2017

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:
Explanation: The finally block is always

M
# Do something
finally: executed.
# Do something

O
7. What will be the output of the following
a) no, there is no such thing as finally Python code?

C
b) no, finally cannot be used with except
c) no, finally must come before except def foo():

T.
d) yes try:
return 1
finally:
Answer: b

O
return 2
Explanation: Refer documentation. k = foo()
print(k)
4. Is the following Python code valid?
try:
SP
a) 1
b) 2
G
# Do something c) 3
except:
# Do something d) error, there is more than one return
LO

else: statement in a single try-finally block


# Do something
Answer: b
a) no, there is no such thing as else Explanation: The finally block is executed
.B

b) no, else cannot be used with except even there is a return statement in the try
c) no, else must come before except block.
17

d) yes
8. What will be the output of the following
Answer: d Python code?
Explanation: Refer documentation.
-R

def foo():
5. Can one block of except statements handle try:
print(1)
multiple exception?
SE

finally:
a) yes, like except TypeError, SyntaxError print(2)
[,…] foo()
b) yes, like except [TypeError, SyntaxError]
C

c) no a) 1 2
d) none of the mentioned b) 1
c) 2
Answer: a d) none of the mentioned
Explanation: Each type of exception can be
specified directly. There is no need to put it in Answer: a
a list. Explanation: No error occurs in the try block

Downloaded From: https://cse-r17.blogspot.com 127


First Semester MCQ for Regulations 2017

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'

M
else:
print("someError has not occurre a) Assertion Error
d") b) 10 8

O
except "someError":
print ("someError has occurred") c) No output
d) 108

C
a) someError has occurred
Answer: c

T.
b) someError has not occurred
c) invalid code Explanation: The code shown above results
d) none of the mentioned in an error if and only if x<y. However, in the

O
above case, since x>y, there is no error. Since
Answer: c there is no print statement, hence there is no
Explanation: A new exception class must
inherit from a BaseException. There is no
such inheritance here.
SP
output.

3. What will be the output of the following


Python code?
G
10. What happens when ‘1’ == 1 is executed?
#generator
LO

a) we get a True
def f(x):
b) we get a False yield x+1
c) an TypeError occurs g=f(8)
d) a ValueError occurs print(next(g))
.B

Answer: b a) 8
Explanation: It simply evaluates to False and b) 9
17

does not raise any exception. c) 7


d) Error
1. The following Python code will result in an
-R

error if the input value is entered as -5. Answer: b


Explanation: The code shown above returns
assert False, 'Spanish' the value of the expression x+1, since we
SE

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
C

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: https://cse-r17.blogspot.com 128


First Semester MCQ for Regulations 2017

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:

M
f(x, 4)
d) No output finally:
print('after f')

O
Answer: d print('after f?')
Explanation: The code shown above will not a()

C
yield any output. This is because when we try
to yield 9, and there is no next(g), the a) No output

T.
iteration stops. Hence there is no output. b) after f?
c) error
5. What will be the output of the following d) after f

O
Python code?
Answer: c
def f(x):
yield x+1
print("test")
SP
Explanation: This code shown above will
result in an error simply because ‘f’ is not
defined. ‘try’ and ‘finally’ are keywords used
G
yield x+2
in exception handling.
g=f(10)
print(next(g))
LO

print(next(g)) 7. What will be the output of the following


Python code?
a) No output
b) def f(x):
.B

for i in range(5):
yield i
11
g=f(8)
17

print(list(g))
test

12 a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
-R

c) c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
11
SE

Answer: a
test
Explanation: The output of the code shown
d) 11 above is a list containing whole numbers in
C

the range (5). Hence the output of this code


Answer: b is: [0, 1, 2, 3, 4].
Explanation: The code shown above results
in the output: 8. The error displayed in the following
Python code is?
11
test import itertools
12 l1=(1, 2, 3)

Downloaded From: https://cse-r17.blogspot.com 129


First Semester MCQ for Regulations 2017

l2=[4, 5, 6] a=False
l=itertools.chain(l1, l2) while not a:
print(next(l1)) try:
f_n = input("Enter file name")
a) ‘list’ object is not iterator i_f = open(f_n, 'r')
b) ‘tuple’ object is not iterator except:
print("Input file not found")
c) ‘list’ object is iterator
d) ‘tuple’ object is iterator a) No error
b) Assertion error

M
Answer: b
c) Input output error
Explanation: The error raised in the code
d) Name error
shown above is that: ‘tuple’ object is not

O
iterator. Had we given l2 as argument to next, Answer: a
the error would have been: ‘list’ object is not

C
Explanation: In the code shown above, if the
iterator. input file in not found, then the statement:

T.
“Input file not found” is printed on the screen.
9. Which of the following is not an exception
The user is then prompted to reenter the file
handling keyword in Python?
name. Error is not thrown.

O
a) try
b) except 2. What will be the output of the following
c) accept
d) finally SP
Python code?

lst = [1, 2, 3]
Answer: c
G
lst[3]
Explanation: The keywords ‘try’, ‘except’
a) NameError
LO

and ‘finally’ are exception handling keywords


in python whereas the word ‘accept’ is not a b) ValueError
keyword at all. c) IndexError
d) TypeError
.B

10. What will be the output of the following


Python code? Answer: c
Explanation: The snippet of code shown
17

g = (i for i in range(5)) above throws an index error. This is because


type(g) the index of the list given in the code, that is,
3 is out of range. The maximum index of this
a) class <’loop’>
-R

list is 2.
b) class <‘iteration’>
c) class <’range’> 3. What will be the output of the following
SE

d) class <’generator’> Python code?


Answer: d t[5]
Explanation: Another way of creating a
C

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: https://cse-r17.blogspot.com 130


First Semester MCQ for Regulations 2017

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

M
a) NameError Explanation: The first code results in a
b) IndexError ValueError. This is because when we enter the

O
c) ValueError input as -6, we are trying to find the factorial
d) TypeError of a negative number, which is not possible.

C
The second code results in a NameError. This
Answer: d is because we have not imported the math

T.
Explanation: The line of code shown above module. Hence the name ‘math’ is undefined.
will result in a type error. This is because the
operand ‘+’ is not supported when we 7. What will be the output of the following

O
combine the data types ‘int’ and ‘str’. Sine Python code?
this is exactly what we have done in the code
shown above, a type error is thrown.

5. What will be the output of the following


SP
def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
G
Python code? getMonth(6)
LO

int('65.43') a) ValueError
b) Invalid
a) ImportError c) 6
b) ValueError d) ValueError(“Invalid”)
.B

c) TypeError
d) NameError Answer: c
Explanation: In the code shown above, since
17

Answer: b the value passed as an argument to the


Explanation: The snippet of code shown function is between 1 and 12 (both included),
above results in a value error. This is because hence the output is the value itself, that is 6. If
-R

there is an invalid literal for int() with base the value had been above 12 and less than 1, a
10: ’65.43’. ValueError would have been thrown.
SE

6. Compare the following two Python codes 8. What will be the output of the following
shown below and state the output if the input Python code if the input entered is 6?
entered in each case is -6?
C

valid = False
CODE 1 while not valid:
import math try:
num=int(input("Enter a number of whose fa n=int(input("Enter a number"))
ctorial you want to find")) while n%2==0:
print(math.factorial(num)) print("Bye")
valid = True
CODE 2 except ValueError:
num=int(input("Enter a number of whose fa print("Invalid")

Downloaded From: https://cse-r17.blogspot.com 131


First Semester MCQ for Regulations 2017

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

M
number has been given as input. If an odd c) AssignmentError
number had been given as input, then there d) ValueError

O
would have been no output.
Answer: c

C
9. Identify the type of error in the following Explanation: NameError, IOError and
Python codes? ValueError are standard exceptions in Python

T.
whereas Assignment error is not a standard
Print(“Good Morning”) exception in Python.
print(“Good night)

O
12. Syntax errors are also known as parsing
a) Syntax, Syntax
errors.
b) Semantic, Syntax
c) Semantic, Semantic
d) Syntax, Semantic
SP
a) True
b) False
G
Answer: a
Answer: b Explanation: Syntax errors are known as
LO

Explanation: The first code shows an error


parsing errors. Syntax errors are raised when
detected during execution. This might occur
there is a deviation from the rules of a
occasionally. The second line of code
language. Hence the statement is true.
represents a syntax error. When there is
.B

deviation from the rules of a language, a 13. An exception is ____________


syntax error is thrown. a) an object
17

b) a special function
10. Which of the following statements is true?
c) a standard module
a) The standard exceptions are automatically d) a module
imported into Python programs
-R

b) All raised standard exceptions must be Answer: a


handled in Python Explanation: An exception is an object that
c) When there is a deviation from the rules of
SE

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
C

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: https://cse-r17.blogspot.com 132


First Semester MCQ for Regulations 2017

Answer: d Answer: c
Explanation: IOError exceptions are raised Explanation: The total size of the program
as a result of an error in opening or closing a remains the same regardless of whether
particular file. modules are used or not. Modules simply
divide the program.
15. Which of the following blocks will be
executed whether an exception is thrown or 3. Program code making use of a given
not? module is called a ______ of the module.
a) except a) Client

M
b) else b) Docstring
c) finally c) Interface

O
d) assert d) Modularity

C
Answer: c Answer: a
Explanation: The statements in the finally Explanation: Program code making use of a

T.
block will always be executed, whether an given module is called the client of the
exception is thrown or not. This clause is module. There may be multiple clients for a
used to close the resources used in a code. module.

O
4. ______ is a string literal denoted by triple
TOPIC 5.3 MODULES AND
PACKAGES SP
quotes for providing the specifications of
certain program elements.
a) Interface
G
1. Which of these definitions correctly b) Modularity
describes a module? c) Client
LO

a) Denoted by triple quotes for providing the d) Docstring


specification of certain program elements
b) Design and implementation of specific Answer: d
Explanation: Docstring used for providing
.B

functionality to be incorporated into a


program the specifications of program elements.
c) Defines the specification of how it is to be
17

used 5. Which of the following is true about top-


d) Any program that reuses code down design process?
a) The details of a program design are
addressed before the overall design
-R

Answer: b
Explanation: The term “module” refers to the b) Only the details of the program are
implementation of specific functionality to be addressed
SE

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
C

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: https://cse-r17.blogspot.com 133


First Semester MCQ for Regulations 2017

6. In top-down design every module is broken become part of the same scope. Since both
into same number of submodules. the modules have the same function name,
a) True there is a name clash.
b) False
9. Which of the following isn’t true about
Answer: b main modules?
Explanation: In top-down design every a) When a python file is directly executed, it
module can even be broken down into is considered main module of a program
different number of submodules. b) Main modules may import any number of

M
modules
7. All modular designs are because of a top- c) Special name given to main modules is:

O
down design process. __main__
a) True d) Other main modules can import main

C
b) False modules

T.
Answer: b Answer: d
Explanation: The details of the program can Explanation: Main modules are not meant to
be addressed before the overall design too. be imported into other modules.

O
Hence, all modular designs are not because of
a top-down design process. 10. Which of the following is not a valid

8. What will be the output of the following


Python code?
SP
namespace?
a) Global namespace
b) Public namespace
G
c) Built-in namespace
#mod1 d) Local namespace
LO

def change(a):
b=[x*2 for x in a]
print(b) Answer: b
#mod2 Explanation: During a Python program
execution, there are as many as three
.B

def change(a):
b=[x*x for x in a] namespaces – built-in namespace, global
print(b)
namespace and local namespace.
from mod1 import change
17

from mod2 import change


#main 11. Which of the following is false about
s=[1,2,3] “import modulename” form of import?
change(s) a) The namespace of imported module
-R

becomes part of importing module


a) [2,4,6] b) This form of import prevents name clash
b) [1,4,9]
SE

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
C

[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: https://cse-r17.blogspot.com 134


First Semester MCQ for Regulations 2017

12. Which of the following is false about from math import factorial
“from-import” form of import? print(math.factorial(5))
a) The syntax is: from modulename import
identifier a) 120
b) This form of import prevents name clash b) Nothing is printed
c) The namespace of imported module c) Error, method factorial doesn’t exist in
becomes part of importing module math module
d) Error, the statement should be:
d) The identifiers in module are accessed
print(factorial(5))
directly as: identifier

M
Answer: d
Answer: b

O
Explanation: In the “from-import” form of
Explanation: In the “from-import” form of
import, the imported identifiers (in this case
import, there may be name clashes because

C
factorial()) aren’t specified along with the
names of the imported identifiers aren’t
module name.
specified along with the module name.

T.
15. What is the order of namespaces in which
13. Which of the statements about modules is
Python looks for an identifier?
false?

O
a) Python first searches the global namespace,
a) In the “from-import” form of import,
then the local namespace and finally the built-
identifiers beginning with two underscores
are private and aren’t imported
b) dir() built-in function monitors the items in
the namespace of the main module
SP
in namespace
b) Python first searches the local namespace,
then the global namespace and finally the
G
built-in namespace
c) In the “from-import” form of import, all
c) Python first searches the built-in
identifiers regardless of whether they are
LO

namespace, then the global namespace and


private or public are imported
finally the local namespace
d) When a module is loaded, a compiled
d) Python first searches the built-in
version of the module with file extension .pyc
namespace, then the local namespace and
.B

is automatically produced
finally the global namespace
Answer: c
17

Answer: b
Explanation: In the “from-import” form of
Explanation: Python first searches for the
import, identifiers beginning with two
local, then the global and finally the built-in
underscores are private and aren’t imported.
namespace.
-R

14. What will be the output of the following


Python code?
SE
C

Downloaded From: https://cse-r17.blogspot.com 135

You might also like