Skip to content
BIASED

Control flow

Block 1 of 8~2 min

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.

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

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