Skip to content
Sign inGet all access
Chapter 3·10 minFree

Control Flow

Branching, looping, and the walrus operator.

Conditionals

if / elif / else. No parentheses around the condition, and a colon before the block:

age = 15

if age < 13:
    print("child")
elif age < 20:
    print("teenager")
else:
    print("adult")
Outputteenager

The ternary puts the value first, the condition second — the reverse of cond ? a : b:

age = 20
label = "adult" if age >= 18 else "minor"
print(label)
Outputadult

Comparisons chain, which is unusual and genuinely useful:

x = 5

if 0 < x < 10:
    print("in range")
Outputin range

Loops

There is no C-style for (i = 0; i < n; i++). One for, and it iterates a sequence:

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)
Outputapplebananacherry

When you genuinely need numbers, range produces them:

for i in range(3):
    print(i)
Output012

It takes a start and a step too:

for i in range(0, 10, 3):   # start, stop, step
    print(i)
Output0369

while repeats while a condition holds:

n = 0

while n < 3:
    print(n)
    n += 1
Output012

break leaves the loop early:

for i in range(10):
    if i > 2:
        break
    print(i)
Output012

continue skips to the next pass:

for i in range(5):
    if i % 2 == 0:
        continue
    print(i)
Output13

for/else and match

Two constructs you are unlikely to have met before.

A loop can have an else. It runs only if the loop finished without hitting break — the “searched and found nothing” case:

n = 7

for i in range(2, n):
    if n % i == 0:
        print(f"{n} is divisible by {i}")
        break
else:
    print(f"{n} is prime")
Output7 is prime

match compares a value against several cases, like a switch:

command = "quit"

match command:
    case "start":
        print("Starting")
    case "quit":
        print("Quitting")
    case _:
        print("Unknown command")
OutputQuitting

The walrus operator

:= assigns inside an expression, so you can use a value and keep it in one step:

total = 7 * 3

if (half := total // 2) > 5:
    print(f"half is {half}")
Outputhalf is 10

Without it you compute the value, then test it, then use it again:

total = 7 * 3
half = total // 2

if half > 5:
    print(f"half is {half}")
Outputhalf is 10