Core Python · #3 of 11
Control Flow
if/elif/else, for, while
Why it matters
Control flow is how you translate problem statements into steps.
The idea
Conditionals choose paths; loops repeat work without copy-paste. Prefer for over while whenever you know the iterable up front — for is harder to misread and harder to make infinite.
Try it
if / elif / else ladder, with a small game classifier:
def grade(score):
if score >= 90: return "A"
elif score >= 80: return "B"
elif score >= 70: return "C"
elif score >= 60: return "D"
else: return "F"
for s in [95, 82, 71, 64, 30]:
print(s, grade(s))
for over a range, with enumerate to get both index and value:
names = ["Ada", "Linus", "Margaret", "Grace"]
for i, n in enumerate(names, start=1):
print(f"{i:>2}. {n}")
while is best when the stop condition is a state, not a count. break exits early; continue skips to the next iteration.
# Find the first square > 100
n = 1
while True:
if n * n > 100:
print("first n with n^2 > 100:", n)
break
n += 1
Quick check
- Q: When do you use
continue? A: Skip the rest of the loop body and go to the next iteration.
Mini drills
- Sum all even numbers from 1 to 20.
- Print numbers 10 to 1 using a
whileloop.
Common mistakes
- Mistake: Infinite loop in
while. Fix: Update the loop variable. - Mistake: Off-by-one in
range. Fix: Rememberrangeis end-exclusive.
Key takeaways
- Use
forover an iterable when you can;whilewhen the stop is state-based. enumerate(seq)beatsrange(len(seq))for index+value loops.breakexits,continueskips — both are fine in moderation.- Indentation IS the block; no
{}to forget.