Skip to content
BIASED

Control flow

How a program chooses and repeats: if, elif and else, the truth test, short-circuit and and or, while and for loops, break, continue and a loop's else, pattern matching with match, and expressions versus statements.

Choosing a branch: if, elif, else

The topic Values, types and names described what a program works on: objects, and the names bound to them. Every program there ran each of its lines exactly once, from top to bottom. That is enough for a calculator. A training script needs more. It has to choose what to do depending on the data, repeat a step for every epoch, and stop early once the model has stopped improving. This topic covers the statements that do that, if, while, for and match, and the question each of them asks of the object it is given.

The first is if. It 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 of them holds, it runs the else block, when there is one. At most one block runs.

loss = 0.42
if loss > 1.0:
    print("diverging")
elif loss > 0.1:
    print("still learning")
else:
    print("converged")
still learning

loss > 1.0 is false, so Python moves on to loss > 0.1, which is true. It prints still learning, and the statement ends; the else block is never reached. Conditions are tried from top to bottom and the first true one wins, so put the strictest condition first.

Blocks are made by indentation. Python has no braces. A line ending in : opens a block, and the block is every following line indented further than it; the block ends at the first line indented back. The convention is four spaces per level (PEP 8). Indentation is part of the syntax, so a mistake in it is reported before anything runs. Here is a file ind.py whose second line has lost its indent:

if True:
print("indented?")
$ python ind.py
  File ".../ind.py", line 2
    print("indented?")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 1

Comparisons chain. 0 < lr < 0.01 is true when both 0 < lr and lr < 0.01 hold, and lr is evaluated only once.

What counts as true

The condition of an if does not have to be a bool. It can be any object, and Python asks the object whether it counts as true.

The rule is short. 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 built-in object is true. The built-in bool() applies the same test:

print(bool(None), bool(False), bool(0), bool(0.0), bool(""), bool([]), bool({}))
print(bool(1), bool(-0.5), bool("False"), bool([0]), bool(" "))
False False False False False False False
True True True True True

The string "False" is true because it is not empty; what it says does not matter. [0] is a list of length 1, so it is true whatever its element is. A single space is one character, so " " is true too.

This is what lets if losses: mean "if the list is not empty", the idiomatic test:

losses = []
if losses:
    print(len(losses), "epochs logged")
else:
    print("no epochs yet")
no epochs yet

Objects of types you write yourself answer through the special method __bool__, or through __len__, with a length of zero meaning false; the topic The data model shows how. Under the hood, if x: compiles to one instruction that runs this test and a conditional jump over the block. The topic How CPython runs code reads that bytecode.

and, or and not

and, or and not combine conditions, and they use the same truth test. Only not always returns a bool. The other two return one of their operands.

  • 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 evaluates a. If a is false, it is the result. Otherwise the result is b.

Stopping as soon as the answer is known is called short-circuit evaluation. It gives two idioms, a default value and a guard:

run_name = ""
print(run_name or "unnamed-run")
print([] and 1 / 0)
print(3 and "yes", not "", not [0])
unnamed-run
[]
yes True False

The second line never divides. [] is false, so and returns it without evaluating 1 / 0, which would otherwise raise ZeroDivisionError.

The mistake. label == "cat" or "dog" reads like English, "the label is cat or dog". Python reads it differently:

label = "fish"
print(label == "cat" or "dog")
print(label == "cat" or label == "dog")
print(label in ("cat", "dog"))
dog
False
False

== binds more tightly than or, so the first condition is (label == "cat") or "dog". The left side is False, so or returns "dog", a non-empty string, which is true. Inside an if, that condition would hold for every label. Write both comparisons, or use in.

Repeating while a condition holds: while

An if runs its block at most once. A while loop runs its block as long as a condition holds. It evaluates the condition and, if it counts as true, runs the block; then it evaluates the condition again, and so on. The loop ends the first time the condition is false. So the block must eventually change something the condition depends on.

A typical use is an algorithm that repeats a step until it converges. Here gradient descent minimizes x2x^2, whose gradient is 2x2x, with learning rate 0.250.25:

x = 1.0
steps = 0
while abs(x) > 0.01:
    x = x - 0.25 * 2 * x   # gradient step on x**2 with lr 0.25
    steps += 1
print(steps, x)
7 0.0078125

abs is the absolute value, and steps += 1 is short for steps = steps + 1. Each step halves x: 1, 0.5, 0.25, and so on. After the seventh step x is 1/128=0.00781251/128 = 0.0078125, the condition is false for the first time, and the loop ends. The same loop, with a real model in place of x2x^2, is gradient descent in the course Machine Learning.

Without the line that changes x, 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: until convergence, until the input ends. When there is a collection to go through, for is clearer.

Repeating over items: for

for name in iterable: runs its block once for each item that the iterable produces, and binds the name to the item before each pass. An iterable is any object that can hand out its items one at a time. A list gives its elements, a string its characters, a dict its keys, a file its lines, and a range its numbers.

losses = [0.9, 0.6, 0.45]
for loss in losses:
    print(loss)
print(list(range(5)), list(range(1, 4)), list(range(10, 0, -4)))
0.9
0.6
0.45
[0, 1, 2, 3, 4] [1, 2, 3] [10, 6, 2]

range(stop) produces 0,1,…,stop−10, 1, \ldots, \text{stop} - 1. range(start, stop, step) starts at start and moves by step until it reaches stop, which is never included. So range(n) has exactly n items, the valid indices of a list of length n. A range stores no numbers; it computes each one when asked, and list() above only collects them for display.

Two built-ins cover most other needs. enumerate pairs each item with its index, and zip pairs the items of two iterables position by position. Each pair is unpacked into two names:

for epoch, loss in enumerate([0.9, 0.6, 0.45]):
    print(epoch, loss)
for split, acc in zip(["train", "val"], [0.98, 0.91]):
    print(split, acc)
0 0.9
1 0.6
2 0.45
train 0.98
val 0.91

How for gets the items. The loop asks the object for an iterator once, with the built-in iter(). Before every pass it asks the iterator for the next item with next(). When no items are left, next() raises the exception StopIteration, and the loop ends. The same calls can be made by hand (the file path is shortened):

it = iter("ab")
print(next(it))
print(next(it))
print(next(it))
a
b
Traceback (most recent call last):
  File ".../iter_demo.py", line 4, in <module>
    print(next(it))
          ~~~~^^^^
StopIteration

A for loop catches this StopIteration itself and simply ends. An object that does not support iter() cannot be looped over: for x in 42: raises TypeError: 'int' object is not iterable. The topic Iteration, comprehensions and generators states this iterator protocol in full.

The mistake. Changing a list while a for loop walks over it skips items, because a list iterator walks by position:

nums = [1, 2, 2, 3]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)
[1, 2, 3]

The first 2, at position 1, is removed. The second 2 shifts into position 1, and the iterator moves on to position 2, which now holds 3. One 2 survives. Build a new list with append instead, or loop over a copy, for n in nums[:]:.

Leaving early: break, continue and else

Three more pieces control where a loop goes next.

  • break ends the innermost loop at once. Execution continues after the loop.
  • continue ends the current pass. A while loop re-checks its condition; a for loop asks for the next item.
  • A loop may have an else block. It runs when the loop ends normally, because the condition of a while became false or the items of a for ran out. It does not run when the loop is left by break. Read it as "no break".

Early stopping uses all of this. It ends training when the validation loss has not improved for a given number of epochs in a row, the patience; here it is 2. float("inf") is infinity, larger than any loss:

val_losses = [0.9, 0.7, 0.65, 0.66, 0.67, 0.64]
best = float("inf")
bad_epochs = 0
for epoch, loss in enumerate(val_losses):
    if loss < best:
        best = loss
        bad_epochs = 0
    else:
        bad_epochs += 1
        if bad_epochs == 2:
            print("early stop at epoch", epoch, "best", best)
            break
else:
    print("all epochs done, best", best)
early stop at epoch 4 best 0.65

Epochs 0 to 2 improve the best loss. Epochs 3 and 4 do not, so at epoch 4 the counter reaches 2 and break leaves the loop. The loss 0.64 is never examined, and the else block is skipped. Had the list run out first, else would have reported that all epochs finished, with no flag variable needed.

continue skips the rest of one pass. Here it leaves missing values out of a mean:

losses = [0.5, None, 0.25, None, 0.75]
total = 0
count = 0
for loss in losses:
    if loss is None:
        continue        # skip a missing value
    total += loss
    count += 1
print(count, total / count)
3 0.5

Choosing by shape: match

An if–elif chain compares values. Often a program has a different question: what shape is this data, and what are its parts? A command typed by a user, a JSON message, an entry in a config. The match statement, added in Python 3.10, answers it. This is pattern matching.

match subject: evaluates the subject once and tries each case pattern from top to bottom. The first pattern that fits runs its block, and the other cases are skipped. A pattern may carry a guard, an if condition after it, which must also be true. A fitting pattern can bind names to parts of the subject. If no case fits, nothing happens and no error is raised.

Here split() cuts a line into a list of words (the topic Strings and text covers it), and match dispatches on that list:

for command in ["train 10", "eval", "save best.pt", "exit", "", "dance now"]:
    match command.split():
        case ["train", epochs]:
            print("training for", epochs, "epochs")
        case ["eval"]:
            print("evaluating")
        case ["save", path]:
            print("saving to", path)
        case ["quit" | "exit"]:
            print("bye")
        case []:
            print("empty line")
        case [verb, *rest]:
            print("unknown command", verb, rest)
training for 10 epochs
evaluating
saving to best.pt
bye
empty line
unknown command dance ['now']

["train", epochs] fits a list of exactly two elements whose first equals "train", and binds epochs to the second. "quit" | "exit" accepts either word. [verb, *rest] fits any list of at least one element and collects the remaining ones into the list rest. The kinds of patterns:

Pattern Fits Binds
"eval", 0, None (literal) an equal value nothing
epochs (bare name, capture) anything the name to the subject
_ (wildcard) anything nothing
[a, b] or (a, b) (sequence) a sequence of that length, never a string each name to an element
[a, *rest] a sequence of length at least 1 rest to a list of the rest
{"type": t} (mapping) a mapping with those keys; extra keys are ignored t to the value
float(v), str() as s (class) an instance of that type v, or s, to the subject
"quit" | "exit" (OR) either alternative the same names in each

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:

BEST = "best.pt"
path = "last.pt"
match path:
    case BEST:
        print("best checkpoint, BEST =", BEST)
best checkpoint, BEST = last.pt

The case fits everything and overwrites BEST. If another case follows it, the compiler refuses the whole statement with SyntaxError: name capture 'BEST' makes remaining patterns unreachable. To compare with a constant, write a literal, case "best.pt":, or a dotted name such as math.pi, which a pattern treats as a value.

Expressions and statements

An expression is code that produces a value: 3, x + 1, len(losses) > 3, print("hi"). A statement is code that does something and produces nothing: an assignment, if, for, import. An expression can stand wherever a value is needed, inside another expression or as an argument; a statement cannot.

if is a statement, so it cannot appear where a value is expected. Its expression form is the conditional expression a if condition else b. It evaluates the condition first, then only one of a and b:

epoch = 7
phase = "warm-up" if epoch < 5 else "main"
print(phase)
main

An assignment is a statement too, so it cannot be nested in an expression. The compiler suggests what was probably meant:

$ python nested.py
  File ".../nested.py", line 1
    y = (x = 5)
         ^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

The assignment expression name := value (Python 3.8+) binds a name and also produces the value, which saves computing it twice:

losses = [0.9, 0.6, 0.45, 0.4, 0.38]
if (n := len(losses)) > 3:
    print(n, "epochs logged")
5 epochs logged

That is the whole toolkit of a training script: for epoch in range(n_epochs): around the training step, while until a change falls below a tolerance, break for early stopping, continue to skip bad batches, and conditional expressions for small choices. The programs of this topic already repeat themselves, though. The early-stopping loop would be copied into every experiment, each time with another list of losses and another patience. The topic Functions gives such a block a name and parameters, so that it is written once and called with different arguments.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Loop: add the numbersoptional

    Real Python in your browser with result checks and a stop button. Device-local self-check; does not affect certificates.

    ~8 min · any device · Read this topic's notes.

    Open practice

Full notes

Answers are saved on the server and tied to this browser until you sign in.