Control Flow
3.0 Intro · 3.1 Conditionals · 3.2 Iteration
← → or Space to navigate · F for fullscreen
The practical question is: which statement should run next?
if
else
elif
for
while
while True
break
continue
return
Python does not use goto, and this chapter does not cover match / case.
goto
match
case
0300-control-flow
0301-conditionals
0302-iteration
Boolean expressions · branches · chained decisions · nested decisions · conditional expressions
A if test else B
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F"
Conditions are checked from top to bottom. The first true branch wins.
x = 5 if x > 0: print("x is positive")
num = 12 if num % 2 == 0: print("even") else: print("odd")
True
False
and
or
not
% appears here only as an operator used in a condition. The operator itself belongs in Chapter 2.
%
score = 78 late = True if score >= 90: label = "strong" elif score >= 70 and not late: label = "passing" elif score >= 70: label = "late pass" else: label = "revise"
Trace:
score >= 90
score >= 70 and not late
score >= 70
"late pass"
For an if / elif chain, only the first true branch runs.
# Problem: always true for most values if status == "new" or "open": process_ticket() # Better if status == "new" or status == "open": process_ticket()
# Problem: equality vs. assignment if count = 0: print("empty") # Better if count == 0: print("empty")
Each side of and or or should usually be a complete Boolean expression.
if username == "admin": if password == "secret": print("Access granted") else: print("Wrong password") else: print("Unknown user")
if username == "admin" and password == "secret": print("Access granted")
if 0 < x < 10: print("single digit")
Nest when decisions genuinely depend on prior branches. Combine tests when the condition remains readable.
Use a conditional expression when the whole decision is a simple value choice.
age = 20 if age >= 18: status = "adult" else: status = "minor"
age = 20 status = "adult" if age >= 18 else "minor"
label = "even" if n % 2 == 0 else "odd"
Use this form for compact assignments, not for large blocks of work.
Use a conditional expression when all three are true:
When the branches do work, use a normal if / else block.
# Good: value choice fee = 0 if total >= 50 else 7.99
# Too much work for one expression if total >= 50: email = "free-shipping" fee = 0 else: email = "standard-shipping" fee = 7.99
iterables · for patterns · while patterns · loop control · accumulators
fruit = ("apple", "banana", "cherry") itr = iter(fruit) print(next(itr)) # apple print(next(itr)) # banana print(next(itr)) # cherry
iter()
next()
A for loop uses this machinery automatically.
for x in collection:
range()
for i in range(n):
for i in range(len(lst)):
enumerate()
for i, x in enumerate(lst):
for x in A: for y in B:
for fruit in ["apple", "banana", "cherry"]: print(fruit) for i, fruit in enumerate(["apple", "banana"]): print(i, fruit)
# Direct iteration for amount in rainfall: print(amount)
# Index-based update for i in range(len(numbers)): numbers[i] *= 2
# Parallel sequences for name, score in zip(names, scores): print(name, score)
# Dictionary items for name, score in scores.items(): print(name, score)
while True: response = input("Enter yes or no: ") if response in ["yes", "no"]: break
Start with the stopping rule, then choose the loop form.
for row in range(1, 4): for col in range(1, 4): print(row * col, end=" ") print()
matrix = [ [1, 2, 3], [4, 5, 6], ] for row in matrix: for value in row: print(value)
The inner loop completes once for each value produced by the outer loop.
times = 0 while times < 3: print("Hello!") times += 1
Every while loop needs a realistic path to stopping.
total = 0 value = int(input("Number? ")) while value != -1: total += value value = int(input("Number? "))
total = 0 while True: value = int(input("Number? ")) if value == -1: break total += value
# Problem: counter never changes count = 0 while count < 3: print(count)
# Better: loop state moves count = 0 while count < 3: print(count) count += 1
Check every while loop for:
If the loop condition depends on a variable, the loop body usually needs to update that variable.
pass
if x < 0: pass
for n in range(10): if n % 2 == 0: continue print(n)
rainfall = [0.2, 0.0, 1.3, 0.4] total = 0 for amount in rainfall: total += amount print(total)
wet_days = 0 for amount in rainfall: if amount > 0: wet_days += 1 print(wet_days)
Set the accumulator before the loop. Update it inside the loop. Use it after the loop.
scores = [88, 72, 95, 61] passing = 0 for score in scores: if score >= 70: passing += 1
labels = [] for score in scores: labels.append("pass" if score >= 70 else "revise")
0
total += value
count += 1
1
product *= value
[]
items.append(value)
Name the accumulator for the result it will hold after the loop.
temperatures = [82, 91, 74, 99, 68] hot_days = 0 for temp in temperatures: if temp < 75: continue if temp >= 95: break hot_days += 1 print(hot_days)
Work through the loop by hand:
hot_days += 1
Use a trace table when if, continue, and break interact.
Next: Chapter 4 — Functions
defining functions · parameters · return values · recursion