Chapter 04
Control flow and exceptions
Conditions and pattern matching
Indentation defines blocks. Use if/elif/else for decisions; match/case (Python 3.10+) for structural pattern matching.
status = 200
match status:
case 200: print("OK")
case 404: print("Not found")
case _: print("Other")Hands-on lab: Rewrite the example using if/elif/else.
Loops
for iterates over sequences; while repeats while a condition is true. break exits a loop and continue skips to the next iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)Hands-on lab: Print only even numbers from 1 to 20.
Exception handling
Use try/except to handle expected errors, and finally for cleanup. Python 3.11+ also supports ExceptionGroup and except*.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")Hands-on lab: Catch FileNotFoundError while opening a missing file.