Lesson 4 of 16 · Level 1: Beginner

Python Conditionals: if, elif, else and match

  • ⏱ 12 min read
  • ❓ 4 review questions
  • ✍️ Exercise with solution
In this lesson
  1. if: run something only when a condition is true
  2. if / else: two paths
  3. if / elif / else: several paths
  4. Compound conditions: and, or, not
  5. Truthy and falsy values
  6. Nested conditionals
  7. The ternary expression: if on one line
  8. match: compare against many values (Python 3.10+)
  9. Full example: an online store's shipping calculator
  10. Real case: tiered sales commissions at a Chicago distributor
  11. Common mistakes with conditionals
  12. Summary
What you'll learn
  • Make decisions with if, elif and else.
  • Combine conditions with and, or and not.
  • Understand truthy and falsy values.
  • Use the one-line ternary expression and the match statement.
  • Code real business rules, like tiered sales commissions, without ordering bugs.

Until now your programs ran every line, always in the same order. Conditionals let them make decisions: do one thing if a condition is true and something else if it isn't. They're the first of Python's control structures, and they're how you turn business rules ("free shipping over $75," "5% commission above $100,000") into code.

3keywords for making decisions: if, elif and else
1block runs in each if/elif/else chain: the first one whose condition is true
4spaces of indentation mark which lines depend on each condition

if: run something only when a condition is true

age = int(input("Age: "))

if age >= 18:
    print("You're 18 or older")
    print("You can register to vote")

print("End of program")

Three syntax details you can't skip:

  1. The condition ends with a colon :.
  2. The instructions that depend on the if are indented 4 spaces. That's the block.
  3. The first line without indentation marks the end of the block. "End of program" always prints.

if / else: two paths

gift_card_balance = 120
purchase = 150

if gift_card_balance >= purchase:
    gift_card_balance -= purchase
    print(f"Purchase approved. Balance: ${gift_card_balance}")
else:
    short = purchase - gift_card_balance
    print(f"Insufficient balance. You're ${short} short")

Exactly one of the two blocks runs. With these numbers, the output is Insufficient balance. You're $30 short.

if / elif / else: several paths

elif is short for "else if." Python checks the conditions from top to bottom and runs only the first block whose condition is true. Letter grades are the classic example:

score = float(input("Score (0-100): "))

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(grade)
The order of the conditions matters

If you put score >= 60 first, a 95 would land there and get a "D." Order from the strictest condition to the least strict. It's the same idea as Excel's IFS function.

1. With score = 85, an if score >= 60 prints "Pass" and a later elif score >= 80 prints "Honor roll." What gets printed?

  • Honor roll
  • Pass
  • Pass and Honor roll

Only the first block whose condition is true runs. 85 ≥ 60 is true, so Python never checks the elif. That's why you order from the strictest condition down.

Compound conditions: and, or, not

age = 25
has_license = True
is_member = False
order_total = 80

if age >= 21 and has_license:
    print("Can rent the car")

if is_member or order_total > 50:
    print("Free shipping")

if not has_license:
    print("You need a driver's license first")
andAll must be true
True when
Every condition is true.
Example
age >= 21 and has_license
Typical use
Requirements: old enough and licensed.
Strictest
orOne is enough
True when
At least one condition is true.
Example
is_member or order_total > 50
Typical use
Perks: free shipping for members or big orders.
Most flexible
notFlips the value
True when
The condition is false.
Example
not has_license
Typical use
Validation: warn when something is missing.
Inverts

For ranges, Python lets you chain comparisons in a very readable way: if 18 <= age < 65:.

2. With age = 20 and has_ticket = False, what is age >= 18 and has_ticket?

  • True
  • An error
  • False

and requires both conditions to be true, and has_ticket is False.

Truthy and falsy values

Inside a condition, Python treats these values as false: False, 0, 0.0, the empty string "", empty collections ([], {}) and None. Everything else counts as true. That lets you write clean checks like this one, which fixes the IndexError from lesson 3:

name = input("Name: ").strip()
if not name:
    print("You didn't enter a name")

3. Which of these values is treated as false in an if?

  • "0" (the string zero)
  • " " (a single space)
  • [] (an empty list)

Empty collections, 0, None and the empty string "" are falsy. "0" and " " are strings with content, so they're truthy.

Nested conditionals

You can put an if inside another one by adding indentation:

if user_registered:
    if password_correct:
        print("Welcome back")
    else:
        print("Wrong password")
else:
    print("User not found")

Use nesting sparingly: more than two or three levels make code hard to follow. Often you can combine conditions with and or reorder them instead.

The ternary expression: if on one line

status = "Pass" if score >= 60 else "Fail"
shipping = 0 if order_total >= 50 else 7.99

Use it only for simple two-option decisions. If you need an elif, go back to the full form.

match: compare against many values (Python 3.10+)

When you compare one variable against several specific values, match reads more clearly than a chain of elif statements. Here's the menu of a simple banking app:

option = input("Choose 1, 2 or 3: ")

match option:
    case "1":
        print("Check balance")
    case "2":
        print("Transfer money")
    case "3":
        print("Exit")
    case _:
        print("Invalid option")

The _ case means "any other value." Typing 2 prints Transfer money; typing 7 prints Invalid option.

Full example: an online store's shipping calculator

total = float(input("Order total: $"))
zone = input("Zone (local / in-state / out-of-state): ").strip().lower()
is_member = input("Rewards member? (y/n): ").strip().lower() == "y"

if is_member or total >= 75:
    shipping = 0
elif zone == "local":
    shipping = 5.99
elif zone == "in-state":
    shipping = 8.99
elif zone == "out-of-state":
    shipping = 12.99
else:
    shipping = None

if shipping is None:
    print("Unknown zone")
else:
    print(f"Shipping: ${shipping:.2f}")
    print(f"Total due: ${total + shipping:.2f}")
Order total: $62.50
Zone (local / in-state / out-of-state): in-state
Rewards member? (y/n): n
Shipping: $8.99
Total due: $71.49

Look at the is_member line: the comparison == "y" already returns True or False, so we store it directly as a boolean. To compare with None, use is, not ==. And because the zone goes through .strip().lower(), a customer who types "In-State " still gets the right rate.

Real case: tiered sales commissions at a Chicago distributor

Lakeshore Supply Co., a distributor in Chicago, pays its sales reps a commission that steps up with monthly sales, plus a $750 bonus for landing at least 3 new clients and reaching the minimum sales tier. Here's how Python decides which rate applies:

  1. First questionSales ≥ $100,000?If True, the rate is 5% and Python skips all the other conditions.
  2. OtherwiseSales ≥ $60,000?3% rate. Getting here already means sales were under $100,000.
  3. OtherwiseSales ≥ $30,000?1.5% rate.
  4. elseNothing matchedRate 0: the rep didn't reach the minimum tier.
# Monthly commission - Lakeshore Supply Co. (Chicago, Illinois)
sales = int(input("Sales this month ($): "))
new_clients = int(input("New clients: "))

if sales >= 100_000:
    rate = 0.05
elif sales >= 60_000:
    rate = 0.03
elif sales >= 30_000:
    rate = 0.015
else:
    rate = 0

commission = sales * rate
bonus = 750 if new_clients >= 3 and sales >= 30_000 else 0
total = commission + bonus

print(f"Rate applied: {rate:.1%}")
print(f"Commission: ${commission:,.2f}")
print(f"Bonus: ${bonus:,.2f}")
print(f"Total payout: ${total:,.2f}")

Here's what the terminal shows when Megan enters her numbers (what she types appears after each prompt):

Sales this month ($): 117500
New clients: 4
Rate applied: 5.0%
Commission: $5,875.00
Bonus: $750.00
Total payout: $6,625.00

Two new details. 100_000 is the same as 100000, but the underscores make big numbers readable at a glance (Python ignores them). And the bonus uses a ternary with and: both conditions are required. These are the month's results for the four reps, who sold $117,500, $71,000, $44,500 and $27,000 (green bars earned the bonus):

Total payout per rep

Megan$6,625
Derek$2,130
Valeria$1,417.50
Tyler$0

Valeria sold less than Derek (who landed only 1 new client) and earns less, but she gets the bonus because she brought in 3 new clients. Tyler brought in 5, yet gets no bonus: he didn't reach $30,000, and and requires both conditions.

4. In the commission program, if you changed the bonus's and to or, how much would Tyler ($27,000 in sales, 5 new clients) earn?

  • $750, just the bonus
  • $0, because he's below the minimum tier
  • $1,155, the 1.5% commission plus the bonus

With or, one condition is enough: 5 clients ≥ 3 is True, so he gets the bonus. His rate is still 0 because $27,000 doesn't reach any tier, so the total is $0 + $750.

Common mistakes with conditionals

Most if bugs are syntax errors, and Python describes them precisely. For example, if you forget to indent the line inside the if:

  File "commission.py", line 3
    print("ok")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

Python points at line 3 because that's where it expected the indentation. These are the mistakes that come up again and again:

Forgetting the colon: if sales >= 50

Every if, elif, else and case line ends with :. The message is SyntaxError: expected ':'.

Assigning instead of comparing: if sales = 50:

Use ==. Python even suggests it: Maybe you meant '==' or ':=' instead of '='?

if zone == "local" or "in-state":

This is always True, because "in-state" on its own is a non-empty string. Write zone == "local" or zone == "in-state", or zone in ("local", "in-state").

Comparing input without converting it: if age >= 18 with age = input().

Convert with int() first. Otherwise you'll see TypeError: '>=' not supported between instances of 'str' and 'int'.

Ordering tiers from lowest to highest with >=.

With >=, start with the highest tier; otherwise everything falls into the first one.

Practice exercise: a BMI calculator

Ask for weight in pounds and height in inches, calculate body mass index with the U.S. formula (703 * weight / height ** 2) and print the category:

  • Below 18.5: "Underweight"
  • 18.5 to under 25: "Healthy weight"
  • 25 to under 30: "Overweight"
  • 30 or more: "Obesity"

If the user enters a height of 0 or less, print an error message instead of calculating.

See solution
weight = float(input("Weight (lb): "))
height = float(input("Height (in): "))

if height <= 0:
    print("Height must be greater than 0")
else:
    bmi = 703 * weight / height ** 2
    if bmi < 18.5:
        category = "Underweight"
    elif bmi < 25:
        category = "Healthy weight"
    elif bmi < 30:
        category = "Overweight"
    else:
        category = "Obesity"
    print(f"BMI: {bmi:.1f} → {category}")

With 180 lb and 70 in (5'10"), the output is BMI: 25.8 → Overweight. Here the order goes from low to high using <, which is also correct as long as each condition rules out the ones before it. BMI is only a rough screening number, not a medical diagnosis.

Summary

  • if, elif and else end with :, and their block is indented.
  • Only the first block whose condition is true runs, so order your conditions carefully.
  • Combine conditions with and, or and not; compare with None using is.
  • Empty strings, empty collections, 0 and None are falsy; match is cleaner for many specific values.
  • Always check the colon, the indentation and that each side of an or is a full comparison.

Next lesson: Python for and while Loops: range, break and continue. You'll loop over collections, use range() and accumulators, and control loops with while, break, continue and list comprehensions.

🎓 Save your progress and get a free certificate

Create your account in 30 seconds, mark your lessons and download your certificate at the end.

Enroll for free