Python Basics

Python Match

Match case statements

Python Match

Python 3.10 introduced the match statement, which provides a more powerful way to handle multiple conditions compared to if-elif-else chains.

Match Statement

The match statement is similar to a switch statement in other languages. It allows you to match a value against multiple patterns:

x = 3

match x:
    case 1:
        print("One")
    case 2:
        print("Two")
    case 3:
        print("Three")
    case _:
        print("Other")

Multiple Values

You can match multiple values in a single case:

x = 2

match x:
    case 1 | 2 | 3:
        print("Small number")
    case 4 | 5 | 6:
        print("Medium number")
    case _:
        print("Large number")

Pattern Matching with Variables

You can also capture values in patterns:

point = (1, 2)

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"On Y-axis at {y}")
    case (x, 0):
        print(f"On X-axis at {x}")
    case (x, y):
        print(f"Point at ({x}, {y})")

Note: The match statement requires Python 3.10 or later.