The match statement was introduced in Python 3.10 and works similarly to switch/case in other languages. It lets you compare (or match) a value against multiple patterns and run different blocks of code depending on which pattern fits.
|._ acts like a “default” or “catch-all”.Basic structure of a match statement:
match value:
case pattern_1:
# code block
case pattern_2:
# code block
case _:
# default / catch-all block
The interpreter evaluates each case from top to bottom. The first pattern that matches runs its block, and the rest are skipped.
if-elif-else chains that compare the same variable.Here we match a day name and print a message based on its value.
# Set the current day
day = "Monday"
# Use match to handle different days
match day:
case "Monday":
# Specific case for Monday
print("Start of the week")
case "Friday":
# Specific case for Friday
print("End of the week")
case _:
# All other days fall here
print("Middle of the week")
You can group several possible values into a single case using the | operator.
# Assign a fruit name
fruit = "apple"
# Match multiple possible fruit values
match fruit:
case "apple" | "banana" | "cherry":
# Any of these values will match this case
print("This is a fruit")
case _:
# Fallback for anything else
print("Unknown item")
The match statement can also match structured data like dictionaries and extract values into variables.
# Define a point as a dictionary
point = {"x": 0, "y": 5}
# Use structural pattern matching to inspect coordinates
match point:
case {"x": 0, "y": y_val}:
# x is 0, so the point lies on the Y axis
print(f"On Y axis at {y_val}")
case {"x": x_val, "y": 0}:
# y is 0, so the point lies on the X axis
print(f"On X axis at {x_val}")
case _:
# Any other combination is somewhere else
print("Somewhere else")
day = "Monday", the output is: Start of the week.fruit = "apple" matches the first case, so it prints: This is a fruit.{"x": 0, "y": 5} matches {"x": 0, "y": y_val}, so y_val becomes 5 and it prints: On Y axis at 5.If none of the explicit patterns match, the case _: block runs, acting like a default branch.
match to replace long if-elif-else chains comparing the same variable.case _: at the end as a safe catch-all branch.| (e.g., weekend days or related commands).match works only in Python 3.10+. Older versions will raise a SyntaxError.case keyword.day that prints whether it is a weekday or weekend. Group Saturday and Sunday using |.match to categorize an item as "fruit", "vegetable", or "unknown".point = {"x": 3, "y": 0} and use match to: