match case¶
- The
match-case
statement, introduced in Python 3.10, provides a powerful and readable way to perform pattern matching and conditional branching in your code. It offers an alternative to traditionalif-elif-else
chains, especially when dealing with complex conditions or working with data structures like dictionaries and tuples.match expression: case pattern1: # Code to execute if expression matches pattern1 case pattern2: # Code to execute if expression matches pattern2 case _: # Wildcard pattern (optional) # Code to execute if no other pattern matches
- Explanation
match expression
: This specifies the value you want to match against different patterns. It can be a variable, a function call, or any expression that evaluates to a value.case pattern1
: Eachcase
block defines a pattern to match against the expression. Patterns can be literals (like numbers, strings), variables, or more complex structures like ranges, class instances, or combinations using operators like|
(or) and&
(and).- If the
expression
matchespattern1
, the indented code block below it is executed.
- If the
case pattern2
(optional): You can have multiplecase
blocks to check for different patterns.- The interpreter tries to match the
expression
against each pattern in the order they appear. The first successful match (based on pattern types and values) executes its corresponding code.
- The interpreter tries to match the
case _
(optional): The wildcard pattern (_
) acts as a catch-all case and is executed if none of the preceding patterns match.
- Explanation
- Advantages of match-case
- Readability: Can simplify complex conditional logic compared to nested
if-elif-else
chains. - Exhaustiveness Checking: Some IDEs can help ensure all possible cases are handled by checking for unused patterns.
- Pattern Matching: Facilitates working with data structures by allowing pattern matching on their elements.
- Readability: Can simplify complex conditional logic compared to nested
- When to Use match-case
- When you have multiple conditions to check based on a single value or structure.
- When the conditions involve complex patterns or comparisons.
- When code readability and maintainability are important.
- Considerations
match-case
is a relatively new feature (Python 3.10+).- If compatibility with older Python versions is a concern,
if-elif-else
might be preferable. - While
match-case
offers benefits, it's not always a strict replacement forif-elif-else
. - Choose the approach that best suits your specific case
In [ ]:
Copied!
from random import randint
grade = randint(50, 100)
match grade:
case grade if 90 <= grade <= 100:
print("Excellent! You got an A.")
case grade if 80 <= grade < 90:
print("Great job! You got a B.")
case grade if 70 <= grade < 80:
print("You got a C. Keep practicing!")
case _:
print("Study hard! You got a D or below.")
from random import randint
grade = randint(50, 100)
match grade:
case grade if 90 <= grade <= 100:
print("Excellent! You got an A.")
case grade if 80 <= grade < 90:
print("Great job! You got a B.")
case grade if 70 <= grade < 80:
print("You got a C. Keep practicing!")
case _:
print("Study hard! You got a D or below.")