Pattern Matching (match-case)
In Python 3.10, developers got a modern feature called match-case (known as switch-case in Java/C++).
It is designed as a cleaner, more readable replacement for long, messy if-elif-else chains when you are comparing a single variable against exact matching values.
1. Why match-case? (Messy elif vs Clean match-case)
Imagine checking a user's role on a website:
❌ Messy if-elif Chain:
role = "admin"
if role == "admin":
print("Full Access Allowed")
elif role == "editor":
print("Edit Access Allowed")
elif role == "viewer":
print("Read Only Access")
else:
print("Unknown Role")
✅ Clean match-case Replacement:
role = "admin"
match role:
case "admin":
print("Full Access Allowed")
case "editor":
print("Edit Access Allowed")
case "viewer":
print("Read Only Access")
case _:
print("Unknown Role") # _ is the wildcard default (like else!)
2. Key Features of match-case
-
case _:(Wildcard Default)
The underscore (_) acts as a fallbackelseblock. If none of the specific cases match,case _:runs. -
case "B" | "C":(Multiple Matches / OR)
The pipe symbol (|) allows matching multiple values in a single case!
grade = "B"
match grade:
case "A":
print("Excellent performance!")
case "B" | "C":
print("Good job, keep it up!") # Matches B or C
case "F":
print("Work hard and try again.")
case _:
print("Invalid grade!")
3. Shortcut: Inline if-else (Ternary Operator)
Sometimes you want to assign a value to a variable based on a simple check in a single line:
# Syntax: <value_if_true> if <condition> else <value_if_false>
marks = 45
result = "Pass" if marks >= 35 else "Fail"
print(result) # Output: Pass
Quick Summary
match-case(Python 3.10+): Structural pattern matching syntax for comparing a variable against exact values.- Wildcard Fallback (
case _:): Runs as the default fallback when no other cases match. - Or Patterns (
|): Combine multiple possible matches in a single case line (e.g.,case "B" | "C":). - Ternary Operator: Clean inline one-line condition (
value_if_true if condition else value_if_false).
What's Next?
Congratulations on completing Module 5! Now that we know how to make decisions in code, let's learn how to repeat tasks automatically using Loops (for, while) in Module 6!