What is Match-Case?
Python 3.10 introduced the match statement as an alternative to the traditional if-elif-else chain. It works similarly to a switch statement in other languages.
Basic Syntax
def check_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(check_status(200)) # Output: OK
print(check_status(404)) # Output: Not Found
Using Match-Case with Variables
You can use variables in cases to match specific patterns.
def check_number(num):
match num:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Other number")
check_number(1) # Output: One
Matching Multiple Values
You can match multiple values using the | operator.
def check_fruit(fruit):
match fruit:
case "apple" | "banana" | "cherry":
print("This is a fruit.")
case _:
print("Unknown item.")
check_fruit("apple") # Output: This is a fruit.
Matching Data Structures
The match statement can work with lists, tuples, and dictionaries.
def process_data(data):
match data:
case [x, y]:
print(f"List with two elements: {x}, {y}")
case {"name": name, "age": age}:
print(f"Person: {name}, Age: {age}")
case _:
print("Unknown structure")
process_data([1, 2]) # Output: List with two elements: 1, 2
process_data({"name": "Alice", "age": 30}) # Output: Person: Alice, Age: 30
Using Wildcards and Guards
Guards add extra conditions inside cases.
def check_number(num):
match num:
case x if x > 0:
print("Positive number")
case x if x < 0:
print("Negative number")
case _:
print("Zero")
check_number(-5) # Output: Negative number
Best Practices
- Use match-case for clear, readable code instead of long if-elif chains.
- Use wildcards (
_) to handle unknown cases. - Leverage pattern matching for structured data.