Control Flow: if / elif / else
Every interesting program eventually needs to make a decision. This is the chapter where your code starts to think.
if
is how your program branches based on what's actually true right now.
To make it concrete, this chapter builds up one running example —
the checkout logic behind an online store — one decision at a time.
1. Simple if
An if statement checks a condition. If it's
True, the indented block underneath runs. If it's
False, Python skips that block entirely and moves on.
Here's the first decision our online store has to make at checkout: does this order qualify for free shipping?
order_total = 62.50
if order_total >= 50:
print("You qualify for free shipping!")
print("Thanks for shopping with us.")
You qualify for free shipping!
Thanks for shopping with us.
{ } mark a block of
code. Python uses indentation (consistent spacing,
usually 4 spaces) instead — every line indented under the
if is part of that block. This isn't just a style
preference; it's how Python knows where the block ends. Mixing tabs
and spaces, or indenting inconsistently, causes a real error.
Go Deeper: why colon + indentation instead of braces?
Python's designer, Guido van Rossum, wanted code layout to be forced to match code structure — in languages with braces, you can indent however you like and the compiler doesn't care, which sometimes lets sloppy or misleading formatting slip through. By making indentation the actual syntax, Python code you read is guaranteed to be structured the way it looks.
if condition:then an indented block runs only when the condition isTrue.- Indentation is not decoration — it's how Python defines the block.
- Code after the
ifblock, back at the original indent level, always runs.
2. if-else
Often you want to do one thing OR another — never both, never
neither. else catches every case the if
didn't.
Before a customer can check out, the store needs to verify their login — a password either matches or it doesn't.
True
or False — usually built from the relational and
logical operators from Chapter 3. entered_password ==
stored_password is a boolean expression: it's either
True (they match) or False (they don't),
never anything in between.
stored_password = "hunter2"
entered_password = "hunter2"
if entered_password == stored_password:
print("Welcome back!")
else:
print("Access denied.")
Welcome back!
Change entered_password to anything else and the
else branch takes over instead:
Access denied.
else:runs exactly when theifcondition wasFalse.- Exactly one of the two blocks runs — never both, never neither.
3. elif — checking more than two possibilities
Real decisions often have more than two outcomes. elif
(short for "else if") lets you check condition after condition, in
order, stopping at the first one that's true.
Our store rewards loyal customers with a membership tier based on how
much they've spent this year — Standard, Silver, Gold, or
Platinum. That's four outcomes from one number, which is exactly what
an elif chain is for.
annual_spend = 620
if annual_spend >= 1000:
tier = "Platinum"
elif annual_spend >= 500:
tier = "Gold"
elif annual_spend >= 200:
tier = "Silver"
else:
tier = "Standard"
print("Membership tier:", tier)
Membership tier: Gold
Go Deeper: order matters in an elif chain
Python checks each condition top to bottom and stops at the very
first True one — it never checks the rest, even
if they'd also be true. This is why the membership example checks
>= 1000 before >= 500: if it checked
>= 200 first, a customer who spent $1,200 would
incorrectly match that condition first and stop there, before ever
reaching >= 1000 — a Platinum customer would
get downgraded to Silver by a bug in the ordering alone. Always
order an elif chain from most specific (or highest threshold) to
least. (This is the same pattern this chapter's project applies to
letter grades — A before B before C, never the reverse.)
elifchecks another condition only if the previous ones wereFalse.- Only the first matching branch runs — order your conditions carefully.
elseat the end catches everything that didn't match any condition.
4. Nested if — decisions inside decisions
An if can contain another if inside its
block. This is useful when the second question only makes sense
after the first is already answered.
Shipping cost is a perfect example: the store first checks the customer's membership tier from the last section, and only if they're a Gold member does it bother checking the order's weight — a Standard customer never needs that second question asked at all.
membership_tier = "Gold"
order_weight_kg = 12
if membership_tier == "Gold":
if order_weight_kg <= 20:
print("Free shipping applied (Gold member, order under 20kg).")
print("Order confirmed.")
Free shipping applied (Gold member, order under 20kg).
Order confirmed.
Go Deeper: nested if vs. a single "and"
The example above could also be written as one line:
if membership_tier == "Gold" and order_weight_kg <= 20:.
Both are correct here. Nesting becomes genuinely necessary once the
inner decision needs its own separate else, or depends
on something only computed inside the outer block — you'll see
real examples of this once you reach loops and functions.
- An
ifinside anotherif's block is called nested. - The inner condition is only checked if the outer one was already
True.
- Every pricing or membership tier page ("Free / Pro / Enterprise", or the Standard/Silver/Gold/Platinum tiers you just built) is an elif chain checking usage or spend level, ordered exactly the way this chapter taught — get the order wrong and customers get billed incorrectly.
- Login systems, fraud checks, and content moderation are almost entirely nested if-statements: "if logged in, if verified, if not flagged, then..." — the same shape as the shipping-cost check above, just with more layers.
- Real bug reports about "wrong tier applied" or "wrong shipping cost shown" are very often exactly the elif-ordering bug you just saw in the Go Deeper above.
Points to Remember
if condition:runs an indented block only when the condition is true.- Indentation defines the block in Python — there are no curly braces.
elsecatches everything theifdidn't; exactly one branch runs.elifchains check multiple possibilities in order, stopping at the first match — order high-to-low or most-specific-first.- Nested
ifstatements handle decisions that only make sense after an outer condition is already true.