🐍 Python for Everyone

← Back to all chapters

Chapter 4 of 27 Beginner 18 min read

Control Flow: if / elif / else

Every interesting program eventually needs to make a decision. This is the chapter where your code starts to think.

So far, every program you've written runs the exact same lines every single time, top to bottom. Real software doesn't work that way — a login check either lets you in or doesn't, a discount either applies or doesn't, a grade is A or B or C depending on the score. 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.
Sub-topic 1 of 4

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?

free_shipping.py
order_total = 62.50

if order_total >= 50:
    print("You qualify for free shipping!")

print("Thanks for shopping with us.")
Output
You qualify for free shipping!
Thanks for shopping with us.
try_shipping.py
Click "Run Code" — try changing 30 to 75 and running again.
What is... indentation? In most languages, curly braces { } 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.

Quick recap
  • if condition: then an indented block runs only when the condition is True.
  • Indentation is not decoration — it's how Python defines the block.
  • Code after the if block, back at the original indent level, always runs.
Sub-topic 2 of 4

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.

What is... a boolean expression? A boolean expression is anything that evaluates to 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.
login_check.py
stored_password = "hunter2"
entered_password = "hunter2"

if entered_password == stored_password:
    print("Welcome back!")
else:
    print("Access denied.")
Output
Welcome back!

Change entered_password to anything else and the else branch takes over instead:

Output (entered_password = "wrongpass")
Access denied.
Quick recap
  • else: runs exactly when the if condition was False.
  • Exactly one of the two blocks runs — never both, never neither.
Sub-topic 3 of 4

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.

membership_tier.py
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)
Output
Membership tier: Gold
try_tier.py
Click "Run Code" — try a few different annual_spend values.
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.)

Quick recap
  • elif checks another condition only if the previous ones were False.
  • Only the first matching branch runs — order your conditions carefully.
  • else at the end catches everything that didn't match any condition.
Sub-topic 4 of 4

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.

shipping_cost.py
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.")
Output
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.

Quick recap
  • An if inside another if's block is called nested.
  • The inner condition is only checked if the outer one was already True.
In the Real World

Points to Remember

← Chapter 3 Take the Quiz →