By WebNest Studio Engineering Team
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.
Why it matters
Business rules are conditions: discounts by order size, access by role, grades by score. Writing them so that they are correct and still readable when there are ten of them is a real skill. Guard clauses and match are the tools that keep such code from becoming a deep nest of if statements.
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
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))
95 A
80 B
62 C
30 F
120 invalid
Combined conditions, guard clauses and the ternary expression
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")
0
100.0
200
100.0
odd
match-case with literals, sequences, mappings and guards
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}))
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.
Exercise
Write a function that returns a grade for a score: A for 90 or more, B for 75 or more, C for 50 or more, and F otherwise.
Expected output: A, B, F (one per line)
def grade(score):
# TODO: return "A", "B", "C" or "F"
pass
print(grade(92))
print(grade(75))
print(grade(40))
Show hints
- Test the highest boundary first, then use
eliffor each lower one. - Because the conditions are checked in order,
elif score >= 75is only reached when the score is below 90.
Show solution
def grade(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 50:
return "C"
else:
return "F"
print(grade(92))
print(grade(75))
print(grade(40))
Quick quiz
1. Which is a valid conditional expression?
- A. x = b if a else c
- B. x = a ? b : c
- C. x = if a then b else c
- D. x = a and then b
Show answer
A. The value comes first, then the condition, then the alternative.
2. In a match statement, what does case _: do?
- A. Matches only an underscore
- B. Matches anything; it is the default case
- C. Ends the match
- D. Raises an error
Show answer
B. The underscore is a wildcard and is placed last.
3. From which Python version is match available?
- A. 2.7
- B. 3.6
- C. 3.10
- D. 3.12
Show answer
C. Structural pattern matching was added in Python 3.10.
Interview questions
Does Python have a switch statement?
Show answer
Since Python 3.10 it has match, which is more powerful than a traditional switch: besides comparing with fixed values, a case can describe the shape of a list, dictionary or object and extract parts of it. In earlier versions the same job is done with an if / elif chain or with a dictionary that maps each value to a function.
What is a guard clause?
Show answer
A guard clause is a check at the start of a function that handles an invalid or special case and returns at once. With the special cases dealt with first, the main logic follows without being nested inside several if blocks, which makes the function easier to read.
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 in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering