MyInternships.in

Python Control Flow

Python Match Case Statement

match-case, added in Python 3.10, lets you compare a value against several patterns and run the matching block, similar to a switch statement in other languages.


Basic match-case Syntax

You start with match followed by the value you want to check, then list one or more case patterns. Python compares the value against each case in order and runs the first block that matches, similar to how elif chains work.

Matching a day number
Python
day = 3
match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case _:
        print("Some other day")

The Wildcard _

The underscore _ is a wildcard pattern that matches anything. It acts like the default/else case and is usually placed last, since Python checks patterns in order and stops at the first match.

Wildcard as default
Python
command = "help"
match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case _:
        print("Unknown command")

Matching Multiple Values

You can combine several values in one case using the | (or) symbol, so a single block handles multiple possibilities without repeating code.

Matching multiple options
Python
fruit = "mango"
match fruit:
    case "apple" | "mango" | "banana":
        print("Common fruit")
    case _:
        print("Exotic fruit")

Guard Conditions

A guard adds an extra if condition to a case, so the pattern only matches when that condition is also True. This makes match-case powerful for checking ranges or combined rules, not just exact values.

Guard condition example
Python
num = 15
match num:
    case n if n < 0:
        print("Negative")
    case n if n % 2 == 0:
        print("Positive even")
    case _:
        print("Positive odd")

Matching Structures

match-case can also destructure data structures like tuples and lists, pulling out values directly in the pattern — this is what makes it "structural" pattern matching rather than a plain switch statement.

Matching a tuple structure
Python
point = (0, 5)
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"On the y-axis at {y}")
    case (x, 0):
        print(f"On the x-axis at {x}")
    case _:
        print("Somewhere else")
ℹ️

match-case requires Python 3.10 or newer. If your program must run on older Python, stick with if/elif/else chains.

💡

Use match-case when you are comparing one variable against many fixed values or shapes — it is often more readable than a long elif chain.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships