Python 3.10 introduced the match
statement, which is also referred to as the "structural pattern matching" feature. This feature is similar to a switch or case statement found in other programming languages and allows you to compare a value against multiple patterns and execute code based on the first pattern that matches. It's a powerful addition to Python that simplifies code readability and makes it more expressive when dealing with complex conditional logic.
Basic Syntax
match expression:
case pattern_1:
# Code to execute if the expression matches pattern_1
case pattern_2:
# Code to execute if the expression matches pattern_2
case pattern_3 if condition:
# Code to execute if the expression matches pattern_3 and the condition is True
case _:
# Code to execute if none of the above patterns match
- expression
: This is the value you want to match against various patterns.
- case
: This keyword introduces a pattern and code block for that pattern.
- pattern_1
, pattern_2
, etc.: These are the patterns that you want to match the expression
against.
- if condition
: You can add an optional condition after a pattern to further refine when that pattern should match.
- case _
: The underscore _
acts as a catch-all pattern. If none of the previous patterns match, the code under this case will execute.
Example:
Let's create a simple example to illustrate how the match
statement works. We'll use it to classify the type of a geometric shape based on the number of sides it has.
def classify_shape(sides):
match sides:
case 3:
return "Triangle"
case 4:
return "Quadrilateral"
case 5:
return "Pentagon"
case 6:
return "Hexagon"
case _:
return "Polygon with more than 6 sides"
In this example:
- classify_shape
takes the number of sides as input.
- The match
statement checks the sides
variable against different patterns.
- If the sides
variable matches one of the patterns, the corresponding code block is executed.
- If none of the patterns match, the catch-all case will be executed, returning "Polygon with more than 6 sides."
print(classify_shape(3)) # Output: "Triangle"
print(classify_shape(4)) # Output: "Quadrilateral"
print(classify_shape(8)) # Output: "Polygon with more than 6 sides"
As you can see, the match
statement makes it clear and concise to handle multiple cases based on a value, enhancing code readability and maintainability.
The Python match
statement is a powerful addition to the language, especially when dealing with complex conditional logic and multiple branching scenarios.