Python Match Statement
A match statement compares one value against a list of cases. The first matching case runs.
The same choice with elif
An elif chain writes the value in every test.
day = 3
if day == 1:
print("Monday")
elif day == 3:
print("Wednesday")
else:
print("Another day")Match one value
Python checks each case until one equals the value.
day = 3
match day:
case 1:
print("Monday")
case 3:
print("Wednesday")
case _:
print("Another day")The wildcard catches the rest
No case equals 9, so the wildcard case runs.
code = 9
match code:
case 1:
print("Start")
case _:
print("Unknown code")First match wins
Two cases can hold the same value. Only the first one runs.
value = 2
match value:
case 2:
print("First two")
case 2:
print("Second two")Match words, not just numbers
A pattern can be a string in quotes.
color = "red"
match color:
case "red":
print("Stop")
case "green":
print("Go")
case _:
print("Wait")Example
day = 5
match day:
case 1:
name = "Monday"
case 2:
name = "Tuesday"
case 3:
name = "Wednesday"
case 4:
name = "Thursday"
case 5:
name = "Friday"
case 6:
name = "Saturday"
case 7:
name = "Sunday"
case _:
name = "Unknown"
print("Day", day, "is", name)Key points
- Pattern: the value written after the word case.
- In this lesson each pattern is one exact value, like 1 or "red".
- Python compares the value with each case from the top.
- The first match wins, and the rest are skipped.
- Wildcard: the pattern _ matches anything at all.
- Put it last, as the catch-all case.
- A case block is indented, just like other blocks.
- Python writes the value once at the top.
In this example, day is 5. Python compares 5 with each case from the top. The case 5 line matches first, so name becomes "Friday". Python skips every case after the match. The last line prints the day number and its name.
Note
match arrived in Python 3.10.
Older versions do not know it, so use an elif chain there.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does this code print? level = 4 match level: case 1: print("Easy") case _: print("Other")