PCEP Controlling loop execution 3 — Questions and Answers
Question 1: What is the output of: ```python for i in range(4): if i % 2 == 0: continue print(i) ```
- 0 2
- 1 3 (Correct answer)
- 0 1 2 3
- 2 4
Correct answer: 1 3
`continue` skips even numbers, so only odd values 1 and 3 are printed.
Question 2: Which scenario would cause a `while` loop's `else` block to NOT execute?
- The loop condition starts as False
- The loop runs exactly once
- A `break` statement exits the loop (Correct answer)
- The loop variable is modified inside the body
Correct answer: A `break` statement exits the loop
The `else` block is skipped only when a `break` statement terminates the loop early.
Question 3: What does `pass` do when used inside a loop body?
- Skips to the next iteration
- Exits the loop
- Does nothing; acts as a placeholder (Correct answer)
- Pauses execution temporarily
Correct answer: Does nothing; acts as a placeholder
`pass` is a no-op statement used as a syntactic placeholder where a statement is required.
Question 4: What is printed by this code? ```python for i in range(3): for j in range(3): if j == 1: break print(i, j) ```
- 0 0 1 0 2 0
- 0 1 1 1 2 1 (Correct answer)
- 0 2 1 2 2 2
- Nothing is printed
Correct answer: 0 1 1 1 2 1
The inner loop breaks when j==1, so j is 1 at that point; the outer loop prints i and j for each i.
Question 5: In Python, can `break` be used outside of a loop?
- Yes, it exits the current function
- Yes, it stops the script
- No, it causes a SyntaxError (Correct answer)
- No, it raises a RuntimeError
Correct answer: No, it causes a SyntaxError
Using `break` outside a loop results in a SyntaxError because it has no loop to break out of.
Question 6: What is the output of: ```python i = 0 while i < 5: i += 1 if i == 3: continue if i == 4: break print(i) ```
- 3
- 4 (Correct answer)
- 5
- 2
Correct answer: 4
When i reaches 4, `break` fires before the print, then `print(i)` outside the loop prints 4.
Question 7: Which statement correctly describes the behavior of `for i in range(0):`?
- It raises a ValueError
- The loop body executes once with i=0
- The loop body never executes (Correct answer)
- It causes an infinite loop
Correct answer: The loop body never executes
`range(0)` produces an empty sequence, so the loop body executes zero times.
What is the output of:
```python
for i in range(4):
if i % 2 == 0:
continue
print(i)
```