Control Flow
Programs that only run top-to-bottom are useless. Learn how to make decisions (if), repeat actions (for, while), and control exactly when things happen.
If / Elif / Else
if checks a condition. If it's True, the indented block runs. Otherwise Python falls through to elif or else.
Indentation is syntaxPython uses indentation (4 spaces) instead of curly braces
{}. The indented lines are the block. Get the indentation wrong and you get an error.score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score} → Grade: {grade}") # Score: 82 → Grade: B
# One-liner (ternary) — great for simple cases
status = "adult" if score >= 50 else "minor"
print(status)
Output
For Loops
A for loop iterates over any sequence — a list, a string, a range, a dictionary, anything.
fruits = ["apple", "banana", "cherry"]
# Basic iteration
for fruit in fruits:
print(f"I like {fruit}")
# range() — generates numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i, end=" ")
print()
for i in range(2, 10, 3): # 2, 5, 8 (start, stop, step)
print(i, end=" ")
print()
# enumerate() — gives you index AND value
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip() — loop over two lists together
prices = [1.2, 0.5, 2.0]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: ${price}")
Output
While Loops
A while loop keeps running as long as its condition is True. Use it when you don't know in advance how many times to loop.
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # MUST update condition, or infinite loop!
# Countdown
n = 5
while n > 0:
print(n, end=" ")
n -= 1
print("Go!")
# while True with break — common pattern
attempts = 0
while True:
attempts += 1
if attempts >= 3:
print(f"Done after {attempts} attempts")
break
Output
Infinite loopsIf you forget to update the condition in a
while loop, it will run forever. Always make sure something in the loop body moves you toward the exit condition.Break, Continue, and Pass
# break — exits the entire loop immediately
print("break demo:")
for i in range(10):
if i == 5:
break
print(i, end=" ") # 0 1 2 3 4
print()
# continue — skips the rest of THIS iteration
print("continue demo (odds only):")
for i in range(10):
if i % 2 == 0:
continue # skip evens
print(i, end=" ") # 1 3 5 7 9
print()
# pass — a no-op placeholder
print("pass demo:")
for i in range(5):
if i == 3:
pass # TODO: handle this case later
else:
print(i, end=" ")
Output