Python – Match-Case Statement

In the world of programming, decision-making is a fundamental aspect. Developers often need to execute different blocks of code based on specific conditions. In Python, the traditional approach to decision-making is through if-elif-else statements. However, starting from Python 3.10, a new feature called the match-case statement has been introduced. This statement provides a more concise and readable way to handle multiple conditions. In this article, we will explore the match-case statement in Python and provide examples to illustrate its usage.

What is the Match-Case Statement?

The match-case statement in Python is a new syntax that allows developers to match a value against a series of patterns and execute the corresponding block of code based on the matched pattern. It is similar to the switch-case statement found in other programming languages. The match-case statement provides a more structured and efficient way to handle multiple conditions, especially when dealing with complex data structures.

How to Use the Match-Case Statement

To use the match-case statement, you need to follow a specific syntax. Let’s take a look at the general structure:

match expression:
    case pattern_1:
        # code block for pattern_1
    case pattern_2:
        # code block for pattern_2
    ...
    case pattern_n:
        # code block for pattern_n
    case _:
        # code block for unmatched patterns

The expression is the value that you want to match against the patterns. The case keyword is followed by the pattern that you want to match. Each pattern can have multiple values separated by commas. The _ is a special pattern that matches any value. It is used as a catch-all for unmatched patterns.

Now, let’s dive into some examples to see how the match-case statement works.

Example 1: Matching Integer Values

def check_number(num):
    match num:
        case 0:
            print("The number is zero.")
        case 1, 2, 3:
            print("The number is a small positive integer.")
        case _:
            print("The number is neither zero nor a small positive integer.")

In this example, the check_number function takes an integer num as input. The match-case statement is used to determine the category of the number. If the number is zero, it prints “The number is zero.” If the number is 1, 2, or 3, it prints “The number is a small positive integer.” Otherwise, it prints “The number is neither zero nor a small positive integer.”

Example 2: Matching Strings

def check_string(string):
    match string:
        case "apple":
            print("The string is 'apple'.")
        case "banana":
            print("The string is 'banana'.")
        case "cherry", "grape", "orange":
            print("The string is a fruit.")
        case _:
            print("The string is not recognized.")

In this example, the check_string function takes a string string as input. The match-case statement is used to identify the type of string. If the string is “apple”, it prints “The string is ‘apple’.” If the string is “banana”, it prints “The string is ‘banana’.” If the string is “cherry”, “grape”, or “orange”, it prints “The string is a fruit.” Otherwise, it prints “The string is not recognized.”

Example 3: Matching Data Structures

def check_data(data):
    match data:
        case [0, 1]:
            print("The data is a list containing 0 and 1.")
        case {"name": "John", "age": 30}:
            print("The data is a dictionary with name 'John' and age 30.")
        case (True, False):
            print("The data is a tuple with True and False.")
        case _:
            print("The data does not match any known pattern.")

In this example, the check_data function takes a data structure data as input. The match-case statement is used to identify the specific pattern of the data. If the data is a list containing 0 and 1, it prints “The data is a list containing 0 and 1.” If the data is a dictionary with the name “John” and age 30, it prints “The data is a dictionary with name ‘John’ and age 30.” If the data is a tuple with True and False, it prints “The data is a tuple with True and False.” Otherwise, it prints “The data does not match any known pattern.”

Conclusion

The match-case statement in Python provides a more concise and readable way to handle multiple conditions. It simplifies decision-making and improves code readability, especially when dealing with complex data structures. By understanding the syntax and examples provided in this article, you can start using the match-case statement in your Python programs and take advantage of its benefits.

Scroll to Top