Python conditionals: if, elif, else and match
What you’ll build
Section titled “What you’ll build”You will build a small order-triage script for an invented shop, OrdersPortal. It reads a list of orders and decides, for each one, whether to reject it, which customer tier it belongs to, whether shipping is free and what to do about payment. Along the way you will learn:
- how to write
if,elifandelseblocks, and why indentation matters; - the comparison operators (
==,<,in,is) and logical operators (and,or,not); - which values Python treats as true or false (“truthiness”);
- the one-line conditional expression
a if condition else b; match/casefor choosing between many shapes of data.
Prerequisites
Section titled “Prerequisites”- Python 3.10 or later for
match/case; everything else works on any Python 3. The outputs on this page come from CPython 3.14.6, the current release. - You can create a variable and run a script. If not, start with variables and types.
How to run the samples: save each sample as a .py file (for example step1.py) and run python3 step1.py in a terminal. On Windows, use py step1.py. Compare what you see with the output shown under each sample.
Step 1: if, elif and else
Section titled “Step 1: if, elif and else”An if statement runs a block only when its condition is true. elif (“else if”) adds more conditions, checked in order, and else catches everything that did not match. Python runs only the first matching block.
amount = 149.99
if amount > 200: tier = "platinum"elif amount > 100: tier = "gold"elif amount > 50: tier = "silver"else: tier = "standard"
print(tier)Output:
gold149.99 is also greater than 50, but the silver branch never runs because gold matched first. That is why you order the conditions from most specific to least specific.
The colon at the end of each line and the indentation of the block are required. Python has no braces and no end if; the indented lines are the block. Use four spaces per level, which is the convention in PEP 8.
Check your work: change amount to 40 and run again. You should see standard.
Step 2: comparisons and logic
Section titled “Step 2: comparisons and logic”Conditions are usually built from comparison operators, combined with and, or and not.
amount = 150is_member = Truestatus = "pending"tags = ["sale", "gift"]
print(amount > 100 and is_member) # both must be trueprint(status == "pending" or status == "processing")print(status in ("pending", "processing")) # same test, shorterprint(not is_member)print(50 < amount < 500) # chained: 50 < amount and amount < 500print("sale" in tags, "clearance" not in tags)print(0.1 + 0.2 == 0.3) # floats are approximateOutput:
TrueTrueTrueFalseTrueTrue TrueFalse| Operator | Meaning | Example |
|---|---|---|
==, != |
Equal, not equal (by value) | status != "cancelled" |
<, <=, >, >= |
Ordering | qty >= 10 |
in, not in |
Membership in a string, list, set, dict keys… | "sale" in tags |
is, is not |
Same object (identity) | result is None |
and, or, not |
Logic | amount > 100 and is_member |
Three things worth remembering:
- Chained comparisons such as
50 < amount < 500read like math and mean50 < amount and amount < 500. - Short-circuiting:
andstops at the first false value andorat the first true one, souser and user.is_adminnever touchesuser.is_adminwhenuserisNone. - Use
isonly forNone(and other singletons such asTrue). For numbers and strings, compare values with==. The last line of the output shows why money is not usually stored asfloat: see the decimal module when exact cents matter.
Check your work: what does print(10 < 5 < 20) show? (False, because 10 < 5 is already false.)
Step 3: truthiness
Section titled “Step 3: truthiness”Any value can be used as a condition, not only True and False. Empty containers, zero, None and False count as false; almost everything else counts as true.
for value in (False, 0, 0.0, "", [], {}, set(), (), None, "0", [0], -1, " "): print(f"{value!r:>8} -> {bool(value)}")
def describe(orders: list[str]) -> str: if not orders: # empty list is falsy return "Nothing to process" return f"{len(orders)} order(s) to process"
print(describe([]))print(describe(["ORD-1001"]))
# `or` and `and` return one of their operands, not necessarily True/Falsenickname = ""print(nickname or "guest")print(None and "never evaluated")
def quantity_label(quantity: int | None) -> str: if quantity is None: # missing return "unknown" if quantity == 0: # present but zero return "out of stock" return f"{quantity} in stock"
print(quantity_label(None), "|", quantity_label(0), "|", quantity_label(7))Output:
False -> False 0 -> False 0.0 -> False '' -> False [] -> False {} -> False set() -> False () -> False None -> False '0' -> True [0] -> True -1 -> True ' ' -> TrueNothing to process1 order(s) to processguestNoneunknown | out of stock | 7 in stockif not orders: is the idiomatic way to test for an empty list. But truthiness merges different situations: 0 and None are both falsy, so if not quantity: cannot tell “out of stock” from “unknown”. When the difference matters, test explicitly, as quantity_label does.
Step 4: the conditional expression
Section titled “Step 4: the conditional expression”When you only need to choose between two values, a conditional expression (often called a ternary) fits on one line: value_if_true if condition else value_if_false.
payment_ok = Falseis_member = Trueamount = 0
status = "confirmed" if payment_ok else "failed"discount = 0.10 if is_member else 0.0label = f"${amount:.2f}" if amount > 0 else "FREE"print(status, discount, label)Output:
failed 0.1 FREEKeep both branches short. If you find yourself nesting one conditional expression inside another, write an if statement instead.
Step 5: match and case
Section titled “Step 5: match and case”match (Python 3.10, PEP 634) compares one value against a series of patterns. It is more than a switch statement: patterns can check the shape of a dict or tuple, pull values out into variables, accept alternatives with | and add an extra condition with if (a guard).
def handle_event(event: dict) -> str: match event: case {"type": "order.created", "order_id": str(order_id)}: return f"New order: {order_id}" case {"type": "payment.failed", "reason": str(reason)}: return f"Payment failed: {reason}" case {"type": "order.cancelled" | "order.refunded" as kind}: return f"Closed ({kind})" case {"type": "order.shipped", "items": int(n)} if n > 10: return "Large shipment: notify the warehouse" case {"type": "order.shipped"}: return "Shipped" case _: return f"Unknown event: {event.get('type')}"
print(handle_event({"type": "order.created", "order_id": "ORD-001"}))print(handle_event({"type": "payment.failed", "reason": "card declined"}))print(handle_event({"type": "order.refunded"}))print(handle_event({"type": "order.shipped", "items": 12}))print(handle_event({"type": "order.shipped", "items": 2}))print(handle_event({"type": "order.lost"}))Output:
New order: ORD-001Payment failed: card declinedClosed (order.refunded)Large shipment: notify the warehouseShippedUnknown event: order.lostCases are tried from top to bottom and the first match wins, just like elif. A mapping pattern matches if the listed keys are present, even when the dict has extra keys. case _: matches anything and plays the role of else. For two or three simple comparisons, plain if/elif is usually clearer; match pays off when you are taking apart structured data.
Complete working result
Section titled “Complete working result”The finished triage script combines every step: guard clauses with truthiness, an if/elif chain, a conditional expression and a match with alternatives, guards and a catch-all capture.
"""OrdersPortal order triage: decide what happens to each incoming order."""
FREE_SHIPPING_FROM = 50.00BLOCKED_COUNTRIES = {"XX"}
def classify(amount: float, is_member: bool) -> str: if amount <= 0: return "invalid" elif amount >= 500 and is_member: return "vip" elif amount >= 500: return "large" elif is_member: return "member" else: return "standard"
def triage(order: dict) -> str: # Guard clauses first: reject bad input early, keep the main path flat. if not order.get("items"): return f"{order['id']}: rejected (no items)" if order.get("country") in BLOCKED_COUNTRIES: return f"{order['id']}: rejected (cannot ship to {order['country']})"
amount = sum(price * qty for price, qty in order["items"]) tier = classify(amount, order.get("is_member", False)) if tier == "invalid": return f"{order['id']}: rejected (total {amount:.2f})"
shipping = "free" if amount >= FREE_SHIPPING_FROM or tier == "vip" else "paid"
match order.get("payment"): case "card" | "paypal": next_step = "charge now" case "invoice" if tier in ("vip", "large"): next_step = "send invoice" case "invoice": next_step = "manual review (invoice for small order)" case None: next_step = "ask for payment method" case other: next_step = f"unsupported payment {other!r}"
return f"{order['id']}: {tier}, {amount:.2f}, {shipping} shipping, {next_step}"
orders = [ {"id": "ORD-1001", "items": [(19.99, 2)], "payment": "card"}, {"id": "ORD-1002", "items": [(250.00, 3)], "is_member": True, "payment": "invoice"}, {"id": "ORD-1003", "items": [(12.50, 1)], "is_member": True, "payment": "invoice"}, {"id": "ORD-1004", "items": [], "payment": "card"}, {"id": "ORD-1005", "items": [(80.00, 1)], "country": "XX", "payment": "card"}, {"id": "ORD-1006", "items": [(0.00, 1)], "payment": "card"}, {"id": "ORD-1007", "items": [(600.00, 1)]}, {"id": "ORD-1008", "items": [(30.00, 2)], "payment": "crypto"},]
for order in orders: print(triage(order))Output:
ORD-1001: standard, 39.98, paid shipping, charge nowORD-1002: vip, 750.00, free shipping, send invoiceORD-1003: member, 12.50, paid shipping, manual review (invoice for small order)ORD-1004: rejected (no items)ORD-1005: rejected (cannot ship to XX)ORD-1006: rejected (total 0.00)ORD-1007: large, 600.00, free shipping, ask for payment methodORD-1008: standard, 60.00, free shipping, unsupported payment 'crypto'The guard clauses at the top of triage are the “early return” style: each one handles a bad case and leaves, so the normal path is not buried three levels deep in nested if blocks. case other: binds any remaining value to the name other, which is why it must come last.
Common mistakes
Section titled “Common mistakes”- Comparing with
Noneusing==. Writeif result is None:. A class can define__eq__so that== Nonegives a surprising answer;iscannot be overridden. - Relying on truthiness when
0or""is a valid value.if not discount:treats a real discount of0the same as a missing one. Testis Noneinstead. - Writing
x == "a" or "b". This is(x == "a") or "b", which is always truthy. Writex in ("a", "b"). - Putting a broad condition first. In an
elifchain,amount > 50beforeamount > 100means the second branch never runs. - Deep nesting. Three or more levels of
ifusually means guard clauses or a helper function would read better. - Using a bare name as a
matchconstant.case OK:does not compare with a variableOK; it captures any value into a new variable namedOK. Use a dotted name (case Status.OK:) or a literal. - Comparing values of different types.
"150" > 100raisesTypeError; convert input withfloat()orint()first.
Troubleshooting
Section titled “Troubleshooting”These are the real messages from Python 3.14 (file paths removed).
| Error | Cause | Fix |
|---|---|---|
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
if amount = 5: |
Use == to compare. |
SyntaxError: expected ':' on if amount > 1 |
Missing colon | Add : at the end of the line. |
SyntaxError: expected ':' on else if amount > 0: |
else if is not Python |
Write elif. |
IndentationError: expected an indented block after 'if' statement on line 2 |
The block is not indented | Indent the body by four spaces. |
IndentationError: unexpected indent |
A line is indented more than its neighbors | Line up every statement in the block. |
SyntaxError: name capture 'OK' makes remaining patterns unreachable |
case OK: with a bare name |
Use case Status.OK: or a literal such as case 200:. |
TypeError: '>' not supported between instances of 'str' and 'int' |
Comparing text from input() with a number |
Convert first: amount = float(text). |
| A string check is never true | Case differs: "Pending" == "pending" is False |
Normalize: status.lower() == "pending". |
Interview questions
Section titled “Interview questions”1. What is the difference between == and is?
== compares values and can be customized by a class’s __eq__. is checks whether two names refer to the same object. Use is for None, and == for everything else.
2. What does print([] or "empty") print, and why?
empty. or returns its first truthy operand, or the last operand if none is truthy. An empty list is falsy, so the result is the string.
3. When would you choose match over an if/elif chain?
When the decision depends on the structure of data, for example a dict’s keys or a tuple’s length, and you want to extract parts of it at the same time. For a few simple comparisons, if/elif is shorter and familiar to every reader.
4. Why is if not count: risky in a function that receives count: int | None?
It is true both for None (no value) and 0 (a real value). Code that should treat them differently must test count is None and count == 0 separately.
Next steps
Section titled “Next steps”Conditions decide whether code runs; loops decide how many times. After that, functions let you name conditions such as is_eligible(order) so long if statements read like sentences.
Related pages
Section titled “Related pages”- Operators: the full list of comparison, logical and membership operators.
- Loops:
forandwhile, which combine withif,breakandcontinue. - Control flow tutorial: conditions and loops together in one walkthrough.
- Walrus operator (
:=): assign and test a value in one condition. - Exceptions: when to raise an error instead of returning a status string.
Official references
Section titled “Official references”- Python tutorial: if statements (Python 3.14)
- Python tutorial: match statements (Python 3.14)
- Truth value testing (Python 3.14)
- Language reference: comparisons, Boolean operations and conditional expressions (Python 3.14)
- Language reference: the if and match statements (Python 3.14)
- PEP 636: Structural Pattern Matching tutorial and PEP 634: specification