Control flow
Conditions, loops, and comprehensions
Conditions
if, elif, and else select the first matching branch. Indentation defines each block. Comparisons produce booleans; and, or, and not combine conditions.
Empty collections, zero, and None are falsey. Use an explicit is None check when zero or an empty value is valid. and and or short-circuit and return an operand, so configured_limit or 10 replaces a legitimate zero.
Loops
forconsumes an iterable.range(4)supplies integers 0–3;enumeratesupplies positions and values.whilerepeats while its condition holds. Each iteration needs a path toward termination.continueskips the remaining loop body;breakexits the innermost loop;returnexits the entire function.- A comprehension suits a compact transformation or filter. Use a loop for multiple steps, early exits, or side effects.
A loop's else runs on normal exhaustion, including an empty input, but not after break:
states = ["retry", "retry", "ready"]
for attempt, state in enumerate(states, start=1):
if state == "ready":
print(f"accepted on attempt {attempt}") # accepted on attempt 3
break
else:
print("no ready state")
print("inspection complete")The else belongs to for, not the inner if. An exception or return also bypasses it. Use this form when the distinction between a match and exhaustion is clear.
Pairing inputs
zip stops at the shortest input. zip(..., strict=True) raises ValueError if lengths differ, but checks as iteration proceeds:
names = ["east", "west"]
limits = [8]
accepted = []
try:
for name, limit in zip(names, limits, strict=True):
accepted.append((name, limit))
except ValueError:
print("length mismatch")
print(accepted) # [('east', 8)]The first pair was processed before the mismatch was detected. If partial updates are forbidden, stage results before committing or check the lengths of reusable inputs first. Checking an arbitrary stream may require buffering.
Gotchas
- Removing items from the list being traversed can skip entries. Build a new result or traverse a snapshot.
- A return inside a loop stops after that item; it does not skip to the next one.
- Nested loops can do quadratic work despite little code. Check empty inputs, late matches, and what remains true after each iteration.
Fill the supplied function bodies without changing their signatures; return results rather than printing them.
Put it into practice
Implement the exercise in a full-screen workspace, then run its tests.