Control Flow
if / for / while / match — the Python way.
Python Control Flow
Python's syntax for control flow is famously minimal — no curly braces, no semicolons. Indentation is the language.
if / elif / else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
The condition doesn't need parentheses. Each branch is the indented block underneath. Conditions can be any expression — Python's truthiness rules decide.
for loops
for iterates over anything iterable — lists, dicts, strings, files, ranges, generators:
for x in [1, 2, 3]: # list
print(x)
for ch in "abc": # string
print(ch)
for k, v in user.items(): # dict (key + value via items())
print(k, v)
for i in range(5): # range — 0..4
print(i)
for i, x in enumerate(xs): # index + value
print(i, x)
Need to iterate two collections in parallel? zip:
for name, age in zip(names, ages):
print(name, age)
while loops
For when you don't know the iteration count up front:
while not done:
chunk = fetch()
process(chunk)
done = chunk.is_last
while True: plus break is a common pattern when you need a "loop until X happens" with exit condition mid-body.
break, continue, else (yes really)
for line in lines:
if line.startswith("#"):
continue # skip
if line == "END":
break # stop
process(line)
else:
print("loop completed without break")
Yes, for and while loops can have an else. It runs only when the loop finished without a break. Useful for search loops:
for x in candidates:
if matches(x):
result = x
break
else:
raise NotFound
match (3.10+)
Python's structural pattern matching:
match command.split():
case ["quit"]:
return None
case ["go", direction]:
return move(direction)
case ["take", *items]:
return take(items)
case _:
return error("unknown command")
Each case can match literal values, bind variables (direction), or destructure (*items, dict keys, class instances).
Comprehensions are conditions too
A list comprehension with if filters:
evens = [x for x in xs if x % 2 == 0]
Equivalent loop:
evens = []
for x in xs:
if x % 2 == 0:
evens.append(x)
The comprehension is denser, no faster — but it scans more like its English description: "the even x in xs".
Conditional expressions
Python has a ternary, written with English keywords:
status = "active" if user.logged_in else "anonymous"
Read it as: "value if condition else other-value". Convention: keep them short. If the branches need to be more than a few words, use a regular if statement.
Tip: don't compare booleans to True
# Don't:
if user.is_admin == True:
# Do:
if user.is_admin:
The first reads as "ask whether is_admin equals True"; the second reads as "ask whether is_admin". The latter matches the way you'd say it out loud.