Introduced in Python 3.10, the match case statement provides a robust mechanism for pattern matching, allowing for more expressive and readable conditional checks. Compared to traditional if-elif-else chains, which can become complex in intricate situations, the match case structure offers an elegant and flexible solution.

Basic example

def check_number(x):
    match x:
        case 10:
            print("It's 10")
        case 20:
            print("It's 20")
        case _:
            print("It's neither 10 nor 20")

check_number(10)  # Output: "It's 10"
check_number(30)  # Output: "It's neither 10 nor 20"

Explanation:

The function check_number(x) compares the value of x with the constants 10 and 20. If no case matches, the wildcard _ (equivalent to default in other languages) executes the default action.

Syntax of the match case Statement

match value:
    case pattern1:
        # Block executed if pattern1 matches
    case pattern2:
        # Block executed if pattern2 matches
    case _:
        # Default case (if no other matches)
  • match value: The variable or value to be compared.

  • case pattern: The structure that defines the pattern to be matched.

  • _ (Wildcard): Generic case for unmatched values.

Practical applications

1. Matching Constants

Useful for directly checking fixed values:

def greet(name):
    match name:
        case "Ana":
            print("Hello, Ana!")
        case "John":
            print("Hi, John!")
        case _:
            print("Hello, visitor!")

greet("Ana")  # Output: "Hello, Ana!"
greet("Maria")  # Output: "Hello, visitor!"

2. Using the | (OR) Operator

Allows combining multiple patterns in a single case:

def check_number(num):
    match num:
        case 10 | 20 | 30:
            print(f"Value {num} recognized.")
        case _:
            print("Unknown value.")

check_number(20)  # Output: "Value 20 recognized."
check_number(15)  # Output: "Unknown value."

3. Adding Conditions with if

Incorporates additional checks within a case:

def check_even(num):
    match num:
        case 10 if num % 2 == 0:
            print("10 is even!")
        case 10:
            print("10 is not even? That's impossible.")
        case _:
            print("Another number.")

check_even(10)  # Output: "10 is even!"

4. Working with Sequences (Lists, Tuples)

Matches the structure and elements of sequences:

def process_data(data):
    match data:
        case [x, y]:
            print(f"List with two elements: {x}, {y}")
        case [x, y, z]:
            print(f"List with three elements: {x}, {y}, {z}")
        case _:
            print("Invalid format.")

process_data([1, 2])  # Output: "List with two elements: 1, 2"

5. Matching Dictionaries

Checks keys and values in mapping structures:

def describe_person(person):
    match person:
        case {"name": name, "age": age}:
            print(f"{name} is {age} years old.")
        case {"name": name}:
            print(f"{name}, age unknown.")
        case _:
            print("Incomplete data.")

describe_person({"name": "Carlos", "age": 30})  # Output: "Carlos is 30 years old."

6. Classes and Objects

Matches class instances and extracts attributes:

class Shape:
    pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

def describe_shape(shape):
    match shape:
        case Circle(radius=radius):
            print(f"Circle with radius {radius}.")
        case Rectangle(width=width, height=height):
            print(f"Rectangle {width}x{height}.")
        case _:
            print("Unknown shape.")

circle = Circle(5)
describe_shape(circle)  # Output: "Circle with radius 5."

Advantages of match case

  • Readability: Simplifies complex conditional structures.

  • Flexibility: Works with various data types (lists, dictionaries, objects).

  • Safety: Ensures handling of unexpected cases with the wildcard _.

Frequently Asked Questions (FAQs)

1. What is the difference between match case and if-elif-else?

The match case statement allows structural matching (not just values), making it more expressive for complex patterns.

2. Does match case replace switch case?

Yes, but with advanced features like pattern matching within data structures.

3. Is using the wildcard _ mandatory?

No, but it is recommended to handle uncovered cases and prevent errors.

Conclusion

The match case statement is a valuable addition to Python, ideal for simplifying complex conditional checks. With practice, you can fully explore its potential to write clearer and more efficient code. Try using it in your projects!

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/how-to-use-the-match-case-statement-in-python/