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))
not loaded

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}")
not loaded

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
not loaded

Quick check

Mini drills

Common mistakes

Key takeaways