Python Match (match ... case)
When one value decides between many different actions, a long chain of elif lines becomes hard to read. Since version 3.10 Python has the match statement: you name the value once, and each case lists a pattern to compare it with. Python runs the block of the first case that matches. Other languages have a similar switch statement, but Python's match can do more.
Matching values
command = "stop"
match command:
case "start":
print("Starting the engine.")
case "stop":
print("Stopping.")
case "pause" | "wait":
print("Waiting a moment.")
case _:
print("Unknown command:", command)Stopping.
The | sign lists several values in one case. The case with _ matches anything, so it works like else: put it last. Unlike switch in C, there is no falling through to the next case and no break to write: exactly one block runs, or none.
Conditions in a case
A case can add a condition with if, called a guard. A name in a pattern captures the value, so the guard and the block can use it:
for score in [100, 75, 30, -5]:
match score:
case 100:
print(score, "perfect")
case n if n >= 50:
print(score, "pass")
case n if n >= 0:
print(score, "fail")
case _:
print(score, "not a valid score")100 perfect 75 pass 30 fail -5 not a valid score
Matching the shape of data
match can also look inside tuples and lists, and take their parts apart at the same time. This is where it is much more powerful than a chain of if statements:
points = [(0, 0), (3, 0), (0, -2), (4, 5)]
for point in points:
match point:
case (0, 0):
print("the origin")
case (x, 0):
print(f"on the x axis at {x}")
case (0, y):
print(f"on the y axis at {y}")
case (x, y):
print(f"at x={x}, y={y}")the origin on the x axis at 3 on the y axis at -2 at x=4, y=5
A pattern can be a literal value such as 0, which must be equal, or a name such as x, which accepts any value and stores it. Patterns can also match lists of any length, dictionaries and objects of your own classes.
When to use match
Use match when one value is compared with many fixed values or when data has several possible shapes. For one or two conditions, or conditions on different values, if and elif stay simpler.
Practice exercises
- Ask for a day number from 1 to 7 and print the name of the day with
match, with a case for invalid numbers. - Write a small calculator: read an operator
+,-,*or/and two numbers, and usematchon the operator. - Use a guard to print "teenager" for ages 13 to 19.
- Match tuples of the form
("move", x, y)and("quit",)and print what each command means.