SwadhyAI Notes

All Python notes

Python Match Case 🎯

Structural Pattern Matching

Introduced in Python 3.10, the match statement allows you to match a value against a series of patterns. It is similar to the switch statement in other languages, but much more powerful.

✨ Basic Syntax

python
status = 404

match status:
    case 400:
        print("Bad request")
    case 404:
        print("Not found")
    case 418:
        print("I'm a teapot")
    case _:
        print("Something's wrong with the internet")

🔗 Combined Cases

You can combine several cases in a single pattern using | (the "or" operator):

python
case 401 | 403 | 404:
    return "Not allowed"

📦 Matching Lists and Tuples

You can match against sequences like lists or tuples, and even unpack values:

python
# point is an (x, y) tuple
point = (0, 5)

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

🛡️ Guard Clauses

You can add an if statement to a case pattern to add extra logic:

python
point = (5, 5)

match point:
    case (x, y) if x == y:
        print(f"Y=X at {x}")
    case (x, y):
        print(f"Not on the diagonal")

💡 Did You Know?

The _ symbol is a wildcard character that matches anything. It acts as a default case if no other patterns match. It is good practice to always include it.