Python Control Flow: Loops 2 — Questions and Answers
Question 1: What does the `else` clause of a `for` loop execute?
- Only if the loop body raised an exception
- Only if the loop completed without a `break` (Correct answer)
- Only if the loop ran zero iterations
- Only if the loop ran at least one iteration
Correct answer: Only if the loop completed without a `break`
The `else` clause runs after the loop finishes normally (without hitting a `break` statement).
Question 2: What is the output of: `for i in range(3): print(i, end=' ')`?
- 1 2 3
- 0 1 2 3
- 0 1 2 (Correct answer)
- 1 2
Correct answer: 0 1 2
`range(3)` generates 0, 1, 2 — it stops before 3.
Question 3: Which loop construct is most appropriate when the number of iterations is unknown ahead of time?
- `for` loop with `range()`
- `for` loop with `enumerate()`
- `while` loop (Correct answer)
- `for` loop with `zip()`
Correct answer: `while` loop
A `while` loop continues as long as a condition is true, making it ideal when iteration count is unknown.
Question 4: What happens if the condition of a `while` loop is never `False`?
- Python raises a `RuntimeError`
- The loop exits after 1000 iterations
- The loop runs indefinitely (infinite loop) (Correct answer)
- The `else` block executes immediately
Correct answer: The loop runs indefinitely (infinite loop)
If the condition never becomes `False` and there's no `break`, the `while` loop runs forever.
Question 5: What does `continue` do inside a loop?
- Exits the loop immediately
- Skips the rest of the current iteration and moves to the next (Correct answer)
- Restarts the loop from the beginning
- Pauses execution until a condition is met
Correct answer: Skips the rest of the current iteration and moves to the next
`continue` skips the remaining statements in the current loop body and proceeds to the next iteration.
Question 6: Given `x = 0`, what does `while x < 5: x += 2` leave `x` as after the loop?
- 4
- 5
- 6 (Correct answer)
- 2
Correct answer: 6
x goes 0→2→4→6; when x=6, the condition 6<5 is False, so the loop ends with x=6.
Question 7: What is the output of: `for i in range(10, 0, -3): print(i, end=' ')`?
- 10 7 4 1 (Correct answer)
- 10 7 4
- 9 6 3
- 10 8 6 4 2
Correct answer: 10 7 4 1
`range(10, 0, -3)` yields 10, 7, 4, 1 — stepping by -3 and stopping before reaching 0.
What does the `else` clause of a `for` loop execute?