Test Series - python

Test Number 22/108

Q: What will be the output of the following Python code?

for i in range(10):
    if i == 5:
        break
    else:
        print(i)
else:
    print("Here")
A. 0 1 2 3 4 Here
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. 1 2 3 4 5
Solution: The else part is executed if control doesn’t break out of the loop.
Q: What will be the output of the following Python code?

for i in range(5):
    if i == 5:
        break
    else:
        print(i)
else:
    print("Here")
A. 0 1 2 3 4 Here
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. none of the mentioned
Solution: The else part is executed if control doesn’t break out of the loop.
Q: What will be the output of the following Python code?

x = (i for i in range(3))
for i in x:
    print(i)
A. 0 1 2
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. none of the mentioned
Solution: The first statement creates a generator object.
Q: What will be the output of the following Python code?

x = (i for i in range(3))
for i in x:
    print(i)
for i in x:
    print(i)
A. 0 1 2
B. 0 1 2 3 4 5 Here
C. 0 1 2 3 4
D. none of the mentioned
Solution: We can loop over a generator object only once.
Q: What will be the output of the following Python code?

string = "my name is x"
for i in string:
    print (i, end=", ")
A. m, y, , n, a, m, e, , i, s, , x,
B. m, y, , n, a, m, e, , i, s, , x
C. my, name, is, x,
D. error
Solution: Variable i takes the value of one character at a time.
Q: What will be the output of the following Python code?

string = "my name is x"
for i in string.split():
    print (i, end=", ")
A. m, y, , n, a, m, e, , i, s, , x,
B. m, y, , n, a, m, e, , i, s, , x
C. my, name, is, x,
D. error
Solution: Variable i takes the value of one word at a time.
Q: What will be the output of the following Python code snippet?

a = [0, 1, 2, 3]
for a[-1] in a:
    print(a[-1])
A. 0 1 2 3
B. 0 1 2 2
C. 3 3 3 3
D. error
Solution: The value of a[-1] changes in each iteration.
Q: What will be the output of the following Python code snippet?

a = [0, 1, 2, 3]
for a[0] in a:
    print(a[0])
A. 0 1 2 3
B. 0 1 2 2
C. 3 3 3 3
D. error
Solution: The value of a[0] changes in each iteration. Since the first value that it takes is itself, there is no visible error in the current example.
Q: What will be the output of the following Python code snippet?

a = [0, 1, 2, 3]
i = -2
for i not in a:
    print(i)
    i += 1
A. -2 -1
B. 0
C. error
D. none of the mentioned
Solution: SyntaxError, not in isn’t allowed in for loops.
Q: What will be the output of the following Python code snippet?

string = "my name is x"
for i in .join(string.split()):
    print (i, end=", ")
A. m, y, , n, a, m, e, , i, s, , x,
B. m, y, , n, a, m, e, , i, s, , x
C. my, name, is, x,
D. error
Solution: Variable i takes the value of one character at a time.

You Have Score    /10