🧩 Python Match–Case — The Modern Switch Statement in Python
Introduction 🌟
The match–case statement (introduced in Python 3.10) is a powerful pattern-matching feature similar to the switch-case found in other languages. It allows you to compare a value against multiple patterns in a clean, readable way.
Note
💡 match–case is more powerful than traditional switch-case because it supports patterns, conditions, variable binding, and even data structure matching.
1. Basic Match–Case Structure 🧱
basic_match.py
choice = 2
match choice:
case 1:
print("Option 1 selected")
case 2:
print("Option 2 selected")
case 3:
print("Option 3 selected")
case _:
print("Invalid option")✔️ _ is the default case (like else).
✔️ Only the first matching case executes.
2. Match–Case With Strings 🔤
string_match.py
day = "monday"
match day.lower():
case "monday":
print("Start of the week")
case "friday":
print("Weekend is near!")
case "sunday":
print("Relax day 😎")
case _:
print("Regular day")3. Match Multiple Values in One Case 🎯
multiple_values.py
fruit = "apple"
match fruit:
case "apple" | "banana" | "mango":
print("This is a popular fruit")
case _:
print("Unknown fruit")Note
✔️ Use | to match multiple options in one case.
4. Match–Case With Conditions (Guards) 🛡️
Use if inside case patterns to apply extra conditions.
case_guard.py
num = 15
match num:
case n if n > 0:
print("Positive number")
case n if n < 0:
print("Negative number")
case _:
print("Zero")5. Matching Data Structures 🧩
Matching Lists
list_match.py
items = [1, 2, 3]
match items:
case [1, 2, 3]:
print("Exact match")
case [1, *rest]:
print("Starts with 1:", rest)
case _:
print("No match")Matching Tuples
tuple_match.py
point = (10, 20)
match point:
case (0, 0):
print("Origin")
case (x, y):
print(f"Point at ({x}, {y})")Note
✔️ Patterns can extract values directly into variables.
6. Match–Case With Classes (Advanced Pattern Matching) 🧠
class_match.py
class Animal:
def __init__(self, name):
return None
class Dog(Animal): pass
class Cat(Animal): pass
pet = Dog()
match pet:
case Dog():
print("It's a dog")
case Cat():
print("It's a cat")
case _:
print("Unknown animal")7. Match–Case vs If–Else 🔍
| Feature | If–Else | Match–Case |
|---|---|---|
| Multiple comparisons | Long and repetitive | Clean and readable |
| Pattern matching | Not supported | Supported |
| Extracting values | Manual work | Automatic binding |
| Default case | else | case _ |
8. Real-World Example 🌍
real_world_example.py
status = 404
match status:
case 200:
print("OK")
case 400:
print("Bad Request")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown status code")Conclusion 🎉
>>“Match–case is Python’s most powerful decision-making tool — clean, readable, and pattern-driven.” ✨
You now understand the match–case statement! Want the next topic? Try Loops, While Loop, For Loop, Range Function, or Control Flow. Just tell me! 😊