Not just values — conditions too
The problem...
You know how to match exact values. But sometimes a value alone isn't enough.
You need to match a range. A condition. Not just "is it this?" — but "is it this, and also that?"
The idea!
match / case supports guards — an extra condition added to a case with if. The case only matches if both the value pattern and the guard condition are true.
The syntax
match value:
case pattern if condition:
# runs if pattern matches AND condition is True
Guards in action
score = int(input("Enter your score: "))
match score:
case n if n >= 90:
print("Excellent.")
case n if n >= 70:
print("Good.")
case n if n >= 60:
print("Passed.")
case _:
print("Failed.")
n captures the value of score. The guard if n >= 90 adds the condition. Together — pattern and guard — decide if the case runs.
Matching on type
value = input("Enter something: ")
match value:
case v if v.isdigit():
print(f"{v} is a number.")
case v if v.isalpha():
print(f"{v} is a word.")
case _:
print("Mixed or unknown.")
Same value — different behavior based on what it contains. No long if / elif chain needed.
Guards with multiple conditions
age = int(input("Enter your age: "))
has_id = input("Do you have ID? (y/n): ")
match age:
case n if n >= 18 and has_id == "y":
print("Access granted.")
case n if n >= 18 and has_id != "y":
print("ID required.")
case _:
print("Access denied — too young.")
Guards can combine conditions with and, or, not — just like if.
match vs if / elif — when to use which
# match — clean when checking one variable against many values
match command:
case "quit" | "exit":
print("Leaving.")
case "help":
print("Help.")
case _:
print("Unknown.")
# if / elif — still better for complex, unrelated conditions
if score > 90 and attendance > 80:
print("Honours.")
elif score > 60:
print("Passed.")
match shines when you're checking one variable. if / elif is still the right tool when conditions involve multiple variables or complex logic.
Heads up!
- Guards use
ifafter the pattern —case n if n > 0 - The variable in the pattern (
n,v) captures the matched value - Guards can use
and,or,not matchis not always better thanif / elif— use the right tool
The mindset shift
Stop thinking: "match only checks exact values."
Start thinking: "match checks values — guards check conditions. Together they're powerful."
What you should understand now
- Guards add conditions to a case —
case n if condition - The pattern variable captures the matched value for use in the guard
- Guards combine with
and,or,not - Use
matchfor one variable, many cases —if / eliffor complex logic