Topic 3 of 64
Control Flow
Overview
Python's control flow uses meaningful indentation instead of braces, making code readable but requiring careful attention to whitespace. The match statement (Python 3.10+) brings pattern matching similar to switch.
Syntax
python
# if / elif / else
score = 85
if score >= 90: grade = "A"
elif score >= 75: grade = "B"
elif score >= 60: grade = "C"
else: grade = "F"
# Ternary (one-liner)
status = "Pass" if score >= 60 else "Fail"
# match (Python 3.10+)
match command:
case "quit": exit()
case "start": start_game()
case "help": show_help()
case _: print("Unknown command")
# Loops
for i in range(5): print(i)
for item in my_list: print(item)
while condition: do_something()
# Loop controls
break # exit loop
continue # skip to next iteration
else: # runs if loop completes without breakCommon Pitfalls
- The else clause on loops is a Python quirk — it runs when the loop completes normally (not via break).
- range(5) gives 0–4, NOT 0–5. range(1, 6) gives 1–5.
- Interview tip: List comprehensions are faster than equivalent for loops because they're optimized at the C level.
Real-World Example
A shipping cost calculator with pattern matching:
example
python
def calculate_shipping(weight_kg: float, zone: str) -> float:
base_rates = {"local": 30, "regional": 60, "national": 120}
match zone:
case "local" if weight_kg <= 0.5:
return base_rates["local"]
case "local":
return base_rates["local"] + (weight_kg - 0.5) * 20
case "regional":
return base_rates["regional"] + weight_kg * 15
case "national":
return base_rates["national"] + weight_kg * 25
case _:
raise ValueError(f"Unknown zone: {zone}")
# List comprehension (one-line for loop)
heavy_orders = [o for o in orders if o["weight"] > 5]