Python Control Flow: Loops 5 — Questions and Answers
Question 1: What is the output of: ``` for i in range(1, 6): if i % 2 == 0: continue print(i, end=' ') ```
- 1 3 5 (Correct answer)
- 2 4
- 1 2 3 4 5
- 1 3 5 7
Correct answer: 1 3 5
`continue` skips even numbers, so only odd numbers 1, 3, 5 are printed.
Question 2: What is the `_` variable commonly used for in a `for` loop like `for _ in range(5)`?
- It signals a private variable
- It indicates the loop variable is intentionally unused (Correct answer)
- It stores the last loop value persistently
- It's required syntax for `range()` loops
Correct answer: It indicates the loop variable is intentionally unused
By convention, `_` is used when the loop variable value is not needed in the loop body.
Question 3: What does `iter()` return when called on a list?
- A copy of the list
- A list iterator object (Correct answer)
- A generator expression
- The first element of the list
Correct answer: A list iterator object
`iter(list)` returns a list iterator that produces elements one at a time via `next()`.
Question 4: What is the output of: ``` result = [x for x in range(10) if x % 3 == 0] print(result) ```
- [0, 3, 6, 9] (Correct answer)
- [3, 6, 9]
- [0, 3, 6]
- [1, 4, 7]
Correct answer: [0, 3, 6, 9]
Numbers from 0-9 divisible by 3 are 0, 3, 6, 9.
Question 5: In a `for` loop, what happens to the loop variable after the loop completes?
- It is deleted automatically
- It retains the last value it was assigned (Correct answer)
- It is reset to its initial value
- It becomes `None`
Correct answer: It retains the last value it was assigned
Python does not delete the loop variable after a `for` loop; it holds the last value from the iteration.
Question 6: Which is the correct way to loop through a string character by character?
- `for char in 'hello'.split():`
- `for char in list('hello'):`
- `for char in 'hello':`
- Both B and C (Correct answer)
Correct answer: Both B and C
Both `for char in 'hello':` and `for char in list('hello'):` iterate character by character.
Question 7: What does `while not done:` do if `done = False`?
- Raises a TypeError
- Never executes the loop body
- Executes the loop body (since `not False` is `True`) (Correct answer)
- Exits immediately
Correct answer: Executes the loop body (since `not False` is `True`)
`not False` evaluates to `True`, so the `while` condition is satisfied and the loop body runs.
What is the output of:
```
for i in range(1, 6):
if i % 2 == 0:
continue
print(i, end=' ')
```