Chapter 03

Control Flow

Python's loop else clause confuses everyone. Modifying a list while iterating crashes silently. range() is lazy. Let's find your gaps.

Questions: 18
Format: Predict Output + Multiple Choice
Difficulty: ★★★☆☆
The big idea of this chapter: Python's for and while loops have an else clause that runs only when the loop completes normally (without break). This is unique to Python and deeply useful — and deeply confusing the first time you see it.
for / while loops
Q 01Predict the Output
for i in range(3):
    print(i)
else:
    print("done")
Output
0 1 2 done
Why? In Python, for loops can have an else clause. It executes when the loop completes normally — i.e., it is NOT skipped by a break. Here the loop runs fully, so "done" prints. The else is misleadingly named — think of it as "no-break" instead.
Q 02Predict the Output
for i in range(5):
    if i == 3:
        break
else:
    print("no break")
print("after loop")
Output
after loop
Why? The break at i==3 exits the loop early, which skips the else clause entirely. So "no break" never prints. Only "after loop" prints (it's outside the loop). This is the primary use case for loop-else: searching for items — if found, break; the else means "item not found."
Q 03Multiple Choice
for i in range(0):   # empty range
    print(i)
else:
    print("else ran")
Answer: b) "else ran".

Even with an empty range, the loop "completes normally" (it never executed any iteration, and there was no break). So the else clause runs. This surprises many people — an empty loop body still triggers the else.
Q 04Predict the Output
i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("while done")
Output
0 1 2 while done
Why? while loops also support an else clause. It runs when the while condition becomes False naturally — not when a break exits the loop. Here, i reaches 3, condition fails, and the else runs.
Q 05Predict the Output
for i in range(5):
    if i == 3:
        continue
    print(i)
Output
0 1 2 4
Why? continue skips the rest of the current iteration and moves to the next. When i == 3, the print(i) is skipped. Unlike break, continue does NOT exit the loop — it just moves to the next value.
range() Behavior
Q 06Multiple Choice
r = range(10)
print(type(r))
print(r[5])
print(len(r))
Answer: b) range, 5, 10.

range() returns a range object — a lazy sequence. It does NOT store all values in memory. Despite this, it supports indexing (r[5]) and len() because range knows its start, stop, and step. This is more efficient than a list for large ranges.
Q 07Predict the Output
print(list(range(1, 10, 3)))
print(list(range(10, 0, -2)))
print(list(range(5, 5)))   # start == stop
Output
[1, 4, 7] [10, 8, 6, 4, 2] []
Why? range(start, stop, step): generates values from start up to (but not including) stop, stepping by step. With a negative step, it counts down. When start equals stop, the range is empty — no error, just an empty sequence.
Q 08Multiple Choice
for i in range(3):
    print(i)
print(i)   # after the loop
Answer: b) 0 1 2, then 2.

In Python, the loop variable i is NOT scoped to the loop — it leaks into the enclosing scope and retains its last value after the loop ends. So after the loop, i == 2. This is different from C/Java where loop variables are scoped to the loop block.
Mutation During Iteration
Q 09Multiple Choice
nums = [1, 2, 3, 4, 5]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
The correct output is [1, 3, 5] — but for tricky reasons.

Actually run this and you'll find [1, 3, 5] in this specific case — but the approach is dangerously wrong in general. When you remove element at index 1 (value 2), element 3 slides to index 1. The iterator then moves to index 2, skipping 3. For even numbers in sequence, this "accidentally" works, but it will silently skip elements in many other cases.

Safe approach: [x for x in nums if x % 2 != 0] — always iterate over a copy or use a comprehension.
Q 10Predict the Output
nums = [1, 2, 3, 4]
for n in nums[:]   # iterate over a copy:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
Output
[1, 3]
Why? nums[:] creates a full copy of the list. The loop iterates over the copy while nums.remove(n) modifies the original. This is safe and correct — all even numbers are removed. This is the standard idiom for mutating a list while iterating: iterate over a copy.
Ternary Expression
Q 11Predict the Output
x = 10
result = "big" if x > 5 else "small"
print(result)

y = 3
print("odd" if y % 2 else "even")
Output
big odd
Why? Python's ternary expression syntax is: value_if_true if condition else value_if_false. Note the condition is in the middle — the opposite of C's condition ? true : false. y % 2 = 1 when odd, which is truthy, so "odd" is returned.
Q 12Multiple Choice
x = 5
y = 10 if x > 3 else 20 if x > 1 else 30
print(y)
Answer: a) 10.

Nested ternary evaluates left to right: 10 if (x > 3) else (20 if x > 1 else 30). Since x = 5 > 3 is True, the first condition wins and y = 10. The rest is not evaluated. Nested ternaries are valid Python but hard to read — use if/elif for clarity.
Comprehensions
Q 13Predict the Output
result = [x * 2 for x in range(5) if x % 2 == 0]
print(result)
Output
[0, 4, 8]
Why? The comprehension filters first (if x % 2 == 0 keeps 0, 2, 4), then applies the expression (x * 2 → 0, 4, 8). The order in the comprehension is: expression, for, if — but evaluation order is: for, if (filter), then expression.
Q 14Multiple Choice
x = 10
result = [x for x in range(3)]
print(x)   # what is x after the comprehension?
Answer: a) 10.

In Python 3, list comprehensions have their own scope — the loop variable x inside the comprehension does NOT leak into the surrounding scope. So the outer x = 10 is unchanged. This is different from a regular for loop, where the variable leaks. In Python 2, comprehensions leaked — Python 3 fixed this.
pass, break, continue
Q 15Predict the Output
for i in range(3):
    pass
print("done", i)
Output
done 2
Why? pass is a no-op — it does nothing and allows the loop body to be syntactically non-empty. The loop still runs all 3 iterations. After the loop, i is 2 (loop variable leaks from regular for loops).
Q 16Predict the Output
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)
Output
0 0 1 0 2 0
Why? break only exits the innermost loop. The outer loop continues normally. For each value of i, the inner loop prints j=0 then breaks at j=1. Python has no labeled break (like Java's break label) — to break multiple loops, use a function and return, or a flag variable.
Q 17Multiple Choice
for i in [1, 2, 3]:
    if i == 2:
        continue
    print(i)
else:
    print("else")
Answer: a) 1, 3, else.

continue does NOT trigger the else to skip — only break does. continue just skips the current iteration. The loop still completes normally (all items are visited), so the else runs. Output: 1, then 2 is skipped, then 3, then "else".
Q 18Predict the Output
items = ["a", "b", "c"]
for i, v in enumerate(items, start=1):
    print(i, v)
Output
1 a 2 b 3 c
Why? enumerate(iterable, start=N) yields (index, value) pairs. The start parameter sets the starting index (default is 0). Here, start=1 makes the count start from 1 — great for human-readable numbered lists. Tuple unpacking for i, v in ... assigns each pair to two variables.
← Chapter 02: Operators Chapter 04: Functions & Scope →