Control Flow: Conditional Blocks and Loops
What this domain covers
Control flow is the largest PCEP domain. You must trace if/elif/else, while, for over range(), and break/continue, including nested and loop-else constructs.
Core rules
- Only the first true branch of an
if/elifchain runs. Conditions are tested top to bottom;elseis optional. range(stop)starts at 0;range(start, stop, step)excludesstop. Negative steps count down:list(range(5, 0, -2)) == [5, 3, 1].whilechecks its condition before every iteration; if initially false, the body never runs.breakexits the nearest loop immediately.continueskips to the next iteration.- A loop's
elseruns only when the loop ends normally, that is, withoutbreak. passis a no-op placeholder. The conditional expressiona if cond else bis an expression, not a statement.
Worked example
for i in range(1, 4): if i == 2: continue; print(i) prints 1 then 3. range(1, 4) yields 1, 2, 3; when i is 2, continue jumps to the next value, so print is skipped only for 2. Replacing continue with break would print only 1, because the loop would terminate at i == 2.
Traps
while x > 0:with no change toxinside creates an infinite loop.- Indentation defines blocks; a wrongly indented
printmay sit outside the loop. for i in range(3):finishes withi == 2; the loop variable persists afterwards.if x = 1:is invalid. Chained comparisons like0 < x < 10mean0 < x and x < 10.- Appending to a list while iterating over it can skip elements.