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")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)Comparisons chain, which is unusual and genuinely useful:
x = 5
if 0 < x < 10:
print("in 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)When you genuinely need numbers, range produces them:
for i in range(3):
print(i)It takes a start and a step too:
for i in range(0, 10, 3): # start, stop, step
print(i)while repeats while a condition holds:
n = 0
while n < 3:
print(n)
n += 1break leaves the loop early:
for i in range(10):
if i > 2:
break
print(i)continue skips to the next pass:
for i in range(5):
if i % 2 == 0:
continue
print(i)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")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")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}")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}")