Skip to Content

Control Flow & Loops

When to use

Branch on a condition or repeat an action.

Analogy

if/elif/else is a fork in the road; for/while is a conveyor belt.

Data-flow diagram

if cond: --True--> branch A
          --else--> branch B

for x in seq:
    body; break / continue
else:    # runs ONLY if no break fired

Deep explanation

Whitespace-significant. Comprehensions beat for+append (faster in C). The walrus := (PEP 572) assigns inside an expression to avoid duplicate work. The rarely-used for/else runs only on a clean exit - perfect for search loops.

Examples

Example 1

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n,'=',x,'*',n//x); break
    else:                      # no break
        print(n,'is prime')

rare for/else - else runs only when loop completes WITHOUT break.

Example 2

while (line := input('> ')) != 'quit':
    print(f'echo: {line}')

walrus := assigns and checks in one expression.

Example 3

matches = [m for m in items if m.score >= 90]
print(matches or 'no high scorer')

list comprehension is idiomatic; or provides a default if empty.

Common mistake

Mutating a list while iterating it directly (for x in lst: lst.remove(x)) silently skips elements. Iterate over lst[:] or build a fresh list.

Key takeaway

Use comprehensions; for/else for ‘not found’; walrus only when it removes a duplicate expression.

Production Failure Playbook

Failure scenario 1: mutable-iteration-bug

Failure scenario 2: infinite-while-loop