Python introduced the match statement in version 3.10.
It provides a clear and structured way to handle multiple conditions by matching a value against different patterns.
Think of match as a more expressive alternative to long if–elif–else chains.
Why the match Statement Exists
Before match, handling many conditions looked like this:
if command == "start":
start_app()
elif command == "stop":
stop_app()
elif command == "restart":
restart_app()
else:
print("Invalid command")This works, but it does not scale well.
As conditions grow, readability drops and logic becomes fragile.
The match statement solves this problem.
Basic Syntax
match variable:
case pattern1:
# code
case pattern2:
# code
case _:
# default casematchevaluates the variablecasechecks patterns_acts likeelse(catch-all case)
Simple Example
1command = "start"
2
3match command:
4 case "start":
5 print("Application started")
6 case "stop":
7 print("Application stopped")
8 case "restart":
9 print("Application restarted")
10 case _:
11 print("Unknown command")Output:
Application startedMatching Multiple Values
You can match multiple patterns in one case.
1status_code = 404
2
3match status_code:
4 case 200 | 201:
5 print("Success")
6 case 400 | 404:
7 print("Client error")
8 case 500:
9 print("Server error")
10 case _:
11 print("Unknown status")This removes repetitive conditions and improves clarity.
Matching with Conditions (Guards)
Guards allow additional logic using if.
1age = 20
2
3match age:
4 case x if x < 18:
5 print("Minor")
6 case x if x >= 18 and x < 60:
7 print("Adult")
8 case _:
9 print("Senior")The match statement checks the pattern first, then the condition.
Matching Data Structures
The real power of match appears when working with tuples and lists.
1point = (0, 5)
2
3match point:
4 case (0, 0):
5 print("Origin")
6 case (0, y):
7 print(f"On Y-axis at {y}")
8 case (x, 0):
9 print(f"On X-axis at {x}")
10 case (x, y):
11 print(f"Point at {x}, {y}")This is called structural pattern matching.
When You Should Use match
Use match when:
- You have many discrete cases
- You are matching structured data
- Readability matters more than quick hacks
- You want predictable control flow
Avoid match when:
- You only have one or two conditions
- Logic depends heavily on ranges without structure
Key Rules You Must Remember
- Python checks cases top to bottom
- The first matching case is executed
_should always be the last casematchis not a switch clone—it is more powerful
Conclusion
The match statement is not syntactic sugar. It represents a shift toward declarative, readable logic. If you misuse it, your code becomes clever garbage. If you use it correctly, your intent becomes obvious—and obvious code is professional code.
