if / elif / else — Decisions
Programs become *smart* the moment they can choose. The if/elif/else structure is Python's decision machine — and after the booleans lesson, you already know half of it.
The basic if
age = 20
if age >= 18:
print("You can vote")
print("Bring your ID")
print("This always runs")The recipe: the if keyword, a condition (which produces True/False), a colon, then an indented block that runs only when the condition is True. The moment indentation returns, you're outside the decision.
else — the other path
marks = 40
if marks >= 50:
print("Passed!")
else:
print("Failed — try again")Exactly one of the two blocks runs. Never both, never neither. else needs no condition — it's simply "everything else."
elif — the ladder
When there are more than two outcomes, elif (short for "else if") builds a ladder:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: F")Output:
Grade: BHow the ladder executes (the key insight)
Python checks conditions top to bottom and runs only the first True block — then jumps past the entire ladder:
This "first match wins" behavior is why the order matters. Reverse the ladder and 85 hits >= 50 first, printing D. Rule: check strictest conditions first.
You can also end a ladder with just an else and no final elif — the else catches everything no condition caught.
Conditions are just booleans
Everything from the booleans lesson plugs straight in:
temperature = 35
is_sunny = True
if temperature > 30 and is_sunny:
print("Perfect for ice cream")
if not is_sunny or temperature > 40:
print("Stay hydrated either way")
# Truthiness shortcut from the booleans lesson:
name = input("Name: ")
if name: # non-empty string = True
print(f"Hello, {name}")
else:
print("You didn't type a name!")Nested ifs (and when to avoid them)
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Bring your ID")This works, but two levels deep is where nesting should stop. The same logic reads flatter as:
if age >= 18 and has_id:
print("Entry allowed")
elif age >= 18:
print("Bring your ID")Flat beats nested — your future self will thank you.
Common Errors & Fixes
: has no indentation. Indent 4 spaces.= instead of ==.✅ Checkpoint
else need a condition? *(No — it's the catch-all)*Next: for loops — making Python do the repeating.