Our Features

Our Features
.

Sunday, 5 June 2016

Python Questions and Answers – While and For Loops – 2

This set of Advanced Python Questions & Answers focuses on “While and For Loops”.
1. What is the output of the following?
i = 0
while i < 5:
    print(i)
    i += 1
    if i == 3:
        break
else:
    print(0)
a) 0 1 2 0
b) 0 1 2
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: The else part is not executed if control breaks out of the loop.
2. What is the output of the following?
i = 0
while i < 3:
    print(i)
    i += 1
else:
    print(0)
a) 0 1 2 3 0
b) 0 1 2 0
c) 0 1 2
c) error
View Answer
Answer: b
Explanation: The else part is executed when the condition in the while statement is false.
3. What is the output of the following?
x = "abcdef"
while i in x:
    print(i, end=" ")
a) a b c d e f
b) abcdef
c) i i i i i i …
d) error
View Answer
Answer: d
Explanation: NameError, i is not defined.
4. What is the output of the following?
x = "abcdef"
i = "i"
while i in x:
    print(i, end=" ")
a) no output
b) i i i i i i …
c) a b c d e f
d) abcdef
View Answer
Answer: a Explanation: “i” is not in “abcdef”.

No comments:

Post a Comment