Lesson 3 of 40
Foundations
Beginner
โฑ 25 min
Control Flow โ if, for, while, match
Control program flow with if/elif/else, Python's structural pattern matching (match/case), for loops with enumerate, while loops, and comprehension shortcuts.
Part 1: if / elif / else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C or below"
# Ternary (conditional expression)
status = "pass" if score >= 50 else "fail"
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C or below"
# Ternary (conditional expression)
status = "pass" if score >= 50 else "fail"
Part 2: match / case โ Structural Pattern Matching
# Python 3.10+ match statement
def handle_command(command):
match command:
case "quit" | "exit":
return "Goodbye!"
case {"action": action, "target": target}:
return f"Do {action} on {target}"
case [first, *rest]:
return f"List starting with {first}"
case _:
return "Unknown"
def handle_command(command):
match command:
case "quit" | "exit":
return "Goodbye!"
case {"action": action, "target": target}:
return f"Do {action} on {target}"
case [first, *rest]:
return f"List starting with {first}"
case _:
return "Unknown"
Part 3: for loops with enumerate & zip
fruits = ["apple", "banana", "cherry"]
# enumerate gives index + value
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip โ iterate multiple lists together
names = ["Alice", "Bob"]
scores = [95, 82]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# range
for i in range(0, 10, 2): # 0,2,4,6,8
print(i)
# enumerate gives index + value
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip โ iterate multiple lists together
names = ["Alice", "Bob"]
scores = [95, 82]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# range
for i in range(0, 10, 2): # 0,2,4,6,8
print(i)
Part 4: while, break, continue & else
# while with else (runs if loop wasn't broken)
n = 1
while n <= 100:
if n % 7 == 0:
print(f"Found: {n}")
break
n += 1
else:
print("No multiple of 7 found")
n = 1
while n <= 100:
if n % 7 == 0:
print(f"Found: {n}")
break
n += 1
else:
print("No multiple of 7 found")