03 / 22 · Getting Started
Control flow
How a Python program chooses and repeats: if, elif and else with the truth test every object answers, while and for loops, break, continue and the else clause of a loop, the match statement with its patterns, and the difference between expressions and statements.
On this page 9
The previous note described what a program works on: objects, and the names bound to them. Every program so far ran each of its lines exactly once, from top to bottom. That is enough for a calculator and for nothing else. A program has to choose between actions depending on the data, repeat an action for every item it is given, and stop when it has found what it needs. This note covers the statements that do that, if, while, for and match, and the rule behind each: the question that the statement asks of the object it is given.
Baseline: straight-line code#
A program without control flow does the same thing whatever its input. To print whether a temperature is hot, mild or cold, it would have to print all three or none. To add up a list it would need one line per element, and a different program for each length. Control flow statements make the path through the code depend on values computed at run time.
Choosing a branch: if, elif, else#
The rule. if evaluates its condition. If the result counts as true, it runs the indented block under it and skips the rest of the statement. Otherwise it tries each elif condition in turn, and if none counts as true, runs the else block, if there is one. At most one block runs.
>>> temperature = 31
>>> if temperature > 30:
... print("hot")
... elif temperature > 15:
... print("mild")
... else:
... print("cold")
...
hot
temperature > 30 is true, so hot is printed. The elif condition temperature > 15 is also true, but it is never evaluated: the first true branch ends the statement. Order the branches from the most specific to the least.
Blocks are made by indentation. Python has no braces around blocks. A line ending in : opens a block, and the block is every following line indented more than that line; the block ends at the first line indented back. Four spaces per level is the convention (PEP 8). Indentation is part of the syntax, so a mistake in it is a compile-time error, reported before anything runs:
$ python ind.py
File ".../ind.py", line 2
print("indented?")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 1
Comparisons chain. 0 < x < 10 means 0 < x and x < 10, with x evaluated once. Any comparison operators can be chained this way, which also makes 1 < 3 > 2 legal and true, if unclear.
What counts as true#
if does not need a bool. Its condition can be any object, and Python asks the object whether it counts as true.
The rule (truth testing). An object is false if it is None or False, a zero of any numeric type (0, 0.0), or an empty collection ("", [], (), {}, set(), range(0)). Every other object of the built-in types is true (Python documentation, truth value testing). For objects of other types, Python calls the type’s __bool__ method if it has one, otherwise __len__, and counts a length of zero as false; an object with neither is true. bool(x) applies the same test and returns True or False.
>>> [bool(v) for v in (None, False, 0, 0.0, "", [], (), {}, set(), range(0))]
[False, False, False, False, False, False, False, False, False, False]
>>> [bool(v) for v in (1, -0.5, "False", [0], (None,), {"a": 1})]
[True, True, True, True, True, True]
The string "False" is true because it is a non-empty string, and [0] is true because it is a list of length 1; its element does not matter. This is what lets if items: mean “if the list is not empty”, the idiomatic test.
Why it works this way. The compiler turns if x: into an instruction that converts x to a bool and a conditional jump. dis shows both:
>>> import dis
>>> def check(x):
... if x:
... return "yes"
... return "no"
...
>>> dis.dis(check)
1 RESUME 0
2 LOAD_FAST_BORROW 0 (x)
TO_BOOL
POP_JUMP_IF_FALSE 3 (to L1)
NOT_TAKEN
3 LOAD_CONST 0 ('yes')
RETURN_VALUE
4 L1: LOAD_CONST 1 ('no')
RETURN_VALUE
TO_BOOL performs the truth test, calling __bool__ or __len__ as needed, and POP_JUMP_IF_FALSE jumps to the label L1 when the result is false. An if is a jump over a block of bytecode. (NOT_TAKEN does nothing; it lets monitoring tools such as coverage see which way the branch went. CPython 3.11 compiles the same function without TO_BOOL and NOT_TAKEN, into a single conditional jump that tests the object directly.)
and, or, not return operands, not True and False. a or b evaluates a; if a is true it is the result, and b is never evaluated. Otherwise the result is b. a and b returns a if a is false, otherwise b. Only not always returns a bool. This short-circuit rule gives two idioms, a default value and a guard:
>>> name = ""
>>> name or "anonymous"
'anonymous'
>>> [] and 1 / 0
[]
The second line never divides: [] is false, so and returns it without evaluating 1 / 0.
The mistake. if x == 1 or 2: reads like English and is always true:
>>> x = 5
>>> x == 1 or 2
2
>>> x == 1 or x == 2
False
>>> x in (1, 2)
False
== binds more tightly than or, so the condition is (x == 1) or 2. The left side is False, so or returns 2, which is true. Write both comparisons, or use in.
Repeating while a condition holds: while#
The rule. while condition: evaluates the condition; if it counts as true it runs the block, then evaluates the condition again, and so on. The loop ends the first time the condition counts as false. The block must eventually change something the condition depends on.
>>> n = 5
>>> total = 0
>>> while n > 0:
... total += n
... n -= 1
...
>>> total, n
(15, 0)
The block ran five times, with n equal to 5, 4, 3, 2, 1; after the fifth pass n is 0, the condition is false, and the loop ends having added . If the line n -= 1 were missing, the condition would stay true forever. A loop that never ends is stopped with Ctrl-C, which raises KeyboardInterrupt in the running program.
while is the right loop when the number of passes is not known in advance: reading input until it ends, or iterating an algorithm until it converges. When there is a collection to go through, for is clearer.
Repeating over items: for#
The rule. for target in iterable: runs its block once for each item that the iterable produces, binding the name target to the item before each pass. An iterable is any object that can hand out its items one at a time: strings (their characters), lists and tuples (their elements), dictionaries (their keys), files (their lines), range objects (their numbers), and many more.
>>> for ch in "abc":
... print(ch)
...
a
b
c
>>> list(range(5)), list(range(1, 4)), list(range(10, 0, -4))
([0, 1, 2, 3, 4], [1, 2, 3], [10, 6, 2])
range(stop) produces ; range(start, stop, step) starts at start and moves by step while it has not reached stop. The stop value is never included, so range(n) has exactly n items, the valid indices of a list of length n. A range does not store its numbers; it computes each one when asked.
Three built-in helpers cover most needs: enumerate(items) gives pairs of an index and an item, zip(a, b) pairs items of two iterables position by position, and d.items() gives the key–value pairs of a dictionary. Each pair is unpacked into two names:
>>> for i, word in enumerate(["red", "green"]):
... print(i, word)
...
0 red
1 green
>>> for name, year in zip(["ada", "alan"], [1815, 1912]):
... print(name, year)
...
ada 1815
alan 1912
How for gets the items. The loop asks the object for an iterator once, with the built-in iter(), and then asks the iterator for the next item, with next(), before every pass. When there are no items left, next() raises the exception StopIteration, and the loop ends. You can make the same calls by hand:
>>> it = iter("ab")
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
Traceback (most recent call last):
...
StopIteration
An object that does not support iter() cannot be looped over, and the error says so: for x in 42: raises TypeError: 'int' object is not iterable. The iteration note states this iterator protocol in full and shows how to write iterables of your own; this note needs only the two calls.
The mistake. Changing a list while a for loop goes through it skips items, because the iterator walks by position:
>>> nums = [1, 2, 2, 3]
>>> for n in nums:
... if n == 2:
... nums.remove(n)
...
>>> nums
[1, 2, 3]
The first 2, at position 1, is removed; the second 2 moves into position 1, and the iterator continues at position 2, which now holds 3. One 2 survives. Build a new list instead, [n for n in nums if n != 2], which gives [1, 3], or loop over a copy, for n in nums[:]:.
Leaving early: break, continue and else#
The rules.
breakends the innermost loop at once. Execution continues after the loop, and the loop’selseblock, if any, is skipped.continueends the current pass. Awhileloop re-evaluates its condition; aforloop asks for the next item.- A loop may have an
elseblock. It runs when the loop ends normally, because the condition of awhilebecame false or the iterator of aforran out, and not when the loop was left bybreak. A loop that never runs its body still runs itselse.
How a for loop runs, with break, continue and else
iter()is called once and returns an iterator.- Before each pass,
next()asks for an item. - If there is one, the loop variable is bound to it and the body runs.
- When the body ends, or at
continue, the loop goes back to step 2. breakjumps past the end of the loop, skipping theelseblock.- When the items run out, the
elseblock runs. - Either way, execution continues with the statement after the loop.
The else clause is for searches: the loop looks for something and breaks when it finds it, and else handles “not found” without a flag variable.
>>> for n in (9, 15, 7, 21):
... if n % 2 == 0:
... print("found even", n)
... break
... else:
... print("no even number")
...
no even number
>>> for n in (9, 14, 7):
... if n % 2 == 0:
... print("found even", n)
... break
... else:
... print("no even number")
...
found even 14
In the first loop no item is even, the iterator runs out after 21, and else runs. In the second, 14 triggers break; 7 is never examined and else is skipped. A better name for the clause would have been nobreak; read it that way.
continue skips the rest of one pass:
>>> for n in range(6):
... if n % 3 == 0:
... continue
... print(n)
...
1
2
4
5
0 and 3 are multiples of 3, so for them continue jumps back to next() before print is reached.
Choosing by shape: match#
An if–elif chain compares values. Often a program needs to ask a different question: what shape is this data, a pair or a single item, a dictionary with a "type" key, a string of digits, and what are its parts? The match statement, added in Python 3.10 (PEP 634), does that.
The rule. match subject: evaluates the subject once and tries each case pattern from top to bottom. The first pattern that matches, and whose guard (an optional if condition after the pattern) is true, has its block run; the other cases are skipped. A pattern that matches can bind names to parts of the subject. If no case matches, nothing happens.
The kinds of patterns, all used in the two examples below:
| Pattern | Matches | Binds |
|---|---|---|
0, "quit", None (a literal) | an equal value (None, True, False by identity) | nothing |
x (a bare name, a capture) | anything | x to the subject |
_ (the wildcard) | anything | nothing |
(a, b) or [a, b] (a sequence) | a sequence of that length, not a string | each name to an element |
[first, *rest] | a sequence of length at least 1 | rest to a list of the remaining elements |
{"type": t} (a mapping) | a mapping that has those keys; extra keys are ignored | t to the value |
int(), str() as s (a class) | an instance of that type | with as, s to the subject |
"q" | "Q" (an OR pattern) | either alternative | the same names in every alternative |
Worked example: points. The subject is a pair of coordinates:
>>> def describe(point):
... match point:
... case (0, 0):
... return "origin"
... case (0, y):
... return f"on the y-axis at {y}"
... case (x, 0):
... return f"on the x-axis at {x}"
... case (x, y) if x == y:
... return f"on the diagonal at {x}"
... case (x, y):
... return f"at {x}, {y}"
... case _:
... return "not a point"
...
>>> describe((0, 0)), describe((0, 5)), describe((3, 0))
('origin', 'on the y-axis at 5', 'on the x-axis at 3')
>>> describe((2, 2)), describe([4, 1]), describe("hi")
('on the diagonal at 2', 'at 4, 1', 'not a point')
Line by line: (0, 0) matches only a two-element sequence whose elements equal 0 and 0. (0, 5) fails the first case and matches (0, y), binding y to 5. (2, 2) fails the first three and matches (x, y) with the guard x == y true. [4, 1] is a list, and a sequence pattern accepts any sequence, written with round or square brackets. "hi" is a sequence of two characters, but sequence patterns never match strings, so it falls through to _. (The f"..." strings insert values into text; the strings note explains them.)
Worked example: events as dictionaries. Data that arrives from outside a program, such as JSON messages, is often a dictionary whose keys say what it is:
>>> def handle(event):
... match event:
... case {"type": "click", "x": x, "y": y}:
... return f"click at {x}, {y}"
... case {"type": "key", "key": "q" | "Q"}:
... return "quit"
... case {"type": "key", "key": str() as k}:
... return f"key {k}"
... case {"type": "scroll", "lines": int(n)} if n < 0:
... return f"scroll up {-n}"
... case {"type": t}:
... return f"unknown event {t}"
...
>>> handle({"type": "click", "x": 3, "y": 4, "button": 1})
'click at 3, 4'
>>> handle({"type": "key", "key": "Q"})
'quit'
>>> handle({"type": "scroll", "lines": -2})
'scroll up 2'
>>> handle({"type": "scroll", "lines": 2})
'unknown event scroll'
>>> handle({"no": "type"}) is None
True
The click matches although it has an extra key, "button": mapping patterns check only the keys they name. int(n) checks that the value is an int and binds it to n, and the guard sends positive scrolls on to the last case. A dictionary without a "type" key matches no case, so handle reaches its end and returns None.
The mistake: a bare name always captures. A name in a pattern is never compared with an existing variable; it is bound to the subject. A case meant to compare with a constant RED matches everything instead, and the compiler refuses the statement when cases follow it:
$ python capture.py
File ".../capture.py", line 4
case RED:
^^^
SyntaxError: name capture 'RED' makes remaining patterns unreachable
To compare with a constant, use a literal (case "red":) or a dotted name (case Color.RED:), which the language treats as a value to compare with (PEP 636).
When to use match. When the cases differ in structure and the code needs the parts: parsed commands, messages, syntax trees. For a plain comparison of one value against a few constants, an if–elif chain or a dictionary lookup is as clear. Classes can take part in matching with their attributes, case Point(x=0); the classes note shows how.
Expressions against statements#
An expression is code that produces a value: 3, x + 1, len(items) > 0, f(x). A statement is code that does something and produces nothing: an assignment, if, for, def, import. An expression can appear wherever a value is needed, inside another expression or as an argument; a statement cannot. The REPL prints the value of an expression and nothing for a statement, which is how the first note told them apart.
if is a statement, so it cannot appear where a value is expected. The conditional expression is its expression form:
>>> n = 7
>>> "even" if n % 2 == 0 else "odd"
'odd'
a if condition else b evaluates the condition first, then only one of a and b. It suits a choice between two values; anything longer reads better as an if statement.
An assignment is a statement, so it cannot be nested in an expression, and the compiler says what was probably meant:
>>> y = (x = 5)
File "<python-input-0>", line 1
y = (x = 5)
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
The assignment expression name := value (since Python 3.8, PEP 572) binds a name and also produces the value, which avoids computing something twice:
>>> data = [3, 1, 4, 1, 5, 9, 2, 6]
>>> if (n := len(data)) > 5:
... print(f"long list: {n} items")
...
long list: 8 items
The machine-learning courses use all of this in plain form: for epoch in range(n_epochs): around a training loop, while until a change falls below a tolerance in gradient descent, conditional expressions for small choices, and break out of the epoch loop for early stopping, which ends training when the validation loss stops improving.
What changed#
| Straight-line code (the baseline) | With control flow | |
|---|---|---|
| Path through the code | every line once, in order | chosen at run time from the data |
| Choosing | impossible | if/elif/else on any object’s truth value; match on its shape |
| Repeating | one line per repetition | while a condition holds; for each item of an iterable |
| Stopping early | impossible | break; continue for one pass; loop else for “not found” |
| Values from choices | none | the conditional expression a if c else b |
Limitations#
- Iteration is only previewed. How
iter()andnext()work, and how to write an object that aforloop accepts, is in the iteration note, together with comprehensions and generators. - Exceptions change control flow too. An exception leaves every loop and function until something handles it;
tryandexceptare in the files and exceptions note. - Bytecode varies. The instructions shown by
disare CPython 3.14’s and differ between versions; the behaviour they implement is the language’s and does not change. matchhas more. Class patterns with keyword attributes,__match_args__, and value patterns on enumerations are left to the classes note and the tutorial PEP 636.
What you should remember#
ifruns at most one branch: the first whose condition counts as true. Blocks are defined by indentation.- Truth test:
None,False, zeros and empty collections are false; everything else is true unless its type defines__bool__or__len__otherwise.if items:tests for non-empty. andandorshort-circuit and return one of their operands.x == 1 or 2is always true.whilerepeats while a condition holds;forasks the iterable for an iterator once and for the next item before each pass, untilStopIteration.breakleaves the loop and skips itselse;continuegoes to the next pass; a loop’selsemeans “no break”.matchpicks the first case whose pattern fits the subject’s shape and binds its parts; a bare name in a pattern always captures.- Expressions produce values; statements do not.
a if c else band:=are the expression forms of a choice and an assignment.
Code#
The script runs every construct of the note on small inputs: the truth test of common objects, a while loop that counts Collatz steps, for with break and else for a divisor search, continue to filter lines, and match to parse commands by their shape. Run it with python -I flow.py; it uses only the standard library, and its output is the same on every platform.
"""Branches, loops and match, on small concrete inputs (Python 3.14)."""
# 1. Truthiness: what `if x:` decides for common objects
for value in (0, 7, 0.0, "", "0", [], [0], None, {}, {"k": 1}):
print(f"{value!r:>8} -> {'true' if value else 'false'}")
# 2. while: count the steps of the Collatz rule until n reaches 1
def collatz_steps(n):
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps
print([collatz_steps(n) for n in (1, 6, 7, 27)])
# 3. for with break and else: the smallest divisor, or "prime"
def smallest_divisor(n):
for d in range(2, n):
if d * d > n:
break # no divisor up to sqrt(n): stop searching
if n % d == 0:
return d
return None
def classify(n):
for d in range(2, n):
if n % d == 0:
result = f"{n} = {d} * {n // d}"
break
else: # runs only if the loop was not left by break
result = f"{n} is prime"
return result
print([smallest_divisor(n) for n in (15, 49, 97)], classify(91), classify(97))
# 4. continue: skip blank lines and comments, keep the rest
lines = ["# settings", "rate = 0.1", "", " # note", "epochs = 5"]
kept = []
for line in lines:
if not line.strip() or line.strip().startswith("#"):
continue
kept.append(line)
print(kept)
# 5. match: parse simple commands by their shape
def run(command):
match command.split():
case []:
return "nothing to do"
case ["go", ("north" | "south" | "east" | "west") as direction]:
return f"going {direction}"
case ["go", other]:
return f"cannot go {other!r}"
case ["take", *things] if things:
return f"taking {', '.join(things)}"
case ["quit" | "exit"]:
return "bye"
case [verb, *_]:
return f"unknown verb {verb!r}"
for c in ("", "go north", "go up", "take key lamp", "take", "quit", "dance now"):
print(f"{c!r:16} -> {run(c)}")
# Output with CPython 3.14.7 (the same on any platform):
# 0 -> false
# 7 -> true
# 0.0 -> false
# '' -> false
# '0' -> true
# [] -> false
# [0] -> true
# None -> false
# {} -> false
# {'k': 1} -> true
# [0, 8, 16, 111]
# [3, 7, None] 91 = 7 * 13 97 is prime
# ['rate = 0.1', 'epochs = 5']
# '' -> nothing to do
# 'go north' -> going north
# 'go up' -> cannot go 'up'
# 'take key lamp' -> taking key, lamp
# 'take' -> unknown verb 'take'
# 'quit' -> bye
# 'dance now' -> unknown verb 'dance'
"take" alone fails the guard if things (the list things is empty, so false) and falls through to the last case. smallest_divisor(97) stops at d = 10, since , having found no divisor, and returns None.
Next#
The programs of this note are already long enough to repeat themselves: the same loop with a different list, the same test in two places. The next note packages a block of code under a name with parameters, so that it can be called with different arguments, and shows what happens in memory when a function calls another, including itself.
References#
- Python documentation (3.14): The Python Tutorial, §4 (more control flow tools); The Python Language Reference, §8 (compound statements:
if,while,for,match) and §6.11–6.13 (Boolean operations, assignment expressions, conditional expressions); Truth value testing;dis. - B. Bucher, G. van Rossum. PEP 634 — Structural Pattern Matching: Specification. 2020. T. Kohn, G. van Rossum. PEP 635 — Motivation and Rationale and D. F. Moisset. PEP 636 — Tutorial. 2020.
- C. Angelico, T. Peters, G. van Rossum. PEP 572 — Assignment Expressions. 2018.
- G. van Rossum, B. Warsaw, A. Coghlan. PEP 8 — Style Guide for Python Code. 2001.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022. Ch. 2 (pattern matching with sequences) and ch. 3 (with mappings).
- B. Slatkin. Effective Python, 3rd ed. Addison-Wesley, 2024 (avoiding
elseblocks after loops; the walrus operator).