Python Control Flow: Loops 3 — Questions and Answers
Question 1: What does `enumerate(['a', 'b', 'c'])` yield when iterated?
- ('a', 0), ('b', 1), ('c', 2)
- (0, 'a'), (1, 'b'), (2, 'c') (Correct answer)
- ['a', 'b', 'c'] with indices
- A dictionary {0:'a', 1:'b', 2:'c'}
Correct answer: (0, 'a'), (1, 'b'), (2, 'c')
`enumerate()` yields `(index, value)` tuples starting from index 0 by default.
Question 2: Which statement about nested loops is true?
- `break` in the inner loop also exits the outer loop
- `break` in the inner loop only exits the inner loop (Correct answer)
- Python limits nesting to 3 levels
- `continue` in the inner loop restarts the outer loop
Correct answer: `break` in the inner loop only exits the inner loop
`break` only exits the innermost loop containing it; the outer loop continues normally.
Question 3: What is the result of `sum(i for i in range(5))`?
- 5
- 10 (Correct answer)
- 15
- 4
Correct answer: 10
`range(5)` is 0+1+2+3+4 = 10.
Question 4: How do you iterate over both keys and values of a dictionary `d` simultaneously?
- `for k, v in d:`
- `for k, v in d.items():` (Correct answer)
- `for k, v in d.keys():`
- `for k, v in zip(d):`
Correct answer: `for k, v in d.items():`
`d.items()` returns key-value pairs as tuples, which can be unpacked in the loop header.
Question 5: What is the output of: `i = 0 while True: i += 1 if i == 3: break print(i)`?
- 2
- 3 (Correct answer)
- 4
- Infinite loop
Correct answer: 3
The loop breaks when `i` becomes 3, so `print(i)` outputs 3.
Question 6: 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 the loop
Correct answer: Does nothing — acts as a placeholder
`pass` is a no-op statement used as a syntactic placeholder when a statement is required but no action is needed.
Question 7: What is the output of: ``` for i in range(4): if i == 2: continue print(i, end=' ') ```
- 0 1 2 3
- 0 1 3 (Correct answer)
- 1 2 3
- 0 1
Correct answer: 0 1 3
`continue` skips the `print` when `i == 2`, so 2 is not printed.
What does `enumerate(['a', 'b', 'c'])` yield when iterated?