PCEP Controlling loop execution 2 — Questions and Answers
Question 1: What happens when a `break` statement is encountered inside a nested `for` loop?
- It exits all loops immediately
- It exits only the innermost loop (Correct answer)
- It skips to the next iteration of the outer loop
- It raises a SyntaxError
Correct answer: It exits only the innermost loop
`break` only terminates the innermost loop in which it appears, not any enclosing loops.
Question 2: What is the output of this code? ```python for i in range(5): if i == 3: continue print(i, end=' ') ```
- 0 1 2 3 4
- 0 1 2 4 (Correct answer)
- 1 2 4 5
- 0 1 2
Correct answer: 0 1 2 4
`continue` skips the iteration where `i == 3`, so 3 is not printed.
Question 3: Which of the following correctly uses `break` inside a `while` loop?
- while True: break()
- while True: break (Correct answer)
- while True: stop break
- while True: exit loop
Correct answer: while True: break
`break` is a statement used alone without parentheses or additional keywords.
Question 4: What does the `else` clause of a `for` loop execute?
- Only when the loop body raises an exception
- Only when the loop completes without hitting a `break` (Correct answer)
- Only when the loop iterates zero times
- Every time the loop condition is checked
Correct answer: Only when the loop completes without hitting a `break`
The `else` clause runs after the loop finishes normally, but is skipped if a `break` exits the loop.
Question 5: What is the output of: ```python for i in range(3): pass print(i) ```
- 0
- 2 (Correct answer)
- 3
- NameError
Correct answer: 2
The loop variable `i` retains its last value after the loop ends, which is 2 for `range(3)`.
Question 6: How does `continue` differ from `break` inside a loop?
- `continue` exits the loop; `break` skips to the next iteration
- `continue` skips to the next iteration; `break` exits the loop (Correct answer)
- Both exit the loop immediately
- Both skip to the next iteration
Correct answer: `continue` skips to the next iteration; `break` exits the loop
`continue` moves to the next iteration while `break` terminates the entire loop.
Question 7: What is the result of this code? ```python x = 10 while x > 0: x -= 3 if x == 4: break print(x) ```
- 4 (Correct answer)
- 1
- 7
- -2
Correct answer: 4
x goes 10→7→4, at which point the `break` fires and the loop exits with x == 4.
What happens when a `break` statement is encountered inside a nested `for` loop?