Compare one value against a list of patterns and run the first case that fits.
# match-case statement
command = "start"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown")
# ans: Starting...
command =
status_code =
Cases are tried top to bottom; the first pattern that fits wins and the rest are skipped.
# multiple values
status_code = 201
match status_code:
case 200 | 201:
print("Success")
case 404:
print("Not Found")
case _:
print("Other")
# ans: Success
# underscore is the wildcard
x = 100
match x:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Default")
# ans: Default
# no match, no output
x = 5
match x:
case 1:
print("One")
case 2:
print("Two")
# ans: (nothing)
Predict which case runs, then press → to trace.
# what prints?
x = 2
match x:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Other")
# ans: Two
# default case?
x = 100
match x:
case 1:
print("One")
case _:
print("Default")
# ans: Default
# multiple values?
x = 201
match x:
case 200 | 201:
print("Success")
case _:
print("Other")
# ans: Success
# no match?
x = 5
match x:
case 1:
print("One")
case 2:
print("Two")
# ans: nothing (no default, no match)
# first match wins?
x = 1
match x:
case 1:
print("First")
case 1:
print("Second")
# ans: First
# match with a string?
cmd = "quit"
match cmd:
case "start":
result = "Starting"
case "quit":
result = "Quitting"
# ans: result is "Quitting"
# wildcard position?
x = 999
match x:
case _:
print("Any")
case 999:
print("999")
# ans: SyntaxError: case _ must be last
Python refuses to run this: case _ matches everything, so the cases after it could never run.
# or pattern?
x = 503
match x:
case 500 | 502 | 503:
print("Server Error")
# ans: Server Error
# match None?
x = None
match x:
case None:
print("Is None")
case _:
print("Not None")
# ans: Is None
# match with a guard? (advanced)
x = 15
match x:
case n if n > 10:
print("Big")
case _:
print("Small")
# ans: Big
case n captures the value into n; the guard if n > 10 must also be True.
The first case whose pattern fits runs; the rest are skipped.
| means "or"case 200 | 201: fits either value.
case _The wildcard fits anything, so it goes last.
Without a wildcard, nothing runs when no case fits.