Python MCQs
1. What will be the output of the following Python code?
for i in range(2.0): print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Object of type float cannot be interpreted as an integer.
2. What will be the output of the following Python code?
for i in range(int(2.0)): print(i)
a) 0.0 1.0
b) 0 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: range(int(2.0)) is the same as range(2).
3. What will be the output of the following Python code?
for i in range(float('inf')): print (i)
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
d) none of the mentioned
View Answer
Answer: d
Explanation: Error, objects of type float cannot be interpreted as an integer.
4. What will be the output of the following Python code?
for i in range(int(float('inf'))): print (i)
a) 0.0 0.1 0.2 0.3 …
b) 0 1 2 3 …
c) 0.0 1.0 2.0 3.0 …
d) none of the mentioned
View Answer
Answer: d
Explanation: OverflowError, cannot convert float infinity to integer.
5. What will be the output of the following Python code snippet?
for i in [1, 2, 3, 4][::-1]: print (i)
a) 1 2 3 4
b) 4 3 2 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: [::-1] reverses the list.
6. What will be the output of the following Python code snippet?
for i in ''.join(reversed(list('abcd'))): print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: ‘ ‘.join(reversed(list(‘abcd’))) reverses a string.
7. What will be the output of the following Python code snippet?
for i in 'abcd'[::-1]: print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: [::-1] reverses the string.
8. What will be the output of the following Python code snippet?
for i in '': print (i)
a) None
b) (nothing is printed)
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: The string does not have any character to loop over.
9. What will be the output of the following Python code snippet?
x = 2 for i in range(x): x += 1 print (x)
a) 0 1 2 3 4 …
b) 0 1
c) 3 4
d) 0 1 2 3
View Answer
Answer: c
Explanation: Variable x is incremented and printed twice.
10. What will be the output of the following Python code snippet?
x = 2 for i in range(x): x -= 2 print (x)
a) 0 1 2 3 4 …
b) 0 -2
c) 0
d) error
View Answer
Answer: b
Explanation: The loop is entered twice.