The match
statement is a feature introduced in Python 3.10, enabling a clean and powerful way to perform pattern matching. It is similar to a switch-case statement found in other programming languages but more versatile.
The match
statement evaluates the value of a variable (or expression) against multiple patterns defined in case
blocks. When a match is found, the corresponding block of code is executed. If no match is found, a default case (case _
) can be used.
Syntax:
match variable:
case pattern1:
# Code to execute if pattern1 matches
case pattern2:
# Code to execute if pattern2 matches
...
case _:
# Code to execute if no patterns match (default case)
Example:
x = 4 # x is the variable to match
match x:
case 0:
print("x is zero") # This will execute if x == 0
case 4:
print("x is 4") # This will execute if x == 4
case _ if x < 10:
print("x is less than 10") # This will execute for x < 10
case _:
print("No match found") # Default case
# Output: x is 4
Advantages of Match Case
-
Readable Code:
It is more readable and concise compared to multiple
if-elif-else
statements. -
Flexible Matching:
It supports both value and condition-based matching, making it highly versatile.
-
Default Case Handling:
The
_
wildcard provides a straightforward way to handle unmatched cases.