Contents

Python Match Case statement

Introduction to match case statement: syntax, usage and benefits

Website Visitors:

Match case in Python

In Python, the match case statement is a new feature introduced in version 3.10 that allows for concise and readable pattern matching. It can be used as an alternative to if-elif-else chains or switch statements. This statement evaluates an expression and matches it against patterns specified in the case clauses. In this article, we will discuss the syntax, usage, and benefits of the match case statement.

Syntax of Match Case Statement

The syntax of the match case statement in Python is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
match expression:
    case pattern_1:
        statement(s)
    case pattern_2:
        statement(s)
    ...
    case pattern_n:
        statement(s)
    [case _:]
        statement(s)

Here, the expression is the value that will be matched against the pattern specified in the case clauses. The pattern can be any Python expression, including literals, variables, and functions. The statement(s) under each case clause will be executed if the pattern matches the expression.

The case _: clause is a catch-all pattern that matches any value. It is optional and can be used as a default case. If your expression does not match any value then the default case will be used.

Example Usage of Match Case Statement

Here is an example of using the match case statement in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def calculate(x, operator, y):
    match operator:
        case '+':
            return x + y
        case '-':
            return x - y
        case '*':
            return x * y
        case '/':
            return x / y
        case _:
            raise ValueError(f"Invalid operator '{operator}'")

print(calculate(10, '+', 5))  # Output: 15
print(calculate(10, '-', 5))  # Output: 5
print(calculate(10, '*', 5))  # Output: 50
print(calculate(10, '/', 5))  # Output: 2.0
print(calculate(10, '%', 5))  # Output: ValueError: Invalid operator '%'

In this example, the calculate function takes three arguments x, operator, and y. The match case statement is used to evaluate the operator argument and perform the corresponding mathematical operation.

If the operator is not one of the four expected values, the catch-all pattern is used to raise a ValueError with a custom message.

Here are a few more examples of using the match case statement in Python:

Example 1: Matching on Type

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def print_value(value):
    match type(value):
        case str:
            print(f"Value is a string: {value}")
        case int:
            print(f"Value is an integer: {value}")
        case float:
            print(f"Value is a float: {value}")
        case _:
            print("Value is of an unrecognized type")

print_value("Hello, world!")   # Output: Value is a string: Hello, world!
print_value(42)                # Output: Value is an integer: 42
print_value(3.14)              # Output: Value is a float: 3.14
print_value([1, 2, 3])         # Output: Value is of an unrecognized type

In this example, the print_value function takes a single argument value and matches on its type using the match case statement. The appropriate message is printed depending on the type of value. If the type is not recognized, a catch-all pattern is used to print a generic message.

Example 2: Matching on Values and Conditions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def calculate_grade(score):
    match score:
        case 90 <= score <= 100:
            return 'A'
        case 80 <= score < 90:
            return 'B'
        case 70 <= score < 80:
            return 'C'
        case 60 <= score < 70:
            return 'D'
        case score < 60:
            return 'F'
        case _:
            raise ValueError(f"Invalid score: {score}")

print(calculate_grade(95))    # Output: A
print(calculate_grade(85))    # Output: B
print(calculate_grade(75))    # Output: C
print(calculate_grade(65))    # Output: D
print(calculate_grade(55))    # Output: F
print(calculate_grade(110))   # Output: ValueError: Invalid score: 110

In this example, the calculate_grade function takes a single argument score and matches on its value and conditions using the match case statement. The appropriate letter grade is returned based on the score. If the score is not within the expected range, a catch-all pattern is used to raise a ValueError with a custom message.

Example 3: Matching on Multiple Expressions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def calculate_tax(income, status):
    match income, status:
        case (0 <= income <= 10000), 'single':
            return 0
        case (0 <= income <= 20000), 'married':
            return 0
        case (income <= 40000), 'single':
            return 0.1 * income
        case (income <= 60000), 'married':
            return 0.1 * income
        case (income > 40000), 'single':
            return 0.2 * income
        case (income > 60000), 'married':
            return 0.2 * income
        case _:
            raise ValueError(f"Invalid income or status")

print(calculate_tax(8000, 'single'))   # Output: 0
print(calculate_tax(15000, 'married')) # Output: 0
print(calculate_tax(25000, 'single'))  # Output: 2500.0
print(calculate_tax(50000, 'married')) # Output: 5000.0
print(calculate_tax(80000, 'single'))  # Output: 16000.0

In this example, the calculate_tax function takes two arguments income and status and matches on both expressions using the match case statement. The appropriate tax rate is returned based on the income and status of the taxpayer. If the income or status is not recognized, a catch-all pattern is used to raise a ValueError with a custom message.

These are just a few examples of using the match case statement in Python. You can use match case statements to simplify code that would otherwise require complex branching logic. It is also a more concise and readable alternative to using nested if-else statements.

Benefits of Match Case Statement

The match case statement offers several benefits over if-elif-else chains and switch statements. Here are some of the advantages of using the match case statement:

  • Readability: The match case statement is more concise and easier to read than a long chain of if-elif-else statements.

  • Type checking: The match case statement allows for type checking and type annotations, making the code more robust and less prone to errors.

  • Versatility: The match case statement can match any expression, not just simple values, which makes it more versatile than a switch statement.

  • Extensibility: The match case statement can be extended with custom matchers and patterns, making it more flexible than a switch statement.

Suggested Article

If you’d like to continue reading, checkout our other python commands article here or browse all other topics here.

Conclusion

The match case statement is a new feature introduced in Python 3.10 that offers a more concise and readable alternative to if-elif-else chains and switch statements. It allows for pattern matching on any expression and can be extended with custom matchers and patterns. By using the match case statement, you can write more robust and maintainable code that is easier to read and understand.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.