Python Questions and Answers Part-10

1. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
print('i', end = " ")
a) no output
b) i i i i i i …
c) a a a a a a …
d) a b c d e f

Answer: b
Explanation: Here i i i i i … printed continuously because as the value of i or x isn’t changing, the condition will always evaluate to True. But also here we use a citation marks on “i”, so, here i treated as a string, not like a variable.

2. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[:-1]
print(i, end = " ")
a) i i i i i i
b) a a a a a a
c) a a a a a
d) none of the mentioned

Answer: b
Explanation: The string x is being shortened by one character in each iteration.

3. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x[:-1]:
print(i, end = " ")
a) a a a a a
b) a a a a a a
c) a a a a a a …
d) a

Answer: c
Explanation: String x is not being altered and i is in x[:-1].

4. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
x = x[1:]
print(i, end = " ")
a) a a a a a a
b) a
c) no output
d) error

Answer: b
Explanation: The string x is being shortened by one character in each iteration.

5. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x[1:]:
print(i, end = " ")
a) a a a a a a
b) a
c) no output
d) error

Answer: c
Explanation: i is not in x[1:].

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

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

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

Answer: b
Explanation: range(int(2.0)) is the same as range(2).

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

Answer: d
Explanation: Error, objects of type float cannot be interpreted as an integer.

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

Answer: d
Explanation: OverflowError, cannot convert float infinity to integer.

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

Answer: b
Explanation: [::-1] reverses the list.