Course topics

By WebNest Studio

Python Tutorial

Conditional Statements: if, elif, else and match

Programs make decisions constantly: is the user logged in, did the payment succeed, which discount applies? Python's if, elif and else statements run different code depending on conditions, the conditional expression puts a decision in a single line, and the match statement (Python 3.10+) matches values against patterns.

This lesson covers every form of conditional in Python with practical examples.

if, elif and else

An if block runs when its condition is truthy. Add any number of elif branches, checked top to bottom — the first truthy one runs and the rest are skipped — and an optional else for everything else. Blocks are defined by indentation (4 spaces). Conditions can be combined with and, or and not, and chained comparisons such as 0 <= score <= 100 read naturally.

Nested Conditions and Guard Clauses

An if can contain another if, but deep nesting is hard to read. Prefer guard clauses: handle invalid cases first and return early, leaving the main logic un-indented.

Conditional Expressions

The ternary form value_if_true if condition else value_if_false chooses between two values in one expression: status = "adult" if age >= 18 else "minor". Use it for simple choices only.

match-case (Structural Pattern Matching)

match compares a value against case patterns: literal values, alternatives with |, the wildcard _, sequence patterns that unpack lists, mapping patterns for dicts, class patterns, and guards with if. It is more powerful than a switch statement in other languages and ideal for parsing commands or structured data.

Examples

Grading with if / elif / else

Python
def grade(score):
    if not 0 <= score <= 100:
        return "invalid"
    if score >= 90:
        return "A"
    elif score >= 75:
        return "B"
    elif score >= 50:
        return "C"
    else:
        return "F"

for s in [95, 80, 62, 30, 120]:
    print(s, grade(s))
Output
95 A
80 B
62 C
30 F
120 invalid

Combined conditions, guard clauses and the ternary expression

Python
def ticket_price(age, is_student, day):
    if age < 0:
        return None                       # guard clause
    base = 0 if age < 5 else 200
    if (age >= 60 or is_student) and day != "Sunday":
        base *= 0.5
    return base

print(ticket_price(3, False, "Monday"))
print(ticket_price(21, True, "Monday"))
print(ticket_price(21, True, "Sunday"))
print(ticket_price(65, False, "Friday"))

n = 7
print("even" if n % 2 == 0 else "odd")
Output
0
100.0
200
100.0
odd

match-case with literals, sequences, mappings and guards

Python
def handle(command):
    match command.split():
        case ["quit" | "exit"]:
            return "Goodbye"
        case ["add", item]:
            return f"Adding {item}"
        case ["add", item, qty] if qty.isdigit():
            return f"Adding {qty} x {item}"
        case ["remove", *items] if items:
            return f"Removing {', '.join(items)}"
        case _:
            return "Unknown command"

for c in ["add pen", "add pen 3", "remove pen book", "exit", "dance"]:
    print(handle(c))

def describe(event):
    match event:
        case {"type": "payment", "amount": amount} if amount > 10000:
            return f"Large payment: {amount}"
        case {"type": "payment", "amount": amount}:
            return f"Payment: {amount}"
        case {"type": "refund"}:
            return "Refund"
        case _:
            return "Other"

print(describe({"type": "payment", "amount": 25000}))
print(describe({"type": "payment", "amount": 500}))
print(describe({"type": "refund", "id": 7}))
Output
Adding pen
Adding 3 x pen
Removing pen, book
Goodbye
Unknown command
Large payment: 25000
Payment: 500
Refund

Common Mistakes

  • Using = instead of == in a condition (a SyntaxError in Python, which prevents the classic C bug).
  • Ordering elif conditions wrongly, e.g. checking score >= 50 before score >= 90.
  • Deeply nesting ifs instead of using guard clauses.
  • Using match on Python versions older than 3.10.
  • Forgetting the case _ fallback, so unmatched values silently do nothing.

Key Points to Remember

  • if/elif/else checks conditions top to bottom and runs the first match.
  • Chained comparisons like 0 <= x <= 100 and guard clauses keep code readable.
  • x if cond else y is a one-line conditional expression.
  • match-case supports literal, sequence, mapping and class patterns with guards (3.10+).

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.