Sei sulla pagina 1di 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 word algorithm refers to a special method
usable by a computer for the solution to a
problem. The statement of the problem
SEMESTER - I specifies in general terms the desired
input/output relationship.

3. This characteristic often draws the line


MCQ - Regulations between what is feasible and what is
impossible.
2017 a) Performance
b) System Evaluation
c) Modularity
Department of CSE d) Reliability

Answer: a
Explanation: Algorithms help us to
understand scalability. Performance often
draws the line between what is feasible and
UNIT I ALGORITHMIC what is impossible.
PROBLEM SOLVING 4. The time that depends on the input: an
already sorted sequence that is easier to sort.
TOPIC 1.1 ALGORITHMS a) Process
b) Evaluation
1. The word ____________comes from the c) Running
name of a Persian mathematician Abu Ja’far d) Input
Mohammed ibn-i Musa al Khowarizmi.
Answer: c
a) Flowchart
Explanation: The running time depends on
b) Flow
the input: an already sorted sequence is easier
c) Algorithm
to sort. The running time is given by the size
d) Syntax
of the input, since short sequences are easier
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

www.studymaterialz.in 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.

6. When an algorithm is written in the form of 10. A data structure that follows the FIFO
a programming language, it becomes a principle.
_________ a) Queue
a) Flowchart b) LL
b) Program c) Stack
c) Pseudo code d) Union
d) Syntax
Answer: a
Answer: b Explanation: The answer is Queue. A Queue
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.
TOPIC 1.2 FLOW CHARTS
7. Any algorithm is a program.
a) True 1. The symbol denotes _______
b) False

Answer: b
a) I/O
Explanation: The statement is false. An
b) Flow
algorithm is represented in the form of a
c) Terminal
programming language is called a program.
d) Decision
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
It is used for indication of start and stop
one and removed from the other end.
nodes of a program.
a) Stack
b) Queue 2. In computer science, algorithm refers to a
c) Linked List pictorial representation of a flowchart.
d) Array a) True
b) False
Answer: b
Explanation: In a queue, the items are Answer: b
inserted from the rear end and deleted from Explanation: The statement is false. The
the front end. correct statement would be: In computer
science, flowchart refers to a pictorial
9. Another name for 1-D arrays.
representation of an algorithm.
a) Linear arrays

www.studymaterialz.in 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.
flowchart is nothing but a pictorial a) True
representation of an algorithm. b) False

4. Actual instructions in flowcharting are Answer: b


represented in __________ Explanation: The statement is false. There
a) Circles should be no set standards on the amount of
b) Boxes details that should be provided in a flowchart.
c) Arrows
d) Lines 8. A detailed flowchart is called ______
a) Stack
Answer: b b) Macro
Explanation: The actual instructions are c) Micro
written in boxes. Boxes are connected by d) Union
using arrows to indicate the exact flow of a
flowchart and the order in which they are to Answer: c
be executed. Explanation: A detailed flowchart or a
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.

9. Which of the following is not an advantage


of a flowchart?
a) Decision a) Better communication
b) Initiation b) Efficient coding
c) Initialization c) Systematic testing
d) I/O d) Improper documentation
Answer: a Answer: d
Explanation: A diamond shape box denotes Explanation: Flowcharts provide a proper
the decision making statements. It jumps to a documentation. It also provides systematic
truth value or a false value. debugging.
6. A box that can represent two different 10. A flowchart that outlines the main
conditions. segments of a program.
a) Rectangle a) Queue
b) Diamond b) Macro
c) Circle c) Micro
d) Parallelogram d) Union

www.studymaterialz.in 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
• Repetition
1. A ______________ is diagram that depicts • Case
the flow of a program. • Sequence.
a) Algorithm
b) Hash Table 5. The action performed by a ___________
c) Graph structure must eventually cause the loop to
d) Flowchart terminate.
a) sequence
Answer: d b) case
Explanation: A flowchart is a diagram that c) repetition
helps us determine the flow of the program. d) process
Other options are irrelevant.
Answer: c
2. Terminals are represented by diagonals in a Explanation: The action performed by a
flowchart. repetition structure must eventually cause the
a) True loop to terminate. Otherwise, an infinite loop
b) False is created.

Answer: b 6. The following symbol denotes:


Explanation: The statement is false.
Terminals are represented by rounded
rectangles. They indicate the starting or
ending point in a flowchart. a) Module
b) Terminal
3. The operation represented by c) Process
parallelograms. d) i/o operation
a) Input/Output
b) Assignment Answer: a
c) Comparison Explanation: This symbol is that of a
d) Conditions module. The terminal is denoted by a rounded
rectangle. I/O operation by a parallelogram
Answer: a and process by a rectangle.
Explanation: The input/output operations are
represented by parallelograms. They
generally are used to display messages during
input and output part of a program.

4. Which of the following is not a flowchart


structure?

Downloaded From: https://cse-r17.blogspot.com 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
b) case a) Decision
c) repetition b) Input/Output
d) process c) Process
d) Module
Answer: c
Explanation: This is a repetition structure. Answer: a
The action performed by a repetition structure Explanation: The answer is decision.
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
is true or false.
8. What type of a structure is this?
TOPIC 1.4 PSEUDO CODE

1. Keep the statement language


______________ while writing a pseudo
code.
a) Dependent
b) Independent
a) sequence c) Case sensitive
b) case d) Capitalized
c) repetition
d) process Answer: b
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
cases are given along with a default case in multiline structures.
the case structure.
2. Capitalize initial keyword – This is a rule
9. A _______ is a connector showing the while writing a pseudo code.
relationship between the representative a) True
shapes. b) False
a) line
b) arrow Answer: a
c) Process Explanation: The statement is true. It is an
d) box important rule to capitalize the initial
keyword while writing a pseudo code.
Answer: b
Explanation: Arrows are the connectors that 3. Which of the following is not a keyword?
show the relationship between different a) Read

www.studymaterialz.in 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
4. ______________ is used to show hierarchy c) Tokens
in a pseudo code. d) Functions
a) Indentation
b) Curly Braces Answer: b
c) Round Brackets Explanation: Variables begin with a
d) Semicolon lowercase. They contain no spaces. They also
involve the consistent use of names.
Answer: a
Explanation: Each design structure uses a 8. Another notation for exponentiation.
particular indentation pattern. a) *
Indentation should be considered in the b) **
following cases: c) ***
Sequence d) *^
Selection
Loop. Answer: b
Explanation: Double asterisk sign is also
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) write a) ()
c) READ b) {}
d) WRITE c) [].
d) ” ”
Answer: c
Explanation: The READ statement is used to Answer: a
take the input. READ being a keyword should Explanation: Parenthesis is used for
be in capital letters. grouping while working with fields. There are
other symbols like *, +, -, **, etc.
6. _____________ are identified by their
addresses, we give them names (field names / 10. A statement used to close the IF block.
variable names) using words. a) ELSE
a) Memory variables b) ELSEIF
b) Memory Locations c) END
c) Memory Addresses d) ENDIF
d) Data variables
Answer: d
Answer: b Explanation: The answer is ENDIF. It is used
Explanation: Memory locations are

www.studymaterialz.in 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
STATEMENTS with an underscore discouraged?
a) they are used to indicate a private variables
of a class
TOPIC 2.1 VARIABLES b) they confuse the interpreter
c) they are used to indicate global variables
1. Is Python case sensitive when dealing with d) they slow down execution
identifiers?
a) yes Answer: a
b) no Explanation: As Python has no concept of
c) machine dependent private variables, leading underscores are
d) none of the mentioned used to indicate variables that must not be
accessed from outside the class.
Answer: a
Explanation: Case is always significant. 6. Which of the following is not a keyword?
a) eval
2. What is the maximum possible length of an b) assert
identifier? c) nonlocal
a) 31 characters d) pass
b) 63 characters
c) 79 characters Answer: a
d) none of the mentioned Explanation: eval can be used as a variable.

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


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

www.studymaterialz.in 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.
a) abc = 1,000,000
b) a b c = 1000 2000 3000 3. What is the order of precedence in python?
c) a,b,c = 1000, 2000, 3000 i) Parentheses
d) a_b_c = 1,000,000 ii) Exponential
iii) Multiplication
Answer: b iv) Division
Explanation: Spaces are not allowed in v) Addition
variable names. vi) Subtraction
a) i,ii,iii,iv,v,vi
10. Which of the following cannot be a b) ii,i,iii,iv,v,vi
variable? c) ii,i,iv,iii,v,vi
a) __init__ d) i,ii,iii,iv,vi,v
b) in
c) it Answer: a
d) on Explanation: For order of precedence, just
remember this PEMDAS (similar to
Answer: b BODMAS).
Explanation: in is a keyword.
4. What is the answer to this expression, 22 %
TOPIC 2.2 OPERATORS 3 is?
a) 7
b) 1
1. Which is the correct operator for c) 0
power(xy)? d) 5
a) X^y
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
is, 1.
Answer: b
Explanation: In python, power operator is 5. Mathematical operations can be performed
x**y i.e. 2**3=8. on a string.
a) True
2. Which one of these is floor division? b) False
a) /
b) // Answer: b
c) % Explanation: You can’t perform
d) None of the mentioned mathematical operation on string even if the
string is in the form: ‘1234…’.

www.studymaterialz.in 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. >>>

www.studymaterialz.in 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
c) ValueError
4. Which of the following will run without d) TypeError
errors?
a) round(45.8) Answer: b
b) round(6352.898,2,5) Explanation: Mango is not defined hence
c) round() name error.
d) round(7463.123,2,1)
8. What will be the output of the following
Answer: a Python code snippet?
Explanation: Execute help(round) in the
1. def example(a):
shell to get details of the parameters that are
passed into the round function. 2. a = a + '2'

5. What is the return type of function id? 3. a = a*2


a) int
b) float 4. return a
c) bool
5. >>>example("hello")
d) dict
a) indentation Error
Answer: a
b) cannot perform mathematical operation on
Explanation: Execute help(id) to find out
strings
details in python shell.id returns a integer
c) hello2
value that is unique.
d) hello2hello2
6. In python we do not specify types, it is
Answer: a
directly interpreted by the compiler, so
Explanation: Python codes have to be
consider the following operation to be
indented properly.
performed.
9. What data type is the object below?
1. >>>x = 13 ? 2
L = [1, 23, 'hello', 1]
objective is to make sure x has a integer
value, select all that apply (python 3.xx) a) list
a) x = 13 // 2 b) dictionary
b) x = int(13 / 2) c) array
c) x = 13 % 2 d) tuple
d) All of the mentioned
Answer: a
Answer: d Explanation: List data type can store any
Explanation: // is integer operation in python

www.studymaterialz.in 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
Answer: d
Explanation: Dictionary stores values in 2. >>>grade2 = 90
terms of keys and values.
3. >>>average = (grade1 + grade2) / 2
11. Which of the following results in a
a) 85.0
SyntaxError?
b) 85.1
a) ‘”Once upon a time…”, she said.’
c) 95.0
b) “He said, ‘Yes!'”
d) 95.1
c) ‘3\’
d) ”’That’s okay”’ Answer: a
Explanation: Cause a decimal value of 0 to
Answer: c appear as output.
Explanation: Carefully look at the colons.
14. Select all options that print.
12. The following is displayed by a print
function call. Select all of the function calls hello-how-are-you
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’)
2. dick
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ +
3. harry ‘you’)

a) Answer: c
Explanation: Execute in the shell.
print('''tom
15. What is the return value of trunc()?
\ndick a) int
b) bool
\nharry''')
c) float
b) print(”’tomdickharry”’) d) None
c) print(‘tom\ndick\nharry’)
Answer: a
d)
Explanation: Execute help(math.trunc) to get
print('tom details.

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

www.studymaterialz.in 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
be represented accurately in binary. The c) x = 19023
round off errors from 0.1 and 0.2 accumulate d) x = 03964
and hence there is a difference of 5.5511e-17
between (0.1 + 0.2) and 0.3. Answer: d
Explanation: Numbers starting with a 0 are
2. Which of the following is not a complex octal numbers but 9 isn’t allowed in octal
number? numbers.
a) k = 2 + 3j
b) k = complex(2, 3) 7. What is the result of cmp(3, 1)?
c) k = 2 + 3l a) 1
d) k = 2 + 3J b) 0
c) True
Answer: c d) False
Explanation: l (or L) stands for long.
Answer: a
3. What is the type of inf? Explanation: cmp(x, y) returns 1 if x > y, 0 if
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) float(‘nan’)
Answer: c c) float(’56’+’78’)
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
4. What does ~4 evaluate to? float.
a) -5
b) -4 9. What is the result of round(0.5) –
c) -3 round(-0.5)?
d) +3 a) 1.0
b) 2.0
Answer: a c) 0.0
Explanation: ~x is equivalent to -(x+1). d) Value depends on Python version

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


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

www.studymaterialz.in 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
Python 2.7.17 (default, Nov 7 2019, 10:0
b) 12
7:09) c) 0.75
d) 7
>>> round(0.5)
Answer: d
1.0 Explanation: ^ is the Binary XOR operator.
>>> round(-0.5)

-1.0
TOPIC 2.5 PRECEDENCE OF
OPERATORS
>>>
1. The value of the expressions 4/(3*(2-1))
In the above output, you can see that the and 4/3*(2-1) is the same.
round() functions on 0.5 and -0.5 are moving a) True
away from 0 and hence “round(0.5) – b) False
(round(-0.5)) = 1 – (-1) = 2”
Answer: a
$ 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) making a difference. The result of both of
>>> round(0.5) these expressions is 1.333333333. Hence the
statement is true.
0
2. What will be the value of the following
>>> round(-0.5) Python expression?
0 4 + 3 % 5
>>> round(2.5)
a) 4
2 b) 7
c) 2
>>> round(3.5) d) 0
4
Answer: b
>>> Explanation: The order of precedence is: %,
+. Hence the expression above, on
simplification results in 4 + 3 = 7. Hence the
In the above output, you can see that the result is 7.
round() functions on 0.5 and -0.5 are moving

www.studymaterialz.in 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
decimal place.
Answer: b
Explanation: The above expression is 7. Which of the following is the truncation
evaluated as: 16%15//16, which is equal to division operator?
1//16, which results in 0. a) /
b) %
4. Which of the following operators has its c) //
associativity from right to left? d) |
a) +
b) // Answer: c
c) % Explanation: // is the operator for truncation
d) ** division. It is called so because it returns only
the integer part of the quotient, truncating the
Answer: d decimal part. For example: 20//3 = 6.
Explanation: All of the operators shown
above have associativity from left to right, 8. What are the values of the following
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
following Python expression? 2**3**2

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


b) 64, 64, 64
a) 43 c) 512, 512, 512
b) 44 d) 512, 64, 512
c) 22
d) 23 Answer: d
Explanation: Expression 1 is evaluated as:
Answer: b 2**9, which is equal to 512. Expression 2 is
Explanation: The expression shown above is evaluated as 8**2, which is equal to 64. The
an example of explicit conversion. It is last expression is evaluated as 2**(3**2).
evaluated as int(43.55+1) = int(44.55) = 44. This is because the associativity of **
Hence the result of this expression is 44. operator is from right to left. Hence the result
of the third expression is 512.
6. What is the value of the following
expression? 9. What is the value of the following
expression?
2+4.00, 2**4.0
8/4/2, 8/(4/2)

www.studymaterialz.in 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?
a) 4.7 – 1.5
10. What is the value of the following b) 7.9 * 6.3
expression? c) 1.7 % 2
d) 3.4 + 4.6
float(22//3+3/3)
Answer: c
a) 8 Explanation: Coercion is the implicit
b) 8.0 (automatic) conversion of operands to a
c) 8.3 common type. Coercion is automatically
d) 8.33 performed on mixed-type expressions. The
expression 1.7 % 2 is evaluated as 1.7 % 2.0
Answer: b
(that is, automatic conversion of int to float).
Explanation: The expression shown above is
evaluated as: float( 7+1) = float(8) = 8.0. 4. What will be the output of the following
Hence the result of this expression is 8.0. Python expression?
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)
c) (1,0)
a) Error
d) (3,1)
b) 1.0
c) 1.00 Answer: a
d) 1 Explanation: The expressions are evaluated
as: 4%3 and 6//2 respectively. This results in
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.
digits.
5. Which among the following list of
2. What will be the value of X in the
operators has the highest precedence?
following Python expression?
+, -, **, %, /, <<, >>, |
X = 2+9*((3*12)-8)/10
a) <<, >>
a) 30.0
b) **
b) 30.8
c) |
c) 28.4
d) %
d) 27.2

www.studymaterialz.in 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
a) 5.0
b) 5 Answer: b
c) 4.0 Explanation: The order of precedence is: **,
d) 4 //, +. The expression 4+2**5//10 is evaluated
as 4+32//10, which is equal to 4+3 = 7. Hence
Answer: c the result of the expression shown above is 7.
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.
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 Answer: b


example of type conversion? Explanation: The value of the expression
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
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.
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
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?

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


in an error?
a) float(‘10’) a) 8
b) int(‘10’) b) 1
c) float(’10.8’) c) 2
d) int(’10.8’) d) 4

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

www.studymaterialz.in 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)
gives the result 15. The expression int(‘1111’,
Answer: b 10) will give the result 1111.
Explanation: The binary form of the number
29 is 11101. Hence the output of this 6. What will be the output of the following
expression is ‘0b11101’. Python expression if x=15 and y=12?
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
b) 0b1101
x>>2 c) 12
d) 1101
a) 8
b) 4 Answer: c
c) 2 Explanation: The symbol ‘&’ represents
d) 1 bitwise AND. This gives 1 if both the bits are
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.
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?
4. What will be the output of the following a) int(1011)
Python expression? b) int(‘1011’,23)
int(1011)?
c) int(1011,2)
d) int(‘1011’)
a) 1011
b) 11 Answer: c
c) 13 Explanation: The expression int(1011,2)
d) 1101 results in an error. Had we written this
expression as int(‘1011’,2), then there would
Answer: a not be an error.
Explanation: The result of the expression
shown will be 1011. This is because we have 8. Which of the following represents the
not specified the base in this expression. bitwise XOR operator?
Hence it automatically takes the base as 10. a) &
b) ^
c) |
d) !

www.studymaterialz.in 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
a) ‘0bx1000’ Answer: a
b) 8 Explanation: The one’s complement of a
c) 1000 value is obtained by simply changing all the
d) ‘0b1000’ 1’s to 0’s and all the 0’s to 1’s. Hence the
one’s complement of 110010101 is
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
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
b) AND
10. What will be the output of the following c) XOR
Python expression? d) NOT
0x35 | 0x75
Answer: c
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.
d) 118
4. What will be the output of the following
Answer: c Python expression?
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
1110101, which is equal to 117. Hence the b) 4
result of the above expression is 117. c) 8
d) 12
1. It is not possible for the two’s complement
value to be equal to the original value in any Answer: c
case. Explanation: ^ is the XOR operator. The
a) True binary form of 4 is 0100 and that of 12 is
b) False 1100. Therefore, 0100^1100 is 1000, which is
equal to 8.
Answer: b
Explanation: In most cases the value of two’s 5. Any odd number on being AND-ed with
complement is different from the original ________ always gives 1. Hint: Any even
value. However, there are cases in which the number on being AND-ed with this value
two’s complement value may be equal to the always gives 0.

www.studymaterialz.in 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
always gives 0. Explanation: The code shown above is used
to swap the contents of two memory locations
6. What will be the value of the following using bitwise X0R operator. Hence the output
Python expression? of the code shown above is: 20 10.

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


a) 1011011
a) 0b10000 b) 11010100
b) 0b10001000 c) 11101011
c) 0b1000b1000 d) 10110011
d) 0b10000b1000
Answer: b
Answer: d Explanation: The binary form of -44 is
Explanation: The output of bin(10-2) = 00101100. The one’s complement of this
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).
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?
a) a<<2 ~100?
b) a<<4
a) 101
c) a>>2
b) -101
d) a>>4
c) 100
Answer: a d) -100
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
~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.

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

www.studymaterialz.in 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?
True
not(3>4)
b) not(1&1)

False a)

True True

c) True

False b)

False True

d) False

True c)

False False

Answer: d True
Explanation: The Boolean function returns
true if the argument passed to the bool d)
function does not amount to zero. In the first
False
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
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
function returns false, and the second
2. What will be the output of the following function returns false.
Python code snippet?

['hello', 'morning'][bool('')]
4. What will be the output of the following
a) error Python code?
b) no output
c) hello ['f', 't'][bool('spam')]
d) morning

www.studymaterialz.in 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
amount to zero. Else ‘t’ is printed. The Answer: c
argument given to the Boolean function in the Explanation: The code shown above shows
above case is ‘spam’, which does not amount two functions. In both the cases the right
to zero. Hence the output is t. operand is returned. This is because each
function is evaluated from left to right. Since
5. What will be the output of the following the left operand is false, it is assumed that the
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', '', []]
list(filter(bool, l))

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


b) [1, 0, 2, 0, ‘hello’, ”, []] Python code?
c) [1, 0, 2, ‘hello’, ”, []]
d) [1, 2, ‘hello’] class Truth:
pass
Answer: d x=Truth()
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
the output is: [1, 2, ‘hello’]. c) false
d) error
6. What will be the output of the following
Python code if the system date is 21st June, Answer: b
2017 (Wednesday)? Explanation: If the truth method is not
[] or {}
defined, the object is considered true. Hence
{} or [] the output of the code shown above is true.

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


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

[] a) error
b) hello
c)

www.studymaterialz.in 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
9. Which of the following Boolean
1. What will be the output of the following
expressions is not logically equivalent to the
Python code?
other three?
a) not(-6<0 or-6>10) x = ['ab', 'cd']
b) -6>=0 and -6<=10 for i in x:
c) not(-6<10 or-6==10) i.upper()
d) not(-6>10 or-6==10) print(x)

Answer: d a) [‘ab’, ‘cd’]


Explanation: The expression not(-6<0 or b) [‘AB’, ‘CD’]
-6>10) returns the output False. c) [None, None]
The expression -6>=0 and -6<=10 returns the d) none of the mentioned
output False.
The expression not(-6<10 or -6==10) returns Answer: a
the output False. Explanation: The function upper() does not
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
Python code snippet? Python code?

x = ['ab', 'cd']
not(10<20) and not(10>30)
for i in x:
x.append(i.upper())
a) True print(x)
b) False
c) Error a) [‘AB’, ‘CD’]
d) No output b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
Answer: b d) none of the mentioned
Explanation: The expression not(10<20)
returns false. The expression not(10>30) Answer: d
returns true. The and operation between false Explanation: The loop does not terminate as
and true returns false. Hence the output is new elements are being added to the list in
false. each iteration.

Sanfoundry Global Education & Learning 3. What will be the output of the following
Series – Python. Python code?

www.studymaterialz.in 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 break
c) error print(i)
d) none of the mentioned i += 1

Answer: c a) 5 6 7 8
Explanation: SyntaxError, there shouldn’t be b) 5 6 7 8 9
a space between + and = in +=. c) 5 6 7 8 9 10 11 12 13 14 15 ….
d) error
4. What will be the output of the following
Python code? Answer: d
Explanation: 9 isn’t allowed in an octal
i = 1 number.
while True:
if i%0O7 == 0:
break 7. What will be the output of the following
print(i) Python code?
i += 1
i = 1
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

Answer: a a) 1
Explanation: Control exits the loop when i 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
Python code? Answer: d
Explanation: The loop does not terminate
i = 5 since i is never an even number.
while True:
if i%0O11 == 0:
break 8. What will be the output of the following
print(i) Python code?
i += 1
i = 2
a) 5 6 7 8 9 10 while True:
if i%3 == 0:
b) 5 6 7 8 break
c) 5 6 print(i)
d) error i += 2

www.studymaterialz.in 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
loop. b) 0 1 2
c) error
9. What will be the output of the following d) none of the mentioned
Python code?
Answer: b
i = 1 Explanation: The else part is not executed if
while False: control breaks out of the loop.
if i%2 == 0:
break 2. What will be the output of the following
print(i)
i += 2
Python code?

i = 0
a) 1 while i < 3:
b) 1 3 5 7 … print(i)
c) 1 2 3 4 … i += 1
d) none of the mentioned else:
print(0)
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
10. What will be the output of the following d) error
Python code?
Answer: b
True = False Explanation: The else part is executed when
while True: the condition in the while statement is false.
print(True)
break 3. What will be the output of the following
Python code?
a) True
b) False x = "abcdef"
c) None while i in x:
d) none of the mentioned print(i, end=" ")

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

www.studymaterialz.in 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"
b) i i i i i i … while i in x:
c) a b c d e f x = x[:-1]
d) abcdef print(i, end = " ")

Answer: a a) i i i i i i
Explanation: “i” is not in “abcdef”. b) a a a a a a
c) a a a a a
5. What will be the output of the following d) none of the mentioned
Python code?
Answer: b
x = "abcdef" Explanation: The string x is being shortened
i = "a" by one character in each iteration.
while i in x:
print(i, end = " ")
8. What will be the output of the following
a) no output Python code?
b) i i i i i i … x = "abcdef"
c) a a a a a a … i = "a"
d) a b c d e f while i in x[:-1]:
print(i, end = " ")
Answer: c
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 …
d) a
6. What will be the output of the following
Python code? Answer: c
Explanation: String x is not being altered and
x = "abcdef" i is in x[:-1].
i = "a"
while i in x: 9. What will be the output of the following
print('i', end = " ")
Python code?
a) no output x = "abcdef"
b) i i i i i i … i = "a"
c) a a a a a a … while i in x:
d) a b c d e f x = x[1:]
print(i, end = " ")
Answer: b
Explanation: Here i i i i i … printed a) a a a a a a
continuously because as the value of i or x b) a
isn’t changing, the condition will always

www.studymaterialz.in 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?

x = "abcdef" x = 'abcd'
i = "a" for i in range(x):
while i in x[1:]: print(i)
print(i, end = " ")
a) a b c d
a) a a a a a a b) 0 1 2 3
b) a c) error
c) no output d) none of the mentioned
d) error
Answer: c
Answer: c Explanation: range(str) is not allowed.
Explanation: i is not in x[1:].
4. What will be the output of the following
1. What will be the output of the following Python code?
Python code?
x = 'abcd'
x = 'abcd' for i in range(len(x)):
for i in x: print(i)
print(i)
x.upper() a) a b c d
b) 0 1 2 3
a) a B C D c) error
b) a b c d d) 1 2 3 4
c) A B C D
d) error Answer: b
Explanation: i takes values 0, 1, 2 and 3.
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?
returned.
x = 'abcd'
2. What will be the output of the following for i in range(len(x)):
Python code? print(i.upper())

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

www.studymaterialz.in 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'
i.upper() for i in range(len(x)):
print (x) x = 'a'
print(x)
a) a b c d
b) 0 1 2 3 a) a
c) error b) abcd abcd abcd
d) none of the mentioned c) a a a a
d) none of the mentioned
Answer: c
Explanation: Objects of type int have no Answer: c
attribute upper(). Explanation: range() is computed only at the
time of entering the loop.
7. What will be the output of the following
Python code snippet? 10. What will be the output of the following
Python code snippet?
x = 'abcd'
for i in range(len(x)): x = 'abcd'
x[i].upper() for i in range(len(x)):
print (x) print(x)
x = 'a'
a) abcd
b) ABCD a) a
c) error b) abcd abcd abcd abcd
d) none of the mentioned c) a a a a
d) none of the mentioned
Answer: a
Explanation: Changes do not happen in- Answer: d
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.
8. What will be the output of the following
Python code snippet? 1. What will be the output of the following
Python code?
x = 'abcd'
for i in range(len(x)): x = 123
i[x].upper() for i in x:
print (x) print(i)

a) abcd a) 1 2 3
b) ABCD b) 123
c) error c) error
d) none of the mentioned d) none of the mentioned

www.studymaterialz.in 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
print(i) c) 0 a 1 b 2 c
d) none of the mentioned
a) 0 1 2
b) a b c Answer: b
c) 0 a 1 b 2 c Explanation: Loops over the keys and prints
d) none of the mentioned the values.

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


Explanation: Loops over the keys of the Python code?
dictionary.
d = {0: 'a', 1: 'b', 2: 'c'}
3. What will be the output of the following for x in d.values():
print(x)
Python code?

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


a) 0 1 2
for x, y in d: b) a b c
print(x, y) c) 0 a 1 b 2 c
d) none of the mentioned
a) 0 1 2
b) a b c Answer: b
c) 0 a 1 b 2 c Explanation: Loops over the values.
d) none of the mentioned
7. What will be the output of the following
Answer: d Python code?
Explanation: Error, objects of type int aren’t
iterable. d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(d[x])
4. What will be the output of the following
Python code? a) 0 1 2
d = {0: 'a', 1: 'b', 2: 'c'}
b) a b c
for x, y in d.items(): c) 0 a 1 b 2 c
print(x, y) d) none of the mentioned

a) 0 1 2 Answer: d
b) a b c Explanation: Causes a KeyError.
c) 0 a 1 b 2 c
d) none of the mentioned 8. What will be the output of the following
Python code?
Answer: c
Explanation: Loops over key, value pairs. d = {0, 1, 2}
for x in d.values():

www.studymaterialz.in 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
attribute values. Python code?
9. What will be the output of the following for i in range(2.0):
Python code? print(i)

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


for x in d: b) 0 1
print(x) c) error
d) none of the mentioned
a) 0 1 2
b) {0, 1, 2} {0, 1, 2} {0, 1, 2} Answer: c
c) error Explanation: Object of type float cannot be
d) none of the mentioned interpreted as an integer.
Answer: a 2. What will be the output of the following
Explanation: Loops over the elements of the Python code?
set and prints them.
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
d = {0, 1, 2} b) 0 1
for x in d: c) error
print(d.add(x))
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
c) None None None
range(2).
d) None of the mentioned
3. What will be the output of the following
Answer: c
Python code?
Explanation: Variable x takes the values 0, 1
and 2. set.add() returns None which is for i in range(float('inf')):
printed. print (i)

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

www.studymaterialz.in 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
Explanation: [::-1] reverses the string.
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 … 8. What will be the output of the following
c) 0.0 1.0 2.0 3.0 … Python code snippet?
d) none of the mentioned
for i in '':
Answer: d print (i)
Explanation: OverflowError, cannot convert
a) None
float infinity to integer.
b) (nothing is printed)
5. What will be the output of the following c) error
Python code snippet? d) none of the mentioned

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


print (i) Explanation: The string does not have any
character to loop over.
a) 1 2 3 4
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
Answer: b for i in range(x):
x += 1
Explanation: [::-1] reverses the list. print (x)

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


Python code snippet? b) 0 1
for i in ''.join(reversed(list('abcd'))):
c) 3 4
print (i) d) 0 1 2 3

a) a b c d Answer: c
b) d c b a Explanation: Variable x is incremented and
c) error printed twice.
d) none of the mentioned
10. What will be the output of the following
Answer: b Python code snippet?
Explanation: ‘ ‘.join(reversed(list(‘abcd’)))
x = 2
reverses a string. for i in range(x):
x -= 2
7. What will be the output of the following print (x)
Python code snippet?

www.studymaterialz.in 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
Answer: a
Python code?
Explanation: The first statement creates a
for i in range(10): generator object.
if i == 5:
break 4. What will be the output of the following
else: Python code?
print(i)
else: x = (i for i in range(3))
print("Here") for i in x:
print(i)
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 a) 0 1 2
b) error
Answer: c c) 0 1 2 0 1 2
Explanation: The else part is executed if d) none of the mentioned
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.

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


if i == 5: Python code?
break
else: string = "my name is x"
print(i) for i in string:
else: print (i, end=", ")
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
b) 0 1 2 3 4 5 Here c) my, name, is, x,
c) 0 1 2 3 4 d) error
d) 1 2 3 4 5
Answer: a
Answer: a Explanation: Variable i takes the value of
Explanation: The else part is executed if one character at a time.
control doesn’t break out of the loop.
6. What will be the output of the following
3. What will be the output of the following Python code?
Python code?

www.studymaterialz.in 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
Answer: c d) none of the mentioned
Explanation: Variable i takes the value of
one word at a time. Answer: c
Explanation: SyntaxError, not in isn’t
7. What will be the output of the following allowed in for loops.
Python code snippet?
10. What will be the output of the following
a = [0, 1, 2, 3] Python code snippet?
for a[-1] in a:
print(a[-1]) string = "my name is x"
for i in ' '.join(string.split()):
a) 0 1 2 3 print (i, end=", ")
b) 0 1 2 2
c) 3 3 3 3 a) m, y, , n, a, m, e, , i, s, , x,
d) error b) m, y, , n, a, m, e, , i, s, , x
c) my, name, is, x,
Answer: b d) error
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.
Python code snippet?

a = [0, 1, 2, 3]
TOPIC 3.2 PYTHON STRINGS
for a[0] in a:
print(a[0]) 1. What will be the output of the following
Python statement?
a) 0 1 2 3
b) 0 1 2 2 1. >>>"a"+"bc"
c) 3 3 3 3
d) error a) a
b) bc
Answer: a c) bca
Explanation: The value of a[0] changes in d) abc
each iteration. Since the first value that it
takes is itself, there is no visible error in the Answer: d
current example. Explanation: + operator is concatenation
operator.
9. What will be the output of the following
Python code snippet? 2. What will be the output of the following
Python statement?

www.studymaterialz.in 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
string. a) a new line and hello
b) \nhello
3. The output of executing string.ascii_letters c) the letter r and then hello
can also be achieved by: d) error
a) string.ascii_lowercase_string.digits
b) Answer: b
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
converted.
Answer: b
Explanation: Execute in shell and check. 7. What will be the output of the following
Python statement?
4. What will be the output of the following
Python code? 1. >>>print('new' 'line')

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


b) Output equivalent to print ‘new\nline’
2. >>> str2 = ',' c) newline
d) new line
3. >>> str3 = 'world'
4. >>> str1[-1:] Answer: c
Explanation: String literal separated by
a) olleh whitespace are allowed. They are
b) hello concatenated.
c) h
d) o 8. What will be the output of the following
Python statement?
Answer: d
Explanation: -1 corresponds to the last index. 1. >>> print('x\97\x98')

5. What arithmetic operators cannot be used a) Error


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

www.studymaterialz.in 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
c) 22 None
2. >>>str1[::-1]
d) Error is generated
a) dlrowolleh
Answer: d
b) hello
c) world Explanation: self.o1 was never created.
d) helloworld
2. What will be the output of the following
Python code?
Answer: a
Explanation: Execute in shell to verify.
1. class tester:
10. What will be the output of the following 2. def __init__(self, id):
Python code?
3. self.id = str(id)
print(0xA + 0xB + 0xC)
4. id="224"
a) 0xA0xB0xC
b) Error 5.
c) 0x22
6. >>>temp = tester(12)
d) 33
7. >>>print(temp.id)
Answer: d
Explanation: 0xA and 0xB and 0xC are a) 224
hexadecimal integer literals representing the b) Error
decimal values 10, 11 and 12 respectively. c) 12
There sum is 33. d) None
1. What will be the output of the following Answer: c
Python code? Explanation: Id in this case will be the
attribute of the class.
1. class father:
3. What will be the output of the following
2. def __init__(self, param):
Python code?
3. self.o1 = param
1. >>>example = "snow world"
4.
2. >>>print("%s" % example[4:7])
5. class child(father):
a) wo
6. def __init__(self, param): b) world

www.studymaterialz.in 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

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


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

www.studymaterialz.in 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
a) A d) str
b) B
c) a Answer: d
d) Error Explanation: Format function returns a
string.
Answer: a
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
Python statement? b) hello
c) Error
1. >>>print(chr(ord('b')+1)) d) hello6
a) a Answer: c
b) b Explanation: Cannot concatenate str and int
c) c objects.
d) A
7. What will be the output of the following
Answer: c Python code?
Explanation: Execute in the shell to verify.
1. >>>print("D", end = ' ')
3. Which of the following statement prints
hello\example\test.txt? 2. >>>print("C", end = ' ')
a) print(“hello\example\test.txt”)
b) print(“hello\example\test.txt”) 3. >>>print("B", end = ' ')
c) print(“hello\”example\”test.txt”)
4. >>>print("A", end = ' ')
d) print(“hello”\example”\test.txt”)
a) DCBA
Answer: b
b) A, B, C, D
Explanation: \is used to indicate that the next
c) D C B A
\ is not an escape sequence.
d) D, C, B, A will be displayed on four lines
4. Suppose s is “\t\tWorld\n”, what is
Answer: c
s.strip()?
Explanation: Execute in the shell.
a) \t\tWorld\n
b) \t\tWorld\n 8. What will be the output of the following
c) \t\tWORLD\n Python statement?(python 3.xx)
d) World
1. >>>print(format("Welcome", "10s"),
end = '#')

www.studymaterialz.in 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
command do we execute?
Answer: d
a) s.__len__()
Explanation: Execute in the shell to verify.
b) len(s)
9. What will be displayed by print(ord(‘b’) – c) size(s)
ord(‘a’))? d) s.size()
a) 0
Answer: a
b) 1
Explanation: Execute in shell to verify.
c) -1
d) 2 4. If a class defines the __str__(self) method,
for an object obj for the class, you can use
Answer: b
which command to invoke the __str__
Explanation: ASCII value of b is one more method.
than a. Hence the output of this code is 98-97,
a) obj.__str__()
which is equal to 1.
b) str(obj)
c) print obj
10. Say s=”hello” what will be the return
d) all of the mentioned
value of type(s)?
a) int
Answer: d
b) bool
Explanation: Execute in shell to verify.
c) str
d) String 5. To check whether string s1 contains
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)
d) si.in(s2)
1. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
Answer: a
b) Heelo
Explanation: s2 in s1 works in the same way
c) Heleo
as calling the special function __contains__ .
d) None
6. Suppose i is 5 and j is 4, i + j is same as
Answer: a ________
Explanation: Execute in shell to verify. a) i.__add(j)
b) i.__add__(j)
2. To retrieve the character at index 3 from
string s=”Hello” what command do we c) i.__Add(j)
execute (multiple answers allowed)? d) i.__ADD(j)
a) s[]

www.studymaterialz.in 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
)
3. self.__count = count
a) Peter Pan
4.
b) John Pan
5. c1 = Count(2) c) Peter Smith
d) John Smith
6. c2 = Count(2)
Answer: b
7. print(id(c1) == id(c2), end = " ") Explanation: Execute in the shell to verify.
8. 9. What function do you use to read a string?
9. s1 = "Good" a) input(“Enter a string”)
b) eval(input(“Enter a string”))
10. s2 = "Good" c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))
11. print(id(s1) == id(s2))
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,
d) False False “10.3f”) (_ indicates space).
a) __345.355
Answer: c b) ___345.355
Explanation: Execute in the shell objects c) ____345.355
cannot have same id, however in the case of d) _____345.354
strings its different.
Answer: b
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?
1. What will be the output of the following
1. class Name: Python code?
2. def __init__(self, firstName, m print("abc DEF".capitalize())
i, lastName):

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.

www.studymaterialz.in 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*

a) abc. def Answer: b


b) ABC. DEF Explanation: Padding is done towards the
c) Abc. def left-hand-side first when the final string is of
d) Abc. Def odd length. Extra spaces are present since we
haven’t overridden the value of sep.
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?
converted to lowercase.
print('*', "abcdef".center(7), '*', sep=
3. What will be the output of the following '')
Python code?
a) * abcdef *
print("abcdef".center()) b) * abcdef *
c) *abcdef *
a) cd d) * abcdef*
b) abcdef
c) error Answer: d
d) none of the mentioned Explanation: Padding is done towards the
left-hand-side first when the final string is of
Answer: c odd length.
Explanation: The function center() takes at
least one parameter. 7. What will be the output of the following
Python code?
4. What will be the output of the following
Python code? print('*', "abcde".center(6), '*', sep=''
)
print("abcdef".center(0))
a) * abcde *
a) cd b) * abcde *
b) abcdef c) *abcde *
c) error d) * abcde*
d) none of the mentioned
Answer: c
Answer: b Explanation: Padding is done towards the
Explanation: The entire string is printed right-hand-side first when the final string is of
when the argument passed to center() is less even length.
than the length of the string.
8. What will be the output of the following
Python code?

www.studymaterialz.in 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
must be a character, not an int. a) 2
b) 0
9. What will be the output of the following c) 1
Python code? d) none of the mentioned

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

www.studymaterialz.in 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
Python code?
Answer: b
Explanation: Counts the number of times the print("xyyzxyzxzxyy".endswith("xyy"))
substring ‘xyy’ is present in the given string,
starting from position 2 and ending at a) 1
position 11. b) True
c) 3
6. What will be the output of the following d) 2
Python code?
Answer: b
print("xyyzxyzxzxyy".count('xyy', -10, -1 Explanation: The function returns True if the
)) given string ends with the specified substring.
a) 2 10. What will be the output of the following
b) 0 Python code?
c) 1
d) error print("xyyzxyzxzxyy".endswith("xyy", 0, 2
))
Answer: b
Explanation: Counts the number of times the a) 0
substring ‘xyy’ is present in the given string, b) 1
starting from position 2 and ending at c) True
position 11. d) False

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


Python code? Explanation: The function returns False if
the given string does not end with the
print('abc'.encode()) specified substring.
a) abc 1. What will be the output of the following
b) ‘abc’ Python code?
c) b’abc’
d) h’abc’ print("ab\tcd\tef".expandtabs())

Answer: c a) ab  cd  ef
Explanation: A bytes object is returned by b) abcdef
encode. c) ab\tcd\tef
d) ab cd ef
8. What is the default value of encoding in
encode()? Answer: a
a) ascii Explanation: Each \t is converted to 8 blank

www.studymaterialz.in 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
c) ab\tcd\tef string at which the substring can be found is
d) ab cd ef returned.

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


Explanation: Each \t is converted to 4 blank Python code?
spaces.
print("ccdcddcd".find("c"))
3. What will be the output of the following
Python code? a) 4
b) 0
print("ab\tcd\tef".expandtabs('+')) c) Error
d) True
a) ab+cd+ef
b) ab++++++++cd++++++++ef Answer: b
c) ab cd ef Explanation: The first position in the given
d) none of the mentioned string at which the substring can be found is
returned.
Answer: d
Explanation: TypeError, an integer should be 7. What will be the output of the following
passed as an argument. Python code?

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

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


def") b) Hello {0} and {1} foo bin
c) Error
a) True d) Hello 0 and 1
b) False
c) Error Answer: a
d) None of the mentioned Explanation: The numbers 0 and 1 represent
the position at which the strings are present.
Answer: b
Explanation: The function find() returns the 8. What will be the output of the following
position of the sunstring in the given string Python code?
whereas the in keyword returns a value of
Boolean type. print("Hello {1} and {0}".format('bin',
'foo'))
5. What will be the output of the following
Python code? a) Hello foo and bin
b) Hello bin and foo

www.studymaterialz.in 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
b) Hello ‘foo’ and foo
print("Hello {} and {}".format('foo', 'bi c) Hello foo and ‘bin’
n')) d) Error

a) Hello foo and bin Answer: b


b) Hello {} and {} Explanation: !r causes the characters ‘ or ” to
c) Error be printed as well.
d) Hello and
3. What will be the output of the following
Answer: a Python code?
Explanation: It is the same as Hello {0} and
{1}. print("Hello {0} and {1}".format(('foo',
'bin')))
10. What will be the output of the following
a) Hello foo and bin
Python code?
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
print("Hello {name1} and {name2}".format( c) Error
'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
c) Error out of range.
d) Hello and
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((
'foo', 'bin')))
1. What will be the output of the following
Python code? a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
print("Hello {name1} and {name2}".format( c) Error
name1='foo', name2='bin')) d) None of the mentioned

a) Hello foo and bin Answer: a


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

www.studymaterialz.in 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
Explanation: The arguments passed to the b) 111,222,333,4
function format can be integers also. c) 1112223334
d) Error
6. What will be the output of the following
Python code snippet? Answer: d
Explanation: $ is an invalid format code.
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
b) The sum of 10 and a is 14 print('{:#}'.format(1112223334))
c) The sum of 10 and a is c
d) Error a) 1,112,223,334
b) 111,222,333,4
Answer: b c) 1112223334
Explanation: 2 is converted to binary, 10 to d) Error
hexadecimal and 12 to octal.
Answer: c
7. What will be the output of the following Explanation: The number is printed as it is.
Python code snippet?
1. What will be the output of the following
print('{:,}'.format(1112223334)) Python code?
a) 1,112,223,334 print('{0:.2}'.format(1/3))
b) 111,222,333,4
c) 1112223334 a) 0.333333
d) Error b) 0.33
c) 0.333333:.2
Answer: a d) Error
Explanation: A comma is added after every
third digit from the right. Answer: b
Explanation: .2 specifies the precision.
8. What will be the output of the following
Python code snippet? 2. What will be the output of the following
Python code?
print('{:,}'.format('1112223334'))
print('{0:.2%}'.format(1/3))
a) 1,112,223,334
b) 111,222,333,4 a) 0.33
c) 1112223334 b) 0.33%
d) Error

www.studymaterialz.in 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
Python code?
Answer: b
print('ab12'.isalnum()) Explanation: Space is not a letter.

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


b) False Python code snippet?
c) None
d) Error print('0xa'.isdigit())

Answer: a a) True
Explanation: The string has only letters and b) False
digits. c) None
d) Error
4. What will be the output of the following
Python code? Answer: b
Explanation: Hexadecimal digits aren’t
print('ab,12'.isalnum()) considered as digits (a-f).

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


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

Answer: b a) True
Explanation: The character , is not a letter or b) False
a digit. c) None
d) Error
5. What will be the output of the following
Python code? Answer: b
Explanation: If there are no characters then
print('ab'.isalpha()) False is returned.

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


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

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

www.studymaterialz.in 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
b) False print('11'.isnumeric())
c) None
d) Error a) True
b) False
Answer: a c) None
Explanation: It is a valid identifier. d) Error

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


Python code snippet? Explanation: All the character are numeric.

print('for'.isidentifier()) 5. What will be the output of the following


Python code snippet?
a) True
b) False print('1.1'.isnumeric())
c) None
d) Error a) True
b) False
Answer: a c) None
Explanation: Even keywords are considered d) Error
as valid identifiers.
Answer: b
2. What will be the output of the following Explanation: The character . is not a numeric
Python code snippet? character.

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


Python code snippet?
a) True
b) False print('125erdE a'.isprintable())
c) None
d) Error a) True
b) False
Answer: a c) None
Explanation: There are no uppercase letters. d) Error

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


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

www.studymaterialz.in 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

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


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

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


Python code?
a) True
b) False print('GYMK'.lower())
c) None
d) Error a) n
b) gymk
Answer: a c) rn
Explanation: Tab Spaces are considered as d) r
spaces.
Answer: b
9. What will be the output of the following Explanation: Uppercase letters are converted
Python code snippet? to lowercase. The other characters are left
unchanged.
print('HelloWorld'.istitle())
3. What will be the output of the following
a) True Python code?
b) False
c) None print('''
d) Error \tfoo'''.lstrip())

Answer: b a) \tfoo
Explanation: The letter W is uppercased. b) foo
c)   foo
10. What will be the output of the following d) none of the mentioned
Python code snippet?
Answer: b
print('Hello World'.istitle()) Explanation: All leading whitespace is
removed.
a) True
b) False 4. What will be the output of the following
c) None Python code?
d) Error
print('xyyzxxyxyy'.lstrip('xyy'))
Answer: a
Explanation: It is in title form. a) error
b) zxxyxyy

www.studymaterialz.in 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’)
b) (‘abef’)
print('xyxxyyzxxy'.lstrip('xyy')) c) (‘ab’, ‘cd’, ‘ef’)
d) 2
a) zxxy
b) xyxxyyzxxy Answer: c
c) xyxzxxy Explanation: The string is split into three
d) none of the mentioned parts by partition.

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


Explanation: All combinations of the Python code?
characters passed as an argument are removed
from the left hand side. print('abcdefcdgh'.partition('cd'))

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

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


b) {65: 49, 66: 50, 67: 51} Explanation: The string is partitioned at the
c) 321 point where the separator first appears.
d) 123
10. What will be the output of the following
Answer: a Python code?
Explanation: A translation table is returned
by maketrans. print('abcd'.partition('cd'))

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


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

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


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

www.studymaterialz.in 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'))

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


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

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

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


Explanation: The separator is not present in Python code snippet?
the string hence the second and the third
elements of the tuple are null strings. print('xyyxyyxyxyxxy'.replace('xy', '12',
0))
3. What will be the output of the following
a) xyyxyyxyxyxxy
Python code snippet?
b) 12y12y1212x12
print('abcdef12'.replace('cd', '12')) c) 12yxyyxyxyxxy
d) xyyxyyxyxyx12
a) ab12ef12
b) abcdef12 Answer: a
c) ab12efcd Explanation: The first 0 occurrences of the
d) none of the mentioned given substring are replaced.

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
print('xyyxyyxyxyxxy'.replace('xy', '12',
substring. 100))

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


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

www.studymaterialz.in 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’, ”)
2. What will be the output of the following
Answer: b Python code snippet?
Explanation: The given string is split and a
list of substrings is returned. print('ab\ncd\nef'.splitlines())

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


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’]
a) [‘abcdefcdghcd’] Answer: a
b) ‘abcdefcdghcd’ Explanation: It is similar to calling
c) error split(‘\n’).
d) none of the mentioned
3. What will be the output of the following
Answer: a Python code snippet?
Explanation: The given string is split at 0
occurances of the specified substring. print('Ab!2'.swapcase())

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


Python code snippet? b) ab12
c) aB!2
print('abcdefcdghcd'.split('cd', -1)) d)
a) [‘ab’, ‘ef’, ‘gh’] Answer: c
b) [‘ab’, ‘ef’, ‘gh’, ”] Explanation: Lowercase letters are converted
c) (‘ab’, ‘ef’, ‘gh’) to uppercase and vice-versa.
d) (‘ab’, ‘ef’, ‘gh’, ”)
4. What will be the output of the following
Answer: b Python code snippet?
Explanation: Calling the function with a
negative value for maxsplit is the same as print('ab cd ef'.title())
calling it without any maxsplit specified. The
string will be split into as many substring s as a) Ab cd ef
possible. b) Ab cd eF
c) Ab Cd Ef
1. What will be the output of the following d) None of the mentioned
Python code snippet?
Answer: c
print('abcdefcdghcd'.split('cd', 2)) Explanation: The first letter of every word is

www.studymaterialz.in 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
c) Ab Cd-Ef Explanation: The function translate expects a
d) None of the mentioned dictionary of integers. Use maketrans()
instead of doing the above.
Answer: c
Explanation: The first letter of every word is 9. What will be the output of the following
capitalized. Special symbols terminate a Python code snippet?
word.
print('ab'.zfill(5))
6. What will be the output of the following
Python code snippet? a) 000ab
b) 00ab0
print('abcd'.translate('a'.maketrans('ab c) 0ab00
c', 'bcd'))) d) ab000

a) bcde Answer: a
b) abcd Explanation: The string is padded with zeros
c) error on the left hand side. It is useful for
d) bcdd formatting numbers.

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


Explanation: The output is bcdd since no Python code snippet?
translation is provided for d.
print('+99'.zfill(5))
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
9: 100})) d) +++99
a) bcde Answer: c
b) abcd Explanation: zeros are filled in between the
c) error first sign and the rest of the string.
d) none of the mentioned

Answer: d TOPIC 3.3 FUNCTIONS


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

www.studymaterialz.in 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
which is present in the random module. The any one of the elements of the iterable is zero
functions sqrt and factorial are a part of the and true if all the elements of the iterable are
math module. The print function is a built-in non zero. Hence the output of this function
function which prints a value directly to the will be false.
system output.
5. What will be the output of the following
2. What will be the output of the following Python expression?
Python expression?
round(4.5676,2)?
round(4.576)
a) 4.5
a) 4.5 b) 4.6
b) 5 c) 4.57
c) 4 d) 4.56
d) 4.6
Answer: c
Answer: b Explanation: The function round is used to
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
number of decimal places has not been places. Hence the output will be 4.57.
specified, the decimal number is rounded off
to a whole number. Hence the output will be 6. What will be the output of the following
5. Python function?

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


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

www.studymaterialz.in 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
Explanation: The abs() function prints the used to find the maximum value from among
absolute value of the argument passed. For -3, -4 and false. Since false amounts to the
example: abs(-5)=5. Hence, in this case we value zero, hence we are left with min(0, 2, 7)
get abs(5.0)=5.0. Hence the output is 0 (false).
8. What will be the output of the following 1. What will be the output of the following
Python function? Python functions?
sum(2,4,6) chr(‘97’)
sum([1,2,3]) chr(97)

a) Error, 6 a)
b) 12, Error
c) 12, 6 a
d) Error, Error
Error
Answer: a
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
outcomes will be Error and 6 respectively. a

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


Python function?
Error
all(3,0,4.2)
a
a) True
b) False d)
c) Error Error
d) 0
Error
Answer: c
Explanation: The function all() returns Answer: c
‘True’ if any one or more of the elements of Explanation: The built-in function chr()
the iterable are non zero. In the above case, returns the alphabet corresponding to the
the values are not iterable, hence an error is value given as an argument. This function
thrown. accepts only integer type values. In the first
function, we have passed a string. Hence the
10. What will be the output of the following first function throws an error.
Python function?

www.studymaterialz.in 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
b) 1 (2, 0)
c) 2j
d) 1+2j c)

Answer: d (2.0, 0.5)


Explanation: The built-in function complex()
(2.0, 0.0)
returns the argument in a complex form.
Hence the output of the function shown above
d)
will be 1+2j.
(2, 0.5)
3. What is the output of the function
complex()? (2)
a) 0j
b) 0+0j Answer: c
c) 0 Explanation: See python documentation for
d) Error the function divmod.

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
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
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,
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
error.
Answer: b
Explanation: The function divmod(a,b) is 7. What will be the output of the following
evaluated as a//b, a%b, if both ‘a’ and ‘b’ are Python function?
integers. list(enumerate([2, 3]))
5. What will be the output of the following a) Error
Python function? b) [(1, 2), (2, 3)]
divmod(10.5,5)
c) [(0, 2), (1, 3)]
divmod(2.4,1.2) d) [(2, 3)]

www.studymaterialz.in 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 and the second function adds 3 zeros after the
Python functions? given number.
x=3
eval('x^2')

a) Error 10. Which of the following functions does not


b) 1 necessarily accept only iterables as
c) 9 arguments?
d) 6 a) enumerate()
b) all()
Answer: b c) chr()
Explanation: The function eval is use to d) max()
evaluate the expression that it takes as an
argument. In the above case, the eval() Answer: c
function is used to perform XOR operation Explanation: The functions enumerate(), all()
between 3 and 2. Hence the output is 1. and max() accept iterables as arguments
whereas the function chr() throws an error on
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.
float('1e-003')
float('2e+003') 1. Which of the following functions accepts
only integers as arguments?
a) a) ord()
3.00
b) min()
c) chr()
300 d) any()

b) Answer: c
Explanation: The function chr() accepts only
0.001 integers as arguments. The function ord()
accepts only strings. The functions min() and
2000.0
max() can accept floating point as well as
c) integer arguments.

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


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

www.studymaterialz.in 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
list, we use: list(reversed(l)). The output will Error
be: [4,3,2].
Answer: b
3. What will be the output of the following Explanation: The built-in function ord() is
Python function? used to return the ASCII value of the alphabet
passed to it as an argument. Hence the first
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
the number is 5)
a)   -12345.0 (5 blank spaces before the
number) 5. What will be the output of the following
b) -12345.0 Python function?
c) Error
d) -12345.000000000…. (infinite decimal float(‘-infinity’)
float(‘inf’)
places)
a)
Answer: b
Explanation: The function float() will –inf
remove all the blank spaces and convert the
integer to a floating point number. Hence the inf
output will be: -12345.0.
b)
4. What will be the output of the following
–infinity
Python function?
inf
ord(65)
ord(‘A’)
c)
a)
Error
A Error
65
d)
b)
Error
Error Junk value
65 Answer: a
Explanation: The output of the first function

www.studymaterialz.in 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()
b) divmod() len(["hello",2, 4, 6])
c) all()
d) float() a) 4
b) 3
Answer: d c) Error
Explanation: The built-in functions min(), d) 6
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
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. shown above is 4.

7. What will be the output of the following 10. What will be the output of the following
Python function? Python function?

oct(7)
hex(15)
oct(‘7’)
a) f a)
b) 0xF
c) 0Xf Error
d) 0xf
07
Answer: d
Explanation: The function hex() is used to b)
convert the given argument into its
0o7
hexadecimal representation, in lower case.
Hence the output of the function hex(15) is Error
0xf.
c)
8. Which of the following functions does not
throw an error? 0o7
a) ord()
b) ord(‘ ‘) Error
c) ord(”)
d)
d) ord(“”)
07
Answer: b
Explanation: The function ord() accepts a 0o7
character. Hence ord(), ord(”) and ord(“”)

www.studymaterialz.in 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!'

c)
TOPIC 3.3.2 USER DEFINED
FUNCTIONS Hello

Hello
1. Which of the following is the use of
function in python? d) None of the mentioned
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity Answer: a
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 identifier name for the function, followed by
a pair of parentheses which may enclose
Answer: a some names of variables, and by the final
Explanation: Functions are reusable pieces colon that ends the line. Next follows the
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.
that block using the specified name anywhere
in your program and any number of times. 1. def sayHello():

2. Which keyword is used for function? 2. print('Hello World!') # block b


elonging to the function
a) Fun
b) Define 3. # End of function #
c) Def
d) Function 4.

Answer: c 5. sayHello() # call the function


Explanation: None.
6. sayHello() # call the function agai
n
3. What will be the output of the following
Python code? 4. What will be the output of the following
Python code?
1. def sayHello():
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)

www.studymaterialz.in 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
c) 4 is maximum Answer: a
d) None of the mentioned Explanation: The first time that we print the
value of the name x with the first line in the
Answer: c function’s body, Python uses the value of the
Explanation: Here, we define a function parameter declared in the main block, above
called printMax that uses two parameters the function definition.
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
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 With the last print function call, we display
Python code? the value of x as defined in the main block,
thereby confirming that it is actually
1. x = 50 unaffected by the local assignment within the
previously called function.
2. def func(x):
6. What will be the output of the following
3. print('x is', x)
Python code?
4. x = 2
1. x = 50
5. print('Changed local x to', x)
2. def func():
6. func(x)
3. global x
7. print('x is now', x)
4. print('x is', x)
a)
5. x = 2
x is 50
6. print('Changed global x to', x)
Changed local x to 2
7. func()
x is now 50
8. print('Value of x is', x)
b)
a)
x is 50
x is 50
Changed local x to 2
Changed global x to 2
x is now 2
Value of x is 50

www.studymaterialz.in 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
use default values in case the user does not
x is 50
want to provide values for them. This is done
Changed global x to 50 with the help of default argument values. You
can specify default argument values for
Value of x is 50 parameters by appending to the parameter
name in the function definition the
d) None of the mentioned assignment operator (=) followed by the
default value.
Answer: b The function named say is used to print a
Explanation: The global statement is used to 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 printed just once. We achieve this by
function, that change is reflected when we use specifying a default argument value of 1 to
the value of x in the main block. the parameter times.
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?
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)

3. say('Hello')
8. What will be the output of the following
4. say('World', 5) Python code?
a) 1. def func(a, b=5, c=10):
Hello 2. print('a is', a, 'and b is', b,
'and c is', c)
WorldWorldWorldWorldWorld
3.
b)
4. func(3, 7)
Hello
5. func(25, c = 24)
World 5
6. func(c = 50, a = 100)
c)
a)
Hello
a is 7 and b is 3 and c is 10
World,World,World,World,World

www.studymaterialz.in 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:
a is 50 and b is 100 and c is 5
3. return x
c)
4. elif x == y:
a is 3 and b is 7 and c is 10
5. return 'The numbers are equ
a is 25 and b is 5 and c is 24 al'

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

d) None of the mentioned 7. return y

8.
Answer: c
Explanation: If you have some functions 9. print(maximum(2, 3))
with many parameters and you want to
specify only some of them, then you can give a) 2
values for such parameters by naming them – b) 3
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
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
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
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
In the second usage func(25, c=24), the documentation with Python modules,
variable a gets the value of 25 due to the functions, classes, and methods
position of the argument. Then, the parameter b) All functions should have a docstring
c gets the value of 24 due to naming i.e. c) Docstrings can be accessed by the __doc__
keyword arguments. The variable b gets the attribute on objects
default value of 5. d) All of the mentioned

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


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

www.studymaterialz.in 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

www.studymaterialz.in 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):
32
2. return c * 9/5 + 32
b)
3. print C2F(100)
9
4. print C2F(0)
27
a)
c)
212
567
32
98
b)
d) None of the mentioned
314
Answer: b
24
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
function has one argument with an implicit
98 value. We can call the function with one or
two arguments.
d) None of the mentioned
10. What will be the output of the following
Answer: a Python code?
Explanation: The code shown above is used
to convert a temperature in degree celsius to 1. def sum(*args):
fahrenheit.
2. '''Function returns the sum
9. What will be the output of the following
Python code? 3. of all values'''

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

2. r = 1 5. for i in args:

3. for i in range(y): 6. r += i

4. r = r * x 7. return r

8. print sum.__doc__

www.studymaterialz.in 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
a) 48
b) b) 14
6
c) 64
d) None of the mentioned
100
Answer: a
c) Explanation: The lambda keyword creates an
anonymous function. The x is a parameter,
123 that is passed to the lambda function. The
parameter is followed by a colon character.
12345
The code next to the colon is the expression
d) None of the mentioned that is executed, when the lambda function is
called. The lambda function is assigned to the
Answer: a z variable.
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
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
to document the function. The string must be 3. What will be the output of the following
in triple quotes. Python code?

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


functions at runtime, using a construct called 2. print(lamb(5))
__________
a) lambda a) 15
b) pi b) 555
c) anonymous c) 125
d) none of the mentioned d) None of the mentioned
Answer: a Answer: c
Explanation: Python supports the creation of Explanation: None.
anonymous functions (i.e. functions that are
not bound to a name) at runtime, using a 4. Does Lambda contains return statements?
construct called lambda. Lambda functions a) True
are restricted to a single expression. They can b) False
be used wherever normal functions can be
used.

www.studymaterialz.in 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.
d) None of the mentioned
a) True
b) False Answer: b
Explanation: None.
Answer: b
Explanation: lambda is an anonymous 9. What will be the output of the following
function in Python. Hence this statement is Python code?
false.
1. L = [lambda x: x ** 2,
6. Lambda contains block of statements.
a) True 2. lambda x: x ** 3,
b) False
3. lambda x: x ** 4]
Answer: b
Explanation: None. 4.
5. for f in L:
7. What will be the output of the following
Python code? 6. print(f(3))

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


2. f(2, 30, 400) 27

a) 432 81
b) 24000
c) 430 343
d) No output
b)
Answer: a 6
Explanation: None.
9
8. What will be the output of the following
Python code? 12

1. def writer(): c)

2. title = 'Sir' 9

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


' + x)
81
4. return name

www.studymaterialz.in 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
y) d) An exception is thrown
2. min(101*99, 102*98)
Answer: c
a) 9997 Explanation: Any change made in to an
b) 9999 immutable data type in a function isn’t
c) 9996 reflected outside the function.
d) None of the mentioned
4. What will be the output of the following
Answer: c Python code?
Explanation: None.
def a(b):
b = b + [5]
1. What is a variable defined outside a
function referred to as? c = [1, 2, 3, 4]
a) A static variable a(c)
b) A global variable print(len(c))
c) A local variable
a) 4
d) An automatic variable
b) 5
Answer: b c) 1
Explanation: The value of a variable defined d) An exception is thrown
outside all function definitions is referred to
Answer: b
as a global variable and can be used by
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.
referred to as?
5. What will be the output of the following
a) A global variable
Python code?
b) A volatile variable
c) A local variable a=10
d) An automatic variable b=20
def change():
Answer: c global b
Explanation: The variable inside a function a=45
b=56
is called as local variable and the variable change()
definition is confined only to that function. print(a)
print(b)
3. What will be the output of the following
Python code? a)

www.studymaterialz.in 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.
c)
8. If a function doesn’t have a return
10 statement, which of the following does the
20 function return?
a) int
d) Syntax Error b) null
c) None
Answer: a d) An exception is thrown without the return
Explanation: The statement “global b” statement
allows the global value of b to be accessed
and changed. Whereas the variable a is local Answer: c
and hence the change isn’t reflected outside Explanation: A function can exist without a
the function. return statement and returns None if the
function doesn’t have a return statement.
6. What will be the output of the following
Python code? 9. What will be the output of the following
Python code?
def change(i = 1, j = 2):
i = i + j def display(b, n):
j = j + 1 while n > 0:
print(i, j) print(b,end="")
change(j = 1, i = 2) n=n-1
display('z',3)
a) An exception is thrown because of
conflicting values a) zzz
b) 1 2 b) zz
c) 3 3 c) An exception is executed
d) 3 2 d) Infinite loop

Answer: d Answer: a
Explanation: The values given during Explanation: The loop runs three times and
function call is taken into consideration, that ‘z’ is printed each time.
is, i=2 and j=1.
10. What will be the output of the following
7. What will be the output of the following Python code?
Python code?
def find(a, **b):
def change(one, *two): print(type(b))
print(type(two)) find('letters',A='1',B='2')
change(1,2,3,4)

www.studymaterialz.in 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
d) two underscores followed by a valid
TOPIC 3.3 ARGUMENTS AND identifier
PARAMETERS
Answer: c
1. What is the type of each element in Explanation: Refer documentation.
sys.argv?
a) set 5. How many keyword arguments can be
b) list passed to a function in a single function call?
c) tuple a) zero
d) string b) one
c) zero or more
Answer: d d) one or more
Explanation: It is a list of strings.
Answer: c
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
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?
Answer: b
def foo(fname, val):
Explanation: The first argument is the name
print(fname(val))
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.
a) 3 1
3. What will be the output of the following b) 1 3
Python code? c) error
d) none of the mentioned
def foo(k):
k[0] = 1 Answer: a
q = [0]
foo(q) Explanation: It is possible to pass function
print(q) names as arguments to other functions.

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


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

www.studymaterialz.in 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]
Explanation: It is possible to read the value d) [1] [1, 2] [1, 2, 3]
of a global variable directly.
Answer: b
8. What will be the output of the following Explanation: When a list is a default value,
Python code? the same list will be reused.

def foo(): 1. What will be the output of the following


total += 1 Python code?
return total
total = 0 def foo(k):
print(foo()) k = [1]
q = [0]
a) 0 foo(q)
b) 1 print(q)
c) error
a) [0]
d) none of the mentioned
b) [1]
Answer: c c) [1, 0]
Explanation: It is not possible to change the d) [0, 1]
value of a global variable without explicitly
Answer: a
specifying it.
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
and after k = [1].
def foo(x):
x = ['def', 'abc'] 2. How are variable length arguments
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
a) True identifier
c) two stars followed by a valid identifier
b) False
d) two underscores followed by a valid
c) None
identifier
d) Error
Answer: a
Answer: b
Explanation: 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?

www.studymaterialz.in 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?

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


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

Answer: b a) True
Explanation: It is a list of elements. b) False
c) None
5. What is the value stored in sys.argv[0]? d) Error
a) null
b) you cannot access it Answer: a
c) the program’s name Explanation: The same object is modified in
d) the first argument the function.

Answer: c 9. Where are the arguments received from the


Explanation: Refer documentation. command line stored?
a) sys.argv
6. How are default arguments specified in the b) os.argv
function heading? c) argv
a) identifier followed by an equal to sign and d) none of the mentioned
the default value
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
d) identifier Python code?

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


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

www.studymaterialz.in 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

def f1(): Answer: a


x=15 Explanation: The value passed to the
print(x)
x=12
function san() is 12. This value is
f1() incremented by one and printed. Hence the
output of the code shown above is 13.
a) Error
b) 12 4. What will be the output of the following
c) 15 Python code?
d) 1512
def f1():
global x
Answer: c x+=1
Explanation: In the code shown above, x=15 print(x)
is a local variable whereas x=12 is a global x=12
variable. Preference is given to local variable print("x")
over global variable. Hence the output of the
code shown above is 15. a) Error
b) 13
2. What will be the output of the following c)
Python code?
13
def f1():
x=100 x
print(x)
x=+1 d) x
f1()
Answer: d
a) Error Explanation: In the code shown above, the
b) 100 variable ‘x’ is declared as global within the
c) 101 function. Hence the output is ‘x’. Had the
d) 99 variable ‘x’ been a local variable, the output
would have been:
Answer: b 13
Explanation: The variable x is a local x
variable. It is first printed and then modified.
Hence the output of this code is 100. 5. What will be the output of the following
Python code?
3. What will be the output of the following
Python code? def f1(x):
global x

www.studymaterialz.in 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)
world
16

hello b)

Answer: a world
Explanation: The code shown above will
hello
result in an error because ‘x’ is a global
variable. Had it been a local variable, the hello
output would be: 16
hello c)

hello

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

x=12 d)
def f1(a,b=x):
print(a,b) world
x=15
f1(4) hello

a) Error world
b) 12 4
c) 4 12 Answer: b
d) 4 15 Explanation: Since the variable ‘a’ has been
explicitly specified as a global variable, the
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
modified later. The value passed to the hello
function f1 is 4. Hence the output of the code hello
shown above is 4 12.

7. What will be the output of the following


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

www.studymaterialz.in 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

www.studymaterialz.in 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
b) 90 def cg():
c) 80 global x
x=x+1
d) Error
cg()
x
Answer: a
Explanation: The output of the code shown a) 2
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
13. Read the following Python code carefully Answer: a
and point out the global variables? Explanation: Since ‘x’ has been declared a
global variable, it can be modified very easily
y, z = 1, 2
def f():
within the function. Hence the output is 2.
global x
x = y+z 3. On assigning a value to a variable inside a
function, it automatically becomes a global
a) x variable.
b) y and z a) True
c) x, y and z b) False
d) Neither x, nor y, nor z
Answer: b
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.
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
code. Hence, x, y and z are global variables. Python code?

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


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

error

www.studymaterialz.in 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
Explanation: The output of the code shown
above will be ‘bitter’, followed by an error. Answer: d
The error is because the operand ‘+’ is Explanation: In the code shown above, when
unsupported on the types used above. we call the function f, a new namespace is
created. The assignment x=4 is performed in
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.
want to access?
a) Error 8. ______________ returns a dictionary of
b) The local variable is shadowed the module namespace.
c) Undefined behavior ________________ returns a dictionary of
d) The global variable is shadowed the current namespace.
a)
Answer: d
Explanation: If a local variable exists with locals()
the same name as the local variable that you
globals()
want to access, then the global variable is
shadowed. That is, preference is given to the b)
local variable.
locals()
6. What will be the output of the following
Python code? locals()

a=10 c)
globals()['a']=25
print(a) globals()

a) 10 locals()
b) 25
c) Junk value d)
d) Error
globals()
Answer: b globals()
Explanation: In the code shown above, the
value of ‘a’ can be changed by using globals() Answer: c
function. The dictionary returned is accessed Explanation: The function globals() returns a
using key of the variable ‘a’ and modified to dictionary of the module namespace, whereas
25. the function locals() returns a dictionary of
the current namespace.
7. What will be the output of the following
Python code?

www.studymaterialz.in 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)
b) A function execution instance that calls b) (num-1)*(num-2)
another execution instance of the same c) num*(num-1)
function d) fact(num)*fact(num-1)
c) A class method that calls another class
method Answer: a
d) An in-built method that is automatically Explanation: Suppose n=5 then, 5*4*3*2*1
called is returned which is the factorial of 5.

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


Explanation: The appropriate definition for a Python code?
recursive function is a function execution
instance that calls another execution instance def test(i,j):
if(i==0):
of the same function either directly or
return j
indirectly. else:
return test(i-1,i+j)
2. Only problems that are recursively defined print(test(4,7))
can be solved using recursion.
a) True a) 13
b) False b) 7
c) Infinite loop
Answer: b d) 17
Explanation: There are many other problems
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.
non-recursive function
b) Recursive functions usually take more 6. What will be the output of the following
memory space than non-recursive function Python code?
c) Recursive functions run faster than non-
recursive function l=[]
def convert(b):
d) Recursion makes programs easier to if(b==0):
understand return l
dig=b%2
Answer: c l.append(dig)
Explanation: The speed of a program using convert(b//2)
convert(6)
recursion is slower than the speed of its non- l.reverse()
recursive equivalent. for i in l:
print(i,end="")

www.studymaterialz.in 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
7. What is tail recursion? Answer: d
a) A recursive function that has two base Explanation: A recursive function needn’t
cases have a return value.
b) A function where the recursive functions
leads to an infinite loop 10. What will be the output of the following
c) A recursive function where the function Python code?
doesn’t return anything and just prints the
values def fun(n):
if (n > 100):
d) A function where the recursive call is the
return n - 5
last thing executed by the function return fun(fun(n+11));

Answer: d print(fun(45))
Explanation: A recursive function is tail
recursive when recursive call is executed by a) 50
the function in the last. b) 100
c) 74
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
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
def b(n, tot): returned and printed.
if n == 0:
return tot 11. Recursion and iteration are the same
else: programming approach.
return b(n-2, tot-2)
a) True
a) Both a() and b() aren’t tail recursive b) False
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
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

www.studymaterialz.in 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

www.studymaterialz.in 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
a) 2445 Explanation: Slicing is allowed in lists just
b) 133 as in the case of strings.
c) 12454
d) 123 9. Suppose list1 is [2, 33, 222, 14, 25], What
is list1[-1]?
Answer: c a) Error
Explanation: Max returns the maximum b) None
element in the list. c) 25
d) 2
5. Suppose list1 is [3, 5, 25, 1, 3], what is
min(list1)? Answer: c
a) 3 Explanation: -1 corresponds to the last index
b) 5 in the list.
c) 25
d) 1 10. Suppose list1 is [2, 33, 222, 14, 25], What
is list1[:-1]?
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]
6. Suppose list1 is [1, 5, 9], what is
sum(list1)? Answer: a
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?

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


Explanation: Sum returns the sum of all on', 'Daman']
elements in the list.
2. >>>print(names[-1][-1])
7. To shuffle the list(say list1) what function
a) A
do we use?
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.

www.studymaterialz.in 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]
4. b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
5. names2[0] = 'Alice' d) [0.0, 0.5, 1.0, 1.5, 2.0]
6. names3[1] = 'Bob' Answer: c
7. Explanation: Execute in the shell to verify.

8. sum = 0 5. What will be the output of the following


Python code?
9. for ls in (names1, names2, names3):
1. >>>list1 = [11, 2, 23]
10. if ls[0] == 'Alice':
2. >>>list2 = [11, 2, 2]
11. sum += 1
3. >>>list1 < list2 is
12. if ls[1] == 'Bob':
a) True
13. sum += 10
b) False
14. c) Error
d) None
15. print sum
Answer: b
a) 11 Explanation: Elements are compared one by
b) 12 one.
c) 21
d) 22 6. To add a new element to a list we use
which command?
Answer: b a) list1.add(5)
Explanation: When assigning names1 to b) list1.append(5)
names2, we create a second reference to the c) list1.addLast(5)
same list. Changes to names2 affect names1. d) list1.addEnd(5)
When assigning the slice of all elements in
names1 to names3, we are creating a full Answer: b
copy of names1 which can be modified Explanation: We use the function append to
independently. add an element to the list.

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

www.studymaterialz.in 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”)
b) list1.remove(hello) 3. Suppose listExample is [3, 4, 5, 20, 5, 25,
c) list1.removeAll(“hello”) 1, 3], what is list1 after listExample.pop(1)?
d) list1.removeOne(“hello”) a) [3, 4, 5, 20, 5, 25, 1, 3]
b) [1, 3, 3, 4, 5, 5, 20, 25]
Answer: a c) [3, 5, 20, 5, 25, 1, 3]
Explanation: Execute in the shell to verify. d) [1, 3, 4, 5, 20, 5, 25]

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


list1.index(5)? Explanation: pop() removes the element at
a) 0 the position specified in the parameter.
b) 1
c) 4 4. Suppose listExample is [3, 4, 5, 20, 5, 25,
d) 2 1, 3], what is list1 after listExample.pop()?
a) [3, 4, 5, 20, 5, 25, 1]
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]
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
a) 0 the last element.
b) 4
c) 1 5. What will be the output of the following
d) 2 Python code?

Answer: d 1. >>>"Welcome to Python".split()


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

www.studymaterialz.in 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
Python code? Python code?

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


2. max = myList[0] 2. >>>list2 = list1
3. indexOfMax = 0 3. >>>list1[0] = 4
4. for i in range(1, len(myList)): 4. >>>print(list2)
5. if myList[i] > max: a) [1, 3]
b) [4, 3]
6. max = myList[i]
c) [1, 4]
7. indexOfMax = i d) [1, 3, 4]

8. Answer: b
Explanation: Lists should be copied by
9. >>>print(indexOfMax) executing [:] operation.
a) 1 10. What will be the output of the following
b) 2 Python code?
c) 3
d) 4 1. def f(values):

Answer: a 2. values[0] = 44
Explanation: First time the highest number is
encountered is at index 1. 3.
4. v = [1, 2, 3]
8. What will be the output of the following
Python code? 5. f(v)
1. myList = [1, 2, 3, 4, 5, 6] 6. print(v)
2. for i in range(1, 6): a) [1, 44]
b) [1, 2, 3, 44]
3. myList[i - 1] = myList[i]
c) [44, 2, 3]
4. d) [1, 2, 3]

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


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

www.studymaterialz.in 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.
a) None
5. f(1) b) a
c) b
6. f(2) d) c
7. v = f(3) Answer: d
8. print(v) Explanation: List Comprehension are a
shorthand for creating new lists.
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3] 4. What will be the output of the following
c) [1, 2, 3] Python code?
d) 1 2 3
1. numbers = [1, 2, 3, 4]
Answer: c 2.
Explanation: Execute in the shell to verify
3. numbers.append([5,6,7,8])
2. What will be the output of the following
Python code? 4.

1. names1 = ['Amir', 'Bala', 'Chales'] 5. print(len(numbers))

2. a) 4
b) 5
3. if 'amir' in names1: c) 8
d) 12
4. print(1)

5. else: Answer: b
Explanation: A list is passed in append so the
6. print(2) length is 5.

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


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

www.studymaterialz.in 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))
8. print(increment_items(values, 2))
a) 2 9. print(values)
b) 4
c) 5 a)
d) 8
None
Answer: d
Explanation: + appends all the elements [3, 4, 5]
individually into a new list.
b)
7. What will be the output of the following
None
Python code?
[1, 2, 3]
1. def addItem(listParam):
c)
2. listParam += [1]
[3, 4, 5]
3.
[1, 2, 3]
4. mylist = [1, 2, 3, 4]
d)
5. addItem(mylist)
[3, 4, 5]
6. print(len(mylist))
None
a) 1
b) 4 Answer: a
c) 5 Explanation: Execute in the shell to verify.
d) 8

Answer: c
Explanation: + will append the element to 9. What will be the output of the following
the list. Python code?

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


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

www.studymaterialz.in 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
a) Return a list containing every third item Explanation: Execute in the shell to verify.
from L starting at index 0
b) Return an empty list 2. How many elements are in m?
c) Return a list containing every third index
from L starting at index 0 1. m = [[x, y] for x in range(0, 4) fo
r y in range(0, 4)]
d) Return a list containing the items from L
starting from index 0, omitting every third a) 8
item b) 12
c) 16
Answer: a
d) 32
Explanation: Run the code to get a better
understanding with many arguments. Answer: c
Explanation: Execute in the shell to verify.
10. What will be the output of the following
Python code? 3. What will be the output of the following
Python code?
1. veggies = ['carrot', 'broccoli', 'p
otato', 'asparagus']
1. values = [[3, 4, 5, 1], [33, 6, 1,
2. veggies.insert(veggies.index('brocc 2]]
oli'), 'celery')
2.
3. print(veggies)
3. v = values[0][0]
a) [‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, 4. for row in range(0, len(values)):
‘asparagus’] Correct 1.00
b) [‘carrot’, ‘celery’, ‘potato’, ‘asparagus’] 5. for column in range(0, len(valu
es[row])):
c) [‘carrot’, ‘broccoli’, ‘celery’, ‘potato’,
‘asparagus’] 6. if v < values[row][column]:

7. v = values[row][column]
d) [‘celery’, ‘carrot’, ‘broccoli’, ‘potato’,
‘asparagus’] 8.

Answer: a 9. print(v)
Explanation: Execute in the shell to verify.
a) 3
1. What will be the output of the following b) 5
Python code? c) 6
d) 33

www.studymaterialz.in 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.
2.
6. What will be the output of the following
3. v = values[0][0] Python code?

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

5. for element in lst: 2. [4, 5, 6, 7],

6. if v > element: 3. [8, 9, 10, 11],

7. v = element 4. [12, 13, 14, 15]]

8. 5.

9. print(v) 6. for i in range(0, 4):

a) 1 7. print(matrix[i][1], end = " ")


b) 3
c) 5 a) 1 2 3 4
d) 6 b) 4 5 6 7
c) 1 3 8 12
Answer: a d) 2 5 9 13
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.
Python code?
7. What will be the output of the following
1. values = [[3, 4, 5, 1 ], [33, 6, 1, Python code?
2]]
1. def m(list):
2.
2. v = list[0]
3. for row in values:
3. for e in list:
4. row.sort()
4. if v < e: v = e
5. for element in row:
5. return v
6. print(element, end = " ")
6.
7. print()
7. values = [[3, 4, 5, 1], [33, 6, 1,
a) The program prints two rows 3 4 5 1 2]]
followed by 33 6 1 2

www.studymaterialz.in 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
d) 5 33 b) 2
c) 4
Answer: d d) 5
Explanation: Execute in the shell to verify.
Answer: c
8. What will be the output of the following Explanation: Execute in the shell to verify.
Python code?
10. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?
[7, 8]]]
1. points = [[1, 2], [3, 1.5], [0.5,
2. 0.5]]

3. print(data[1][0][0]) 2. points.sort()

a) 1 3. print(points)
b) 2
c) 4 a) [[1, 2], [3, 1.5], [0.5, 0.5]]
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]]
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.
Python code?
1. What will be the output of the following
1. data = [[[1, 2], [3, 4]], [[5, 6], Python code?
[7, 8]]]
a=[10,23,56,[78]]
2. b=list(a)
a[3][0]=95
3. def ttt(m): a[1]=34
print(b)
4. v = m[0][0]
a) [10,34,56,[95]]
5. b) [10,23,56,[78]]
c) [10,23,56,[95]]
6. for row in m: d) [10,34,56,[78]]
7. for element in row:
Answer: c
8. if v < element: v = elem Explanation: The above copy is a type of
ent

www.studymaterialz.in 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="@"
)))) a=list(s.partition("@"))
print(a)
a) b=list(s.split("@",3))
print(b)
[(1,2,3),(‘a’),(‘xxx’,’yyy’)]
a)
[(2,4),(‘b’,’c’),(‘yy’,’xx’)]
[‘a’,’b’,’c’,’d’]
b)
[‘a’,’b’,’c’,’d’]
[(1, 'a', 'xxx'),(2,’ ‘,’yyy’),(3,’ ‘,’
‘)] b)
[(2, 'b', 'yy'), (4, 'c', 'xx')] [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]

c) Syntax error [‘a’,’b’,’c’,’d’]


d)
c)
[(1, 'a', 'xxx')]
[‘a’,’@’,’@d’]
[(2, 'b', 'yy'), (4, 'c', 'xx')]
[‘a’,’b’,’c’,’d’]
Answer: d
Explanation: The zip function combines the d)
individual attributes of the lists into a list of
tuples. [‘a’,’@’,’@d’]

[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]

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

www.studymaterialz.in 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
Explanation: The above code returns the creates multiple reference copies of sublist.
cumulative sum of elements in a list. Hence when 7 is appended, it gets appended
to all the sublists.
6. What will be the output of the following
Python code? 9. What will be the output of the following
Python code?
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))
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)] b) [ ]
d) Syntax error c) [3,5]
d) Invalid arguments for filter function
Answer: a
Explanation: Variable x iterates over each Answer: c
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
Python code? 10. What will be the output of the following
Python code?
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)

a) 10 a) [3, 7, 8, 6, 1, 2]
b) [1,3,5,7] b) Syntax error
c) 4 c) [3,[7,8],6,1,2]
d) [1,3,6,10] d) [3,4,6,7,8]
Answer: d Answer: a
Explanation: The above code returns the Explanation: In the piece of code, slice
cumulative sum of elements in a list. assignment has been implemented. The sliced
list is replaced by the assigned elements in the
8. What will be the output of the following
list. Type in python shell to verify.
Python code?

a=[[]]*3
1. What will be the output of the following
a[1].append(7) Python code?

www.studymaterialz.in 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
Explanation: The append function simply
b) adds its arguments to the list as it is while
extend function extends its arguments and
[1, 2, 3, 4] later appends it.
None
4. What is the output of the following piece of
c) Syntax error code?
d) a=list((45,)*4)
print((45)*4)
[1,2,3] print(a)

[1,2,3,4]
a)
Answer: b
180
Explanation: Append function on lists
doesn’t return anything. Thus the value of b is [(45),(45),(45),(45)]
None.
b)

(45,45,45,45)
2. What will be the output of the following
[45,45,45,45]
Python code?

>>> a=[14,52,7]
c)
>>>> b=a.copy()
>>> b is a 180

[45,45,45,45]
a) True
b) False d) Syntax error
Answer: b Answer: c
Explanation: List b is just a copy of the Explanation: (45) is an int while (45,) is a
original list. Any copy made in list b will not tuple of one element. Thus when a tuple is
be reflected in list a. multiplied, it created references of itself
which is later converted to a list.
3. What will be the output of the following
Python code? 5. What will be the output of the following
a=[13,56,17]
Python code?
a.append([87])
lst=[[1,2],[3,4]]
print(sum(lst,[]))

www.studymaterialz.in 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
6. What will be the output of the following Answer: d
Python code? Explanation: unpack(*x) unpacks the list
into the separate variables. Now, a=1 and
word1="Apple"
word2="Apple" d=4. Thus 5 gets printed.
list1=[1,2,3]
list2=[1,2,3] 8. What will be the output of the following
print(word1 is word2) Python code?
print(list1 is list2)
places = ['Bangalore', 'Mumbai', 'Delhi']
a) <br class="blank" />places1 = places
places2 = places[:]
True <br class="blank" />places1[1]="Pune"
places2[2]="Hyderabad"
True print(places)

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


b) [‘Bangalore’, ‘Pune’, ‘Delhi’]
False c) [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
d) [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
True
Answer: b
c)
Explanation: places1 is an alias of the list
False places. Hence, any change made to places1 is
reflected in places. places2 is a copy of the
False list places. Thus, any change made to places2
isn’t reflected in places.
d)
9. What will be the output of the following
True
Python code?
False
x=[[1],[2]]
Answer: d print(" ".join(list(map(str,x))))
Explanation: In the above case, both the lists
a) [1] [2]
are equivalent but not identical as they have
b) [49] [50]
different objects.
c) Syntax error
d) [[1]] [[2]]

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

www.studymaterialz.in 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)
a) 561 1
b) 5
c) 12 [1,2,3]
d) Syntax error
c)
Answer: c
Explanation: First, map converts the number 3
to string and then places the individual digits
[1,2,3]
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.
1
11. What will be the output of the following
Python code? [44,2,3]

a= [1, 2, 3, 4, 5] Answer: a
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.
a) 5 5 1 2 3
b) 5 1 2 3 4
c) 2 3 4 5 1
13. What will be the output of the following
d) 2 3 4 5 5
Python code?
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
the first for-loop and the item of index four is for x in range(1, len(a)):
printed again because of the second for-loop. if a[x] > b:
b = a[x]
b= x
12. What will be the output of the following print(b)
Python code?
a) 5
def change(var, lst):
var = 1
b) 3
lst[0] = 44 c) 4
k = 3 d) 0
a = [1, 2, 3]
change(k, a)

www.studymaterialz.in 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"]
<br class="blank" />a.sort(key=len) print(k)
print(a)
a) all characters of my_string that aren’t
a) [‘Apple’, ‘Ball’, ‘Cobra’] vowels
b) [‘Ball’, ‘Apple’, ‘Cobra’] b) a list of Nones
c) [‘Cobra’, ‘Apple’, ‘Ball’] c) list of Trues
d) Invalid syntax for sort() d) list of Falses

Answer: b Answer: b
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. 3. What will be the output of the following
Python code snippet?
15. What will be the output of the following
Python code? my_string = "hello world"
k = [(i.upper(), len(i)) for i in my_stri
num = ['One', 'Two', 'Three'] ng]
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) Exception is thrown (‘ ‘, 1), (‘W’, 1), (‘O’, 1), (‘R’, 1), (‘L’, 1),
c) One Two Three (‘D’, 1)]
d) 0: One 1: Two 2: Three c) [(‘HELLO WORLD’, 11)]
d) none of the mentioned
Answer: d
Explanation: enumerate(iterator,start=0) is a Answer: b
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.

1. What will be the output of the following 4. Which of the following is the correct
Python code snippet? expansion of list_1 = [expr(i) for i in list_0 if
func(i)]?
k = [print(i) for i in my_string if i not a)
in "aeiou"]
list_1 = []
a) prints all the vowels in my_string for i in list_0:
b) prints all the consonants in my_string if func(i):
c) prints all characters of my_string that list_1.append(i)
aren’t vowels
b)
d) prints only on executing print(k)

www.studymaterialz.in 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’]]
d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
d) none of the mentioned ‘cf’]

Answer: c Answer: d
Explanation: We have to create an empty list, Explanation: If it were to be executed as a
loop over the contents of the existing list and nested for loop, i would be the outer loop and
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
Python code snippet?
5. What will be the output of the following
Python code snippet? print([[i+j for i in "abc"] for j in "de
f"])
x = [i**+1 for i in range(3)]; print(x);
a) [‘da’, ‘ea’, ‘fa’, ‘db’, ‘eb’, ‘fb’, ‘dc’, ‘ec’,
a) [0, 1, 2] ‘fc’]
b) [1, 2, 5] b) [[‘ad’, ‘bd’, ‘cd’], [‘ae’, ‘be’, ‘ce’], [‘af’,
c) error, **+ is not a valid operator ‘bf’, ‘cf’]]
d) error, ‘;’ is not allowed c) [[‘da’, ‘db’, ‘dc’], [‘ea’, ‘eb’, ‘ec’], [‘fa’,
‘fb’, ‘fc’]]
Answer: a d) [‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’,
Explanation: i**+1 is evaluated as (i)**(+1). ‘cf’]

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.
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’
c) [‘hello’] print([if i%2==0: i; else: i+1; for i in
d) hello range(4)])

Answer: a a) [0, 2, 2, 4]
Explanation: We are iterating over each letter b) [1, 1, 3, 3]
in the string. c) error
d) none of the mentioned
7. What will be the output of the following
Python code snippet? Answer: c
Explanation: Syntax error.

www.studymaterialz.in 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].

1. What will be the output of the following For example if we have a list l=[-65, 2, 7, -99,
Python code? -4, 3]
>>> [x for x in l if x<0]
l=[1,2,3,4,5] The output would be: [-65, -99, -4].
[x&1 for x in l]
4. What will be the output of the following
a) [1, 1, 1, 1, 1]
Python code?
b) [1, 0, 1, 0, 1]
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 a) Error
Explanation: In the code shown above, each b) [‘PUNE’, 4, ‘MUMBAI’, 6, ‘DELHI’, 5]
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’,
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
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
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)].
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?

l1=[2,4,6]
Answer: c l2=[-2,-4,-6]
Explanation: The code shown above returns for i in zip(l1, l2):
x*y, where x belongs to the list l1 and y print(i)
belongs to the list l2. Therefore, the output is:
[4, 5, 6, 8, 10, 12, 12, 15, 18]. a)

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


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

www.studymaterialz.in 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)

(6, -6) a) Error


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

Answer: c 1 4 7
Explanation: The output of the code shown 2 5 8
will be:
(2, -2) 3 6 9
(4, -4)
(6, -6) d)
This format is due to the statement print(i).
(1 4 7)
6. What will be the output of the following
(2 5 8)
Python code?
(3 6 9)
l1=[10, 20, 30]
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) 0 output of this code is: [[1, 4, 7], [2, 5, 8], [3,
c) [-20, -60, -80] 6, 9]].
d) [0, 0, 0]

Answer: d
Explanation: The code shown above returns 9. What will be the output of the following
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]. [str(round(math.pi)) for i in range (1, 6
)]
7. Write a list comprehension for number and
its cube for l=[1, 2, 3, 4, 5, 6, 7, 8, 9]. a) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
a) [x**3 for x in l] b) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’,
b) [x^3 for x in l] ‘3.141582’]
c) [x**3 in l] c) [‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
d) [x^3 in l] d) [‘3.1’, ‘3.14’, ‘3.142’, ‘3.1416’, ‘3.14159’]

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

www.studymaterialz.in 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]
l3=[7,8,9]
2. What will be the output of the following
for x, y, z in zip(l1, l2, l3): Python code?
print(x, y, z)
[ord(ch) for ch in 'abc']
a)
a) [97, 98, 99]
1 4 7 b) [‘97’, ‘98’, ‘99’]
c) [65, 66, 67]
2 5 8 d) Error
3 6 9
Answer: a
b) Explanation: The list comprehension shown
above returns the ASCII value of each
(1 4 7) alphabet of the string ‘abc’. Hence the output
is: [97, 98, 99]. Had the string been ‘ABC’,
(2 5 8) the output would be: [65, 66, 67].
(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
[round((x-32)*5/9) for x in t]
Answer: a
Explanation: The output of the code shown a) [0]
above is: b) 0
147 c) [0.00]
258 d) Error
369
This is due to the statement: print(x, y,z). Answer: d
Explanation: The value of t in the code
1. Read the information given below carefully shown above is equal to 32.00, which is a
and write a list comprehension such that the floating point value. ‘Float’ objects are not
output is: [‘e’, ‘o’] iterable. Hence the code results in an error.
w="hello" 4. Write a list comprehension for producing a
v=('a', 'e', 'i', 'o', 'u')
list of numbers between 1 and 1000 that are
divisible by 3.
a) [x for w in v if x in v]
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)]

www.studymaterialz.in 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)].

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


if int(i*0.5)==i*0.5: for?
print(i)
{x : x is a whole number less than 20, x
a) [i for i in range(1, 100) if int(i*0.5)== is even} (including zero)
(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)]
(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)]
(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: d
Explanation: The required list
Answer: b comprehension will print a whole number,
Explanation: The code shown above prints 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
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
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
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
Answer: c c) A list of non prime numbers, up to 50
Explanation: The output of the function d) Error
list(map(lambda x:x**-1, [1, 2, 3])) is [1.0,
Answer: c
0.5, 0.3333333333333333] and that of the list
Explanation: The list comprehension shown
comprehension [x**-1 for x in [1, 2, 3]] is
above returns a list of non-prime numbers up
[1.0, 0.5, 0.3333333333333333]. Hence the
to 50. The logic behind this is that the square
answer is: [x**-1 for x in [1, 2, 3]].
root of 50 is almost equal to 7. Hence all the
7. Write a list comprehension to produce the multiples of 2-7 are not prime in this range.
list: [1, 2, 4, 8, 16……212].
10. What will be the output of the following
a) [(2**x) for x in range(0, 13)]
Python code?
b) [(x**2) for x in range(1, 13)]

www.studymaterialz.in 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’]

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


Explanation: The code shown above returns Python code?
a new list containing only strings which do A = [[1, 2, 3],
not have any punctuation in them. The only [4, 5, 6],
string from the list which does not contain [7, 8, 9]]
any punctuation is ‘good’. Hence the output A[1]
of the code shown above is [‘good’].
a) [4, 5, 6]
1. Which of the following matrices will throw b) [3, 6, 9]
an error in Python? c) [1, 4, 7]
a) d) [1, 2, 3]

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


Explanation: We can index the rows and
[4, 5, 6], columns using normal index operations. The
[7, 8, 9]]
statement A[1] represents the second row,
that is, the middle row. Hence the output of
b) the code will be: [4, 5, 6].

B = [[3, 3, 3] 3. Which of the following Python statements


will result in the output: 6?
[4, 4, 4]
A = [[1, 2, 3],
[5, 5, 5]] [4, 5, 6],
[7, 8, 9]]
c)
a) A[2][3]
C = [(1, 2, 4), b) A[2][1]
(5, 6, 7),
c) A[1][2]
d) A[3][2]
(8, 9, 10)]
Answer: c
d) Explanation: The output that is required is 6,
that is, row 2, item 3. This position is
D = [2, 3, 4, represented by the statement: A[1][2].
3, 3, 3,
4. What will be the output of the following
4, 5, 6] Python code?

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


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

www.studymaterialz.in 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
Explanation: To get a particular column as 7. What will be the output of the following
output, we can simple iterate across the rows Python code?
and pull out the desired column, or iterate
through positions in rows and index as we go. A = [[1, 2, 3],
Hence the output of the code shown above is: [4, 5, 6],
[2, 5, 8]. [7, 8, 9]]

[[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]]
A = [[1, 2, 3],
b) Error
[4, 5, 6], c) [11, 12, 13], [14, 15, 16], [17, 18, 19]
[7, 8, 9]] d) [11, 12, 13, 14, 15, 16, 17, 18, 19]
[A[i][i] for i in range(len(A))]
Answer: a
a) [1, 5, 9] Explanation: The code shown above shows a
b) [3, 5, 7] list comprehension which adds 10 to each
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
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?
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,
[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 b) [4, 5, 6]
Python code? c) [3, 5, 7]
l=[[1, 2, 3], [4, 5, 6]]
d) [2, 5, 8]
for i in range(len(l)):
for j in range(len(l[i])): Answer: c
l[i][j]+=10 Explanation: This expression scales the
l common index to fetch A[0][2], A[1][1], etc.
We assume the matrix has the same number
a) No output of rows and columns.
b) Error

www.studymaterialz.in 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
B = [[3, 3, 3],
(3) for col in range(3)]
[4, 4, 4],
[5, 5, 5]]
a) [3, 6, 9, 16, 20, 24, 35, 40, 45] [[col1 * col2 for (col1, col2) in zip(row
b) Error 1, row2)] for (row1, row2) in zip(A, B)]
c) [0, 30, 60, 120, 160, 200, 300, 350, 400]
d) 0 a) [0, 30, 60, 120, 160, 200, 300, 350, 400]
b) [[3, 6, 9], [16, 20, 24], [35, 40, 45]]
Answer: a c) No output
Explanation: In the code shown above, we d) Error
have used list comprehension to combine
values of multiple matrices. We have Answer: b
multiplied the elements of the matrix B with Explanation: The list comprehension shown
that of the matrix A, in the range(3). Hence above results in the output: [[3, 6, 9], [16, 20,
the output of this code is: [3, 6, 9, 16, 20, 24, 24], [35, 40, 45]].
35, 40, 45].
12. What will be the output of the following
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],
A = [[0, 10, 20], [7, 8, 9]]
[30, 40, 50], B = [[3, 3, 3],
[60, 70, 80]] [4, 4, 4],
for row in A: [5, 5, 5]]
for col in row: zip(A, B)
r.append(col+10)
r a) Address of the zip object
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]
b) [10, 20, 30, 40, 50, 60, 70, 80, 90]
c) [11, 12, 13, 14, 15, 16, 17, 18, 19] Answer: a
d) [0, 10, 20, 30, 40, 50, 60, 70, 80] Explanation: The output of the code shown
above returns the address of the zip object. If
Answer: a we print it in the form of a list, we get:
Explanation: The code shown above adds 10 >>> list(zip(A, B))
to each element of the matrix and prints the [([1, 2, 3], [3, 3, 3]), ([4, 5, 6], [4, 4, 4]), ([7,
output row-wise. Since the list l already 8, 9], [5, 5, 5])]
contains some elements, the new elements are
appended to it. Hence the output of this code

www.studymaterialz.in 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.
c) {1, 2, 3}
5. What will be the output of the following
d) {}
Python code?
Answer: b
1. >>>t = (1, 2, 4, 3, 8, 9)
Explanation: Tuples are represented with
round brackets. 2. >>>[t[i] for i in range(0, len(t),
2)]
2. Suppose t = (1, 2, 4, 3), which of the
following is incorrect? a) [2, 3, 9]
a) print(t[3]) b) [1, 2, 4, 3, 8, 9]
b) t[3] = 45 c) [1, 4, 8]
c) print(max(t)) d) (1, 4, 8)
d) print(len(t))
Answer: c
Answer: b Explanation: Execute in the shell to verify.
Explanation: Values cannot be modified in
the case of tuple, that is, tuple is immutable. 6. What will be the output of the following
Python code?
3. What will be the output of the following
Python code? 1. d = {"john":40, "peter":45}

1. >>>t=(1,2,4,3) 2. d["john"]

2. >>>t[1:3] a) 40
b) 45
a) (1, 2) c) “john”
b) (1, 2, 4) d) “peter”
c) (2, 4)
d) (2, 4, 3) Answer: a
Explanation: Execute in the shell to verify.
Answer: c
Explanation: Slicing in tuples takes place 7. What will be the output of the following
just as it does in strings. Python code?

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


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

www.studymaterialz.in 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]

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

2. >>>t2 = (1, 2, 3, 4) a) 30
b) 24
3. >>>t1 < t2 c) 33
d) 12
a) True
b) False Answer: c
c) Error Explanation: Tuples can be used for keys
d) None into dictionary. The tuples can have mixed
length and the order of the items in the tuple
Answer: b
is considered when comparing the equality of
Explanation: Elements are compared one by
the keys.
one in this case.
1. What is the data type of (1)?
9. What will be the output of the following
a) Tuple
Python code?
b) Integer
1. >>>my_tuple = (1, 2, 3, 4) c) List
d) Both tuple and integer
2. >>>my_tuple.append( (5, 6, 7) )
Answer: b
3. >>>print len(my_tuple) Explanation: A tuple of one element must be
created as (1,).
a) 1
b) 2 2. If a=(1,2,3,4), a[1:-1] is _________
c) 5 a) Error, tuple slicing doesn’t exist
d) Error b) [2,3]
c) (2,3,4)
Answer: d d) (2,3)
Explanation: Tuples are immutable and don’t
have an append method. An exception is Answer: d
thrown in this case. Explanation: Tuple slicing exists and a[1:-1]
returns (2,3).
10. What will be the output of the following
Python code? 3. What will be the output of the following
Python code?
1. numberGames = {}
>>> a=(1,2,(4,5))
2. numberGames[(1,2,4)] = 8 >>> b=(1,2,(3,4))
>>> a<b

www.studymaterialz.in 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?
in the subtuple of b, False is printed.
>>> a=(1,2,3,4)
>>> del a
4. What will be the output of the following
Python code?
a) No because tuple is immutable
>>> a=("Check")*3 b) Yes, first element in the tuple is deleted
>>> a c) Yes, the entire tuple is deleted
d) No, invalid syntax for del method
a) (‘Check’,’Check’,’Check’)
b) * Operator not valid for tuples Answer: c
c) (‘CheckCheckCheck’) Explanation: The command del a deletes the
d) Syntax error entire tuple.

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


Explanation: Here (“Check”) is a string not a a) Array of tuples
tuple because there is no comma after the b) List of tuples
element. c) Tuples of lists
d) Invalid type
5. What will be the output of the following
Python code? Answer: 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])
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) >>> a=(0,1,2,3,4)
d) Error as tuple is immutable >>> b=slice(0,2)
>>> a[b]
Answer: d
Explanation: ‘tuple’ object doesn’t support a) Invalid syntax for slicing
item deletion. b) [0,2]
c) (0,1)
6. What will be the output of the following d) (0,2)
Python code?
Answer: c
>>> a=(2,3,4) Explanation: The method illustrated in the
>>> sum(a,3) above piece of code is that of naming of
slices.
a) Too many arguments for sum() method
b) The method sum() doesn’t exist for tuples 10. Is the following Python code valid?

www.studymaterialz.in 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?
Answer: a >>> a,b=1,2,3
Explanation: Zip function combines
individual elements of two iterables into a) Yes, this is an example of tuple unpacking.
tuples. Execute in Python shell to verify. a=1 and b=2
b) Yes, this is an example of tuple unpacking.
1. Is the following Python code valid? a=(1,2) and b=3
c) No, too many values to unpack
>>> a,b,c=1,2,3
>>> a,b,c d) Yes, this is an example of tuple unpacking.
a=1 and b=(2,3)
a) Yes, [1,2,3] is printed
b) No, invalid syntax Answer: c
c) Yes, (1,2,3) is printed Explanation: For unpacking to happen, the
d) 1 is printed number of values of the right hand side must
be equal to the number of variables on the left
Answer: c hand side.
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
Python code? >>> a=(1,2)
>>> b=(3,4)
>>> c=a+b
a = ('check',)
>>> c
n = 2
for i in range(int(n)):
a = (a,) a) (4,6)
print(a) b) (1,2,3,4)
c) Error as tuples are immutable
a) Error, tuples are immutable d) None
b)
Answer: b
(('check',),) Explanation: In the above piece of code, the
values of the tuples aren’t being changed.
((('check',),),)
Both the tuples are simply concatenated.
c) ((‘check’,)’check’,)
5. What will be the output of the following
d)
Python code?
(('check',)’check’,)
>>> a,b=6,7
((('check',)’check’,)’check’,) >>> a,b=b,a
>>> a,b

www.studymaterialz.in 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)
c) None
6. What will be the output of the following
d) Error, tuple has no attribute sort
Python code?

>>> import collections


Answer: d
>>> a=collections.namedtuple('a',['i','j' Explanation: A tuple is immutable thus it
]) doesn’t have a sort attribute.
>>> obj=a(i=4,j=7)
>>> obj 10. Is the following Python code valid?
a) a(i=4, j=7) >>> a=(1,2,3)
b) obj(i=4, j=7) >>> b=a.update(4,)
c) (4,7)
d) An exception is thrown a) Yes, a=(1,2,3,4) and b=(1,2,3,4)
b) Yes, a=(1,2,3) and b=(1,2,3,4)
Answer: a c) No because tuples are immutable
Explanation: The above piece of code d) No because wrong syntax for update()
illustrates the concept of named tuples. method

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.

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


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?
>>> a
>>> a=2,3,4,5
>>> a a) [(1, 2), (2, 4), (3, 9)]
b) [(2,4),(1,2),(3,9)]
a) Yes, 2 is printed c) Error because tuples are immutable
b) Yes, [2,3,4,5] is printed d) Error, tuple has no sort attribute
c) No, too many values to unpack
d) Yes, (2,3,4,5) is printed Answer: a
Explanation: A list of tuples is a list itself.
Answer: d Hence items of a list can be sorted.
Explanation: A tuple needn’t be enclosed in
parenthesis. TOPIC 4.3 DICTIONARIES
(OPERATIONS AND METHODS)

www.studymaterialz.in 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
specifying keys and values. 5. What will be the output of the following
Python code snippet?
2. What will be the output of the following
Python code snippet? 1. d1 = {"john":40, "peter":45}

1. d = {"john":40, "peter":45} 2. d2 = {"john":466, "peter":45}


3. d1 > d2
a) “john”, 40, 45, and “peter”
b) “john” and “peter”
a) True
c) 40 and 45
b) False
d) d = (40:”john”, 45:”peter”)
c) Error
d) None
Answer: b
Explanation: Dictionaries appear in the form
Answer: c
of keys and values.
Explanation: Arithmetic > operator cannot
be used with dictionaries.
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}
2. "john" in d 1. d = {"john":40, "peter":45}
2. d["john"]
a) True
b) False a) 40
c) None b) 45
d) Error c) “john”
d) “peter”
Answer: a
Explanation: In can be used to check if the
Answer: a
key is int dictionary.
Explanation: Execute in the shell to verify.
4. What will be the output of the following
7. Suppose d = {“john”:40, “peter”:45}, to
Python code snippet? delete the entry for “john” what command do
we use?
1. d1 = {"john":40, "peter":45}
a) d.delete(“john”:40)
2. d2 = {"john":466, "peter":45} b) d.delete(“john”)
c) del d[“john”]
3. d1 == d2 d) del d(“john”:40)

www.studymaterialz.in 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.
d) d.len()
2. Which of the following is not a declaration
Answer: b of the dictionary?
Explanation: Execute in the shell to verify. a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
9. What will be the output of the following c) {1,”A”,2”B”}
Python code snippet? d) { }

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


Explanation: Option c is a set, not a
2. print(list(d.keys())) dictionary.
a) [“john”, “peter”] 3. What will be the output of the following
b) [“john”:40, “peter”:45] Python code snippet?
c) (“john”, “peter”)
d) (“john”:40, “peter”:45) a={1:"A",2:"B",3:"C"}
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
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”
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
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
c) Since “susan” is not a key in the set, 4. What will be the output of the following
Python raises a KeyError exception Python code snippet?
d) Since “susan” is not a key in the set, a={1:"A",2:"B",3:"C"}
Python raises a syntax error print(a.get(1,4))

Answer: c a) 1
Explanation: Execute in the shell to verify. b) A
c) 4
1. Which of these about a dictionary is false? d) Invalid syntax for get method
a) The values of a dictionary can be accessed
using keys

www.studymaterialz.in 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
Python code?
a={1:"A",2:"B",3:"C"}
print(a.get(5,4)) a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a) Error, invalid syntax a.update(b)
b) A print(a)
c) 5
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
d) 4
b) Method update() doesn’t exist for
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 d) {4: ‘D’, 5: ‘E’}
isn’t present in the dictionary.
Answer: c
6. What will be the output of the following Explanation: update() method adds
Python code snippet? dictionary b’s key-value pairs to dictionary a.
Execute in python shell to verify.
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) C a={1:"A",2:"B",3:"C"}
c) {1: 3, 2: 3, 3: 3} b=a.copy()
b[2]="D"
d) No method called setdefault() exists for print(a)
dictionary
a) Error, copy() method doesn’t exist for
Answer: b 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’}
already in the dictionary. d) “None” is printed
7. What will be the output of the following Answer: b
Python code snippet? Explanation: Changes made in the copy of
the dictionary isn’t reflected in the original
a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D") one.
print(a)
10. What will be the output of the following
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’} Python code?
b) None

www.studymaterialz.in 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
Answer: d dictionary.
Explanation: The clear() method clears all
14. What will be the output of the following
the key-value pairs in the dictionary.
Python code?
11. Which of the following isn’t true about a={1:"A",2:"B",3:"C"}
dictionary keys? for i in a:
a) More than one key isn’t allowed print(i,end=" ")
b) Keys must be immutable
c) Keys must be integers a) 1 2 3
d) When duplicate keys encountered, the last b) ‘A’ ‘B’ ‘C’
assignment wins c) 1 ‘A’ 2 ‘B’ 3 ‘C’
d) Error, it should be: for i in a.items():
Answer: c
Explanation: Keys of a dictionary may be Answer: a
any data type that is immutable. Explanation: The variable i iterates over the
keys of the dictionary and hence the keys are
12. What will be the output of the following printed.
Python code?
15. What will be the output of the following
a={1:5,2:3,3:4} Python code?
a.pop(3)
print(a) >>> a={1:"A",2:"B",3:"C"}
>>> a.items()
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)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])
Answer: b
Explanation: pop() method removes the key- Answer: d
value pair for the key mentioned in the pop() Explanation: The method items() returns list
method. of tuples with each tuple having a key-value
pair.
13. What will be the output of the following
Python code? 1. Which of the statements about dictionary
values if false?
a={1:5,2:3,3:4} a) More than one key can have the same
print(a.pop(4,9))
value
a) 9 b) The values of the dictionary can be
b) 3 accessed as dict[key]

www.studymaterialz.in 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
Python code snippet? keys present since the key ‘Apple’ is
repeated. Thus, the length of the dictionary is
>>> a={1:"A",2:"B",3:"C"} 2.
>>> del a
5. What will be the output of the following
a) method del doesn’t exist for the dictionary
Python code snippet?
b) del deletes the values in the dictionary
c) del deletes the entire dictionary a = {}
d) del deletes the keys in the dictionary a[1] = 1
a['1'] = 2
Answer: c a[1]=a[1]+1
Explanation: del deletes the entire dictionary count = 0
for i in a:
and any further attempt to access it will throw count += a[i]
an error. print(count)

3. If a is a dictionary with some key-value a) 1


pairs, what does a.popitem() do? 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
given as an argument
d) Invalid method for dictionary Answer: c
Explanation: The above piece of code
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
Python code snippet?
4. What will be the output of the following
Python code snippet? numbers = {}
letters = {}
total={} comb = {}
def insert(items): numbers[1] = 56
if items in total: numbers[3] = 7
total[items] += 1 letters[4] = 'B'
else: comb['Numbers'] = numbers
total[items] = 1 comb['Letters'] = letters
insert('Apple') print(comb)
insert('Ball')
insert('Apple') a) Error, dictionary in a dictionary can’t exist
print (len(total)) b) ‘Numbers’: {1: 56, 3: 7}
c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}}

www.studymaterialz.in 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?
Answer: c
test = {1:'A', 2:'B', 3:'C'}
test = {} Explanation: The value of key 1 is 4 since 1
print(len(test)) and 1.0 are the same. Then, the function
count() gives the sum of all the values of the
a) 0 keys (2+4).
b) None
c) 3 10. What will be the output of the following
d) An exception is thrown Python code snippet?

Answer: a a={}
Explanation: In the second line of code, the a['a']=1
a['b']=[2,3,4]
dictionary becomes an empty dictionary. print(a)
Thus, length=0.
a) Exception is thrown
8. What will be the output of the following b) {‘b’: [2], ‘a’: 1}
Python code snippet? 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
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.
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?
already deleted
d) 1 >>>import collections
>>> a=collections.Counter([1,1,2,3,3,4,4,
Answer: b 4])
>>> a
Explanation: After the key-value pair of
1:’A’ is deleted, the key-value pair of 1:’D’ is a) {1,2,3,4}
added. b) Counter({4, 1, 3, 2})
c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
9. What will be the output of the following
d) {4: 3, 1: 2, 3: 2, 2: 1}
Python code snippet?

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

www.studymaterialz.in 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])
>>> b=collections.Counter([3,4,4,5,5,5])
a) Counter({4: 3, 2: 2, 3: 1}) >>> a&b
b) {3:1}
c) {4:3} a) Counter({3: 12, 4: 1, 5: 1})
d) [(4, 3)] b) Counter({3: 1, 4: 1, 5: 1})
c) Counter({4: 2})
Answer: d d) Counter({5: 1})
Explanation: The most_common() method
returns the n number key-value pairs where Answer: b
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? 1. The following Python code is invalid.

>>>import collections class demo(dict):


>>> b=collections.Counter([2,2,3,4,4,4]) def __test__(self,key):
>>> b.most_common(1) return []
a = demo()
a) Counter({4: 3, 2: 2, 3: 1}) a['test'] = 7
print(a)
b) {3:1}
c) {4:3} a) True
d) [(4, 3)] b) False
Answer: d 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.
2. What will be the output of the following
14. What will be the output of the following Python code?
Python code snippet?
count={}
>>> import collections count[(1,2,4)] = 5
>>> a=collections.Counter([2,2,3,3,3,4]) count[(4,2,1)] = 7
>>> b=collections.Counter([2,2,3,4,4]) count[(1,2)] = 6
>>> a|b count[(4,2,1)] = 2
tot = 0
a) Counter({3: 3, 2: 2, 4: 2}) for i in count:
b) Counter({2: 2, 3: 1, 4: 1}) tot=tot+count[i]
c) Counter({3: 2}) print(len(count)+tot)
d) Counter({4: 1})
a) 25
b) 17

www.studymaterialz.in 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?
3. What will be the output of the following
Python code? >>> a={}
>>> a.fromkeys([1,2,3],"check")
a={}
a[2]=1 a) Syntax error
a[1]=[2,3,4] b) {1:”check”,2:”check”,3:”check”}
print(a[1][1]) c) “check”
d) {1:None,2:None,3:None}
a) [2,3,4]
b) 3 Answer: b
c) 2 Explanation: The dictionary takes values of
d) An exception is thrown keys from the list and initializes it to the
default value (value given in the second
Answer: b parameter). Execute in Python shell to verify.
Explanation: Now, a={1:[2,3,4],2:1} . a[1]
[1] refers to second element having key 1. 7. What will be the output of the following
Python code?
4. What will be the output of the following
Python code? >>> b={}
>>> all(b)
>>> a={'B':5,'A':9,'C':7}
>>> sorted(a) a) { }
b) False
a) [‘A’,’B’,’C’] c) True
b) [‘B’,’C’,’A’] d) An exception is thrown
c) [5,7,9]
d) [9,5,7] Answer: c
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 dictionary is empty.
in the dictionary.
8. If b is a dictionary, what does any(b) do?
5. What will be the output of the following a) Returns True if any key of the dictionary is
Python code? true
b) Returns False if dictionary is empty
>>> a={i: i*i for i in range(6)}
>>> a c) Returns True if all keys of the dictionary
are true
a) Dictionary comprehension doesn’t exist d) Method any() doesn’t exist for dictionary
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}

www.studymaterialz.in 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


>>> b=dict(zip(a.values(),a.keys())) >>> a=dict()
>>> b >>> a=collections.defaultdict(int)
>>> a[1]
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown a) 1
c) {‘a’: ‘b’: ‘c’: } b) 0
d) {1: ‘a’, 2: ‘b’, 3: ‘c’} c) An exception is thrown
d) ‘ ‘
Answer: d
Explanation: The above piece of code inverts Answer: b
the key-value pairs in the dictionary. Explanation: The statement
a=collections.defaultdict(int) gives the default
10. What will be the output of the following value of 0
Python code? (since int data type is given within the
parenthesis) even if the keys don’t exist in the
>>> a={i: 'A' + str(i) for i in range(5)} dictionary.
>>> a
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’} >>> 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']
Answer: b
Explanation: Dictionary comprehension and a) An exception is thrown since the dictionary
string concatenation is implemented in the is empty
above piece of code. b) ‘ ‘
c) ‘A’
11. What will be the output of the following d) 0
Python code?
Answer: b
>>> a=dict() Explanation: The statement
>>> a[1] a=collections.defaultdict(str) gives the default
value of ‘ ‘ even if the keys don’t exist in the
a) An exception is thrown since the dictionary dictionary.
is empty
b) ‘ ‘ 14. What will be the output of the following
c) 1 Python code?
d) 0

www.studymaterialz.in 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.

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


Explanation: The statement use ____________
a=collections.defaultdict(lambda: x) gives the a) outfile = open(“c:\scores.txt”, “w”)
default value of x even if the keys don’t exist b) outfile = open(“c:\scores.txt”, “w”)
in the dictionary. c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\scores.txt”, “w”)
15. What will be the output of the following
Python code? Answer: b
Explanation: w is used to indicate that file is
>>> import collections to be written to.
>>> a=collections.OrderedDict((str(x),x)
for x in range(3)) 3. To open a file c:\scores.txt for appending
>>> a data, we use ____________
a) outfile = open(“c:\scores.txt”, “a”)
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”)
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
Explanation: The line of code
to be appended.
a=collections.OrderedDict() generates a
dictionary satisfying the conditions given 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
b) When you open a file for writing, if the file
does not exist, a new file is created
c) When you open a file for writing, if the file
UNIT V FILES, exists, the existing file is overwritten with the
MODULES, PACKAGES new file
d) All of the mentioned
TOPIC 5.1 TEXT FILES, Answer: d
READING AND WRITING Explanation: The program will throw an
FILES, FORMAT OPERATOR error.

5. To read two characters from a file object


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

www.studymaterialz.in 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)
file as a string from a file object infile, we use b) infile.read()
____________ c) infile.readline()
a) infile.read(2) d) infile.readlines()
b) infile.read()
c) infile.readline() Answer: d
d) infile.readlines() Explanation: Execute in the shell to verify.

Answer: b 10. The readlines() method returns


Explanation: read function is used to read all ____________
the lines in a file. a) str
b) a list of lines
7. What will be the output of the following c) a list of single characters
Python code? d) a list of integers

1. f = None Answer: b
Explanation: Every line is stored in a list and
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
4. if i > 2: by default comes from the keyboard?
a) Raw_input & Input
5. break b) Input & Scan
c) Scan & Scanner
6. print(f.closed) d) Scanner
a) True
Answer: a
b) False
Explanation: Python provides two built-in
c) None
functions to read a line of text from standard
d) Error input, which by default comes from the
Answer: a keyboard. These functions are:
Explanation: The WITH statement when raw_input and input
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

www.studymaterialz.in 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.
Received input is : Hello 4. Which one of the following is not attributes
of file?
c)
a) closed
Enter your input: Hello Python b) softspace
c) rename
Received input is : Python d) mode

d) None of the mentioned Answer: c


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 Attribute Description
and returns it as a string. This would prompt
file.closed Returns true if file is c
you to enter any string and it would display losed, false otherwise.
same string on the screen. When I typed
“Hello Python!” file.mode Returns access mode with
which file was opened.
3. What will be the output of the following
file.name Returns name of the file.
Python code?
file.softspace Returns false if space ex
1. str = input("Enter your input: "); plicitly required with print, true otherw
ise.
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
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
Received input is : [x*5 for x in range
(2,10,2)] Answer: a
Explanation: The tell() method tells you the
b) current position within the file; in other
words, the next read or write will occur at that
Enter your input: [x*5 for x in range(2,1
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)

www.studymaterialz.in 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.
d) None of the mentioned
rename(current_file_name, new_file_name)
Answer: c
7. What is the current syntax of remove() a
Explanation: It displays the output as shown
file?
below. The method next() is used when a file
a) remove(file_name)
is used as an iterator, typically in a loop, the
b) remove(new_file_name, next() method is called repeatedly. This
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
Output:
Answer: a Name of the file: foo.txt
Explanation: remove(file_name)
Line No 0 - This is 1st line
8. What will be the output of the following
Python code?
Line No 1 - This is 2nd line
1. fo = open("foo.txt", "rw+")
2. print "Name of the file: ", fo.name
Line No 2 - This is 3rd line
3.
4. # Assuming file has following 5 lin
es Line No 3 - This is 4th line

5. # This is 1st line


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?


a) sets the file’s current position at the offset
8. # This is 4th line b) sets the file’s previous position at the offset
9. # This is 5th line c) sets the file’s current position within the
file
10. d) none of the mentioned

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


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

www.studymaterialz.in 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:
values are 1 which means seek relative to the
current position and 2 means seek relative to 5. c = sys.stdin.read(1)
the file’s end.
6. if c == '\n':
10. What is the use of truncate() method in
file? 7. break
a) truncates the file size 8. name = name + c
b) deletes the content of the file
c) deletes the file size 9.
d) none of the mentioned
10. print 'Your name is:', name
Answer: a
Explanation: The method truncate() truncates a) sanfoundry
the file size. Following is the syntax for b) sanfoundry, sanfoundry
truncate() method: c) San
fileObject.truncate( [ size ]) d) None of the mentioned

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.
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
file? prompt saying “Enter your name”. We enter
a) Standard Input our name and press enter. The enter key
b) Standard Output generates the new line character: \n.
c) Standard Errors Output:
d) All of the mentioned Enter your name: sanfoundry
Your name is: sanfoundry
Answer: d
Explanation: Standard input, standard output 3. What will be the output of the following
and standard error. Standard input is the data Python code?
that goes to the program. The standard input
comes from a keyboard. Standard output is 1. import sys
where we print our data with the print
2. sys.stdout.write(' Hello\n')
keyword. Unless redirected, it is the terminal
console. The standard error is a stream where 3. sys.stdout.write('Python\n')
programs write their error messages. It is
usually the text terminal. a) Compilation Error
b) Runtime Error

www.studymaterialz.in 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
Output: simple textual data. What if we are working
Hello with objects rather than simple text? For such
Python situations, we can use the pickle module. This
module serializes Python objects. The Python
objects are converted into byte streams and
written to text files. This process is called
4. Which of the following mode will refer to pickling. The inverse operation, reading from
binary data? a file and reconstructing objects is called
a) r deserializing or unpickling.
b) w
c) + 7. What is the correct syntax of open()
d) b function?
a) file = open(file_name [, access_mode][,
Answer:d buffering])
Explanation: Mode Meaning is as explained b) file object = open(file_name [,
below: access_mode][, buffering])
r Reading c) file object = open(file_name)
w Writing d) none of the mentioned
a Appending
b Binary data Answer: 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]
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
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
Explanation: Pickle is the standard the mode in which the file has to be opened,
mechanism for object serialization. Pickle i.e., read, write, append, etc. A complete list
uses a simple stack-based virtual machine that of possible values is given below in the table.
records the instructions used to reconstruct This is optional parameter and the default file
the object. This makes pickle vulnerable to access mode is read (r).
security risks by malformed or maliciously buffering: If the buffering value is set to 0, no
constructed data, that may cause the buffering will take place. If the buffering
deserializer to import arbitrary modules and value is 1, line buffering will be performed
instantiate any object. while accessing a file. If you specify the
buffering value as an integer greater than 1,
then buffering action will be performed with

www.studymaterialz.in 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

www.studymaterialz.in 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
python?
Answer: a a) Close()
Explanation: The read function reads all b) Stop()
characters fh = open(“filename”, “r”) c) End()
content = fh.read(). d) Closefile()
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
b) Readlines() file.
c) Readstatement()
d) Readfullline() 9. Is it possible to create a text file in python?
a) Yes
Answer: b b) No
Explanation: The readline function reads a c) Machine dependent
single line from the file fh = open(“filename”, d) All of the mentioned
“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.
characters? file = open(“newfile.txt”, “w”)
a) write() file.write(“hello world in the new file\n”)
b) writecharacters() file.write(“and another line\n”)
c) writeall() file.close().
d) writechar()
10. Which of the following are the modes of
Answer: a both writing and reading in binary format in
Explanation: To write a fixed sequence of file?
characters to a file a) wb+
fh = open(“hello.txt”,”w”) b) w
write(“Hello World”). c) wb
d) w+
7. Which function is used to write a list of
string in a file? Answer: a
a) writeline() Explanation: Here is the description below
b) writelines() “w” Opens a file for writing only. Overwrites
c) writestatement() the file if the file exists. If the file does not
d) writefullline() exist, creates a new file for writing.
“wb” Opens a file for writing only in binary

www.studymaterialz.in 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
existing file if the file exists. If the file does Answer: d
not exist, creates a new file for reading and Explanation: fp.size has not been
writing. implemented.

1. Which of the following is not a valid mode 5. How do you close a file object (fp)?
to open a file? a) close(fp)
a) ab b) fclose(fp)
b) rw c) fp.close()
c) r+ d) fp.__close__()
d) w+
Answer: c
Answer: b Explanation: close() is a method of the file
Explanation: Use r+, w+ or a+ to perform object.
both read and write operations using a single
file object. 6. How do you get the current position within
the file?
2. What is the difference between r+ and w+ a) fp.seek()
modes? b) fp.tell()
a) no difference c) fp.loc
b) in r+ the pointer is initially placed at the d) fp.pos
beginning of the file and the pointer is at the
end for w+ Answer: b
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?
d) depends on the operating system
a) fp.name = ‘new_name.txt’
Answer: b b) os.rename(existing_name, new_name)
Explanation: none. c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
3. How do you get the name of a file from a
file object (fp)? Answer: b
a) fp.name Explanation: os.rename() is used to rename
b) fp.file(name) files.
c) self.__name__(fp)
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’)

www.studymaterialz.in 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)
d) none of the mentioned
class foo:
def __init__(self, x):
Answer: a self.x = x
Explanation: 0 indicates that the offset is def __less__(self, other):
with respect to the start. if self.x > other.x:
return False
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 c)
b) file position is set to the end of file
c) file position remains unchanged class foo:
d) error def __init__(self, x):
self.x = x
Answer: d def __lt__(self, other):
if self.x < other.x:
Explanation: seek() takes at least one return True
argument. else:
return False
1. Which function is called when the
following Python code is executed? d)

f = foo() class foo:


format(f) def __init__(self, x):
self.x = x
a) format() def __less__(self, other):
b) __format__() if self.x < other.x:
return False
c) str() else:
d) __str__() return True

Answer: d Answer: c
Explanation: Both str(f) and format(f) call Explanation: __lt__ overloads the <
f.__str__(). operator>.

2. Which of the following Python code will


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

www.studymaterialz.in 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) ||
b) |
Answer: b c) //
Explanation: __invert__() overloads ~. d) /
5. Which function overloads the == operator? Answer: b
a) __eq__() Explanation: The function __or__()
b) __equ__() overloads the bitwise OR operator |.
c) __isequal__()
d) none of the mentioned 10. Which function overloads the // operator?
a) __div__()
Answer: a b) __ceildiv__()
Explanation: The other two do not exist. c) __floordiv__()
d) __truediv__()
6. Which operator is overloaded by __lg__()?
a) < Answer: c
b) > Explanation: __floordiv__() is for //.
c) !=
d) none of the mentioned
TOPIC 5.2 EXCEPTION
Answer: d HANDLING
Explanation: __lg__() is invalid.
1. How many except statements can a try-
7. Which function overloads the >> operator? except block have?
a) __more__() a) zero
b) __gt__() b) one
c) __ge__() c) more than one
d) none of the mentioned d) more than zero
Answer: d Answer: d
Explanation: __rshift__() overloads the >> Explanation: There has to be at least one
operator. except statement.
8. Let A and B be objects of class Foo. Which 2. When will the else part of try-except-else
functions are called when print(A + B) is be executed?
executed? a) always
a) __add__(), __str__() b) when an exception occurs
b) __str__(), __add__() c) when no exception occurs
c) __sum__(), __str__() d) when an exception occurs in to except
d) __str__(), __sum__() block

www.studymaterialz.in 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:
# Do something Explanation: The finally block is always
finally: executed.
# Do something
7. What will be the output of the following
a) no, there is no such thing as finally Python code?
b) no, finally cannot be used with except
c) no, finally must come before except def foo():
d) yes try:
return 1
finally:
Answer: b return 2
Explanation: Refer documentation. k = foo()
print(k)
4. Is the following Python code valid?
a) 1
try: b) 2
# Do something c) 3
except:
# Do something d) error, there is more than one return
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) no, else cannot be used with except even there is a return statement in the try
c) no, else must come before except block.
d) yes
8. What will be the output of the following
Answer: d Python code?
Explanation: Refer documentation.
def foo():
5. Can one block of except statements handle try:
print(1)
multiple exception? finally:
a) yes, like except TypeError, SyntaxError print(2)
[,…] foo()
b) yes, like except [TypeError, SyntaxError]
c) no a) 1 2
d) none of the mentioned b) 1
c) 2
Answer: a d) none of the mentioned
Explanation: Each type of exception can be
specified directly. There is no need to put it in Answer: a
a list. Explanation: No error occurs in the try block

www.studymaterialz.in 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'
else:
print("someError has not occurre a) Assertion Error
d") b) 10 8
except "someError":
print ("someError has occurred") c) No output
d) 108
a) someError has occurred
b) someError has not occurred Answer: c
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
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 output.
inherit from a BaseException. There is no
such inheritance here. 3. What will be the output of the following
Python code?
10. What happens when ‘1’ == 1 is executed?
#generator
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))

Answer: b a) 8
Explanation: It simply evaluates to False and b) 9
does not raise any exception. c) 7
d) Error
1. The following Python code will result in an
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
have used to keyword yield. The value of x is
a) True 8. Hence the output of the code is 9.
b) False
4. What will be the output of the following
Answer: a Python code?
Explanation: The code shown above results
in an assertion error. The output of the code def f(x):
is: yield x+1
Traceback (most recent call last): print("test")
yield x+2
File “<pyshell#0>”, line 1, in <module> g=f(9)
assert False, ‘Spanish’

www.studymaterialz.in 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:
f(x, 4)
d) No output finally:
print('after f')
Answer: d print('after f?')
Explanation: The code shown above will not a()
yield any output. This is because when we try
to yield 9, and there is no next(g), the a) No output
iteration stops. Hence there is no output. b) after f?
c) error
5. What will be the output of the following d) after f
Python code?
Answer: c
def f(x): Explanation: This code shown above will
yield x+1 result in an error simply because ‘f’ is not
print("test") defined. ‘try’ and ‘finally’ are keywords used
yield x+2
in exception handling.
g=f(10)
print(next(g))
print(next(g)) 7. What will be the output of the following
Python code?
a) No output
b) def f(x):
for i in range(5):
yield i
11
g=f(8)
print(list(g))
test

12 a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]
11
Answer: a
test
Explanation: The output of the code shown
d) 11 above is a list containing whole numbers in
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)

www.studymaterialz.in 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
Answer: b
c) Input output error
Explanation: The error raised in the code
d) Name error
shown above is that: ‘tuple’ object is not
iterator. Had we given l2 as argument to next, Answer: a
the error would have been: ‘list’ object is not Explanation: In the code shown above, if the
iterator. input file in not found, then the statement:
“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.
a) try
b) except 2. What will be the output of the following
c) accept Python code?
d) finally
lst = [1, 2, 3]
Answer: c lst[3]
Explanation: The keywords ‘try’, ‘except’
and ‘finally’ are exception handling keywords a) NameError
in python whereas the word ‘accept’ is not a b) ValueError
keyword at all. c) IndexError
d) TypeError
10. What will be the output of the following
Python code? Answer: c
Explanation: The snippet of code shown
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’>
list is 2.
b) class <‘iteration’>
c) class <’range’> 3. What will be the output of the following
d) class <’generator’> Python code?
Answer: d t[5]
Explanation: Another way of creating a
generator is to use parenthesis. Hence the a) IndexError
output of the code shown above is: b) NameError
class<’generator’>. c) TypeError
d) ValeError
1. What happens if the file is not found in the
following Python code? Answer: b
Explanation: The expression shown above

www.studymaterialz.in 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
a) NameError Explanation: The first code results in a
b) IndexError ValueError. This is because when we enter the
c) ValueError input as -6, we are trying to find the factorial
d) TypeError of a negative number, which is not possible.
The second code results in a NameError. This
Answer: d is because we have not imported the math
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
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. def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
5. What will be the output of the following print(m)
Python code? getMonth(6)

int('65.43') a) ValueError
b) Invalid
a) ImportError c) 6
b) ValueError d) ValueError(“Invalid”)
c) TypeError
d) NameError Answer: c
Explanation: In the code shown above, since
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
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.
6. Compare the following two Python codes 8. What will be the output of the following
shown below and state the output if the input Python code if the input entered is 6?
entered in each case is -6?
valid = False
CODE 1 while not valid:
import math try:
num=int(input("Enter a number of whose fa n=int(input("Enter a number"))
ctorial you want to find")) while n%2==0:
print(math.factorial(num)) print("Bye")
valid = True
CODE 2 except ValueError:
num=int(input("Enter a number of whose fa print("Invalid")

www.studymaterialz.in 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
number has been given as input. If an odd c) AssignmentError
number had been given as input, then there d) ValueError
would have been no output.
Answer: c
9. Identify the type of error in the following Explanation: NameError, IOError and
Python codes? ValueError are standard exceptions in Python
whereas Assignment error is not a standard
Print(“Good Morning”) exception in Python.
print(“Good night)
12. Syntax errors are also known as parsing
a) Syntax, Syntax
errors.
b) Semantic, Syntax
a) True
c) Semantic, Semantic
b) False
d) Syntax, Semantic
Answer: a
Answer: b Explanation: Syntax errors are known as
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
deviation from the rules of a language, a 13. An exception is ____________
syntax error is thrown. a) an object
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
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 is raised by a function signaling that an
a programming language, a semantic error is unexpected situation has occurred, that the
thrown function itself cannot handle.
d) If any exception is thrown in try block, else
block is executed 14. _______________________ exceptions
are raised as a result of an error in opening a
Answer: a particular file.
Explanation: When any exception is thrown a) ValueError
in try block, except block is executed. If b) TypeError
exception in not thrown in try block, else c) ImportError
block is executed. When there is a deviation d) IOError
from the rules of a programming language, a

www.studymaterialz.in 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
b) else b) Docstring
c) finally c) Interface
d) assert d) Modularity

Answer: c Answer: a
Explanation: The statements in the finally Explanation: Program code making use of a
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.

4. ______ is a string literal denoted by triple


TOPIC 5.3 MODULES AND quotes for providing the specifications of
PACKAGES certain program elements.
a) Interface
1. Which of these definitions correctly b) Modularity
describes a module? c) Client
a) Denoted by triple quotes for providing the d) Docstring
specification of certain program elements
b) Design and implementation of specific Answer: d
functionality to be incorporated into a Explanation: Docstring used for providing
program the specifications of program elements.
c) Defines the specification of how it is to be
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
Answer: b addressed before the overall design
Explanation: The term “module” refers to the b) Only the details of the program are
implementation of specific functionality to be addressed
incorporated into a program. c) The overall design of the program is
addressed before the details
2. Which of the following is not an advantage d) Only the design of the program is
of using modules? addressed
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks Answer: c
c) Provides a means of reducing the size of Explanation: Top-down design is an
the program approach for deriving a modular design in
d) Provides a means of testing individual which the overall design.
parts of the program

www.studymaterialz.in 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
modules
7. All modular designs are because of a top- c) Special name given to main modules is:
down design process. __main__
a) True d) Other main modules can import main
b) False modules
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.
Hence, all modular designs are not because of
a top-down design process. 10. Which of the following is not a valid
namespace?
8. What will be the output of the following a) Global namespace
Python code? b) Public namespace
c) Built-in namespace
#mod1 d) Local namespace
def change(a):
b=[x*2 for x in a]
print(b) Answer: b
#mod2 Explanation: During a Python program
def change(a): execution, there are as many as three
b=[x*x for x in a] namespaces – built-in namespace, global
print(b)
namespace and local namespace.
from mod1 import change
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
becomes part of importing module
a) [2,4,6] b) This form of import prevents name clash
b) [1,4,9] c) The namespace of imported module
c) becomes available to importing module
d) The identifiers in module are accessed as:
[2,4,6]
modulename.identifier
[1,4,9]
Answer: a
d) There is a name clash Explanation: In the “import modulename”
form of import, the namespace of imported
Answer: d module becomes available to, but not part of,
Explanation: A name clash is when two the importing module.
different entities with the same identifier

www.studymaterialz.in 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
Answer: d
Answer: b
Explanation: In the “from-import” form of
Explanation: In the “from-import” form of
import, the imported identifiers (in this case
import, there may be name clashes because
factorial()) aren’t specified along with the
names of the imported identifiers aren’t
module name.
specified along with the module name.
15. What is the order of namespaces in which
13. Which of the statements about modules is
Python looks for an identifier?
false?
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
in namespace
are private and aren’t imported
b) Python first searches the local namespace,
b) dir() built-in function monitors the items in
then the global namespace and finally the
the namespace of the main module
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
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
is automatically produced
finally the global namespace
Answer: c
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.
14. What will be the output of the following
Python code?

www.studymaterialz.in 135

Potrebbero piacerti anche