Python | Match – Case Statement

Python | Match – Case Statement

Python 3.10 introduces the match-case statement, a powerful feature inspired by pattern matching in functional programming languages. This addition enhances the readability and expressiveness of Python code, providing a concise and effective way to handle complex conditional logic. In this article, we’ll explore the match case statement in Python 3.10, explain its syntax and functionality through examples.

Understanding Match Case:

The match case statement in Python serves as an evolution of the traditional switch statement, allowing developers to match patterns. It introduces a more structured and readable way to handle multiple cases, replacing the need for long chains of if-elif-else statements.

Basic Syntax:
The basic syntax of the match case statement resembles as switch statement but offers more flexibility:

match value:
    case pattern1:
        # Code to execute if value matches pattern1
    case pattern2:
        # Code to execute if value matches pattern2
    case _:
        # Code to execute for any other case

Here wildcard ‘_’ in the match case statement allows for matching any other case.
Example 1: Let’s start with a simple example that demonstrates the match case statement with constants:

def describe_color(color):
    match color:
        case "red":
            return "It's a passionate color."
        case "blue":
            return "It's a calming color."
        case "green":
            return "It's a color of nature."
        case _:
            return "I don't know that color."

print(describe_color("blue")) # output: It's a calming color.

Example 2: Example of determining whether a number is even or odd:

def is_even_or_odd(number):
    match number % 2:
        case 0:
            return "Even"
        case 1:
            return "Odd"
        case _:
            return "Not an integer"

print(is_even_or_odd(7)) # output: Odd


The match case statement in Python 3.10 brings a significant improvement to the language, providing a more expressive and concise way to handle complex conditional logic. With its ability to match patterns the match case statement enhances code readability and maintainability. As Python continues to evolve, features like match case demonstrate the language’s commitment to empowering developers with modern and efficient tools.

Leave a Reply

Your email address will not be published.