Python Match
match looks at one stored value and runs the first case that is that value. cups = 2 stores 2. case 1 wants 1, so it does not run. case 2 wants 2, so print("tea") runs. The program stops looking. case _ is not reached.
cups = 2
match cups:
case 1:
print("water")
case 2:
print("tea")
case _:
print("none")
The screen shows tea.
One cup hits the first case
cups = 1. case 1 wants 1, so print("water") runs. case 2 and case _ stay quiet. A later case does not get a turn after an earlier one has already fit.
cups = 1
match cups:
case 1:
print("water")
case 2:
print("tea")
case _:
print("none")
The screen shows water.
Nine is none of the named cases
cups = 9. It is not 1 and it is not 2. case _ means whatever is left, and print("none") runs. Only that one case runs. You do not also see tea or water.
cups = 9
match cups:
case 1:
print("water")
case 2:
print("tea")
case _:
print("none")
The screen shows none.
The previous page had two paths, if and else. This page gives each value its own case. One run picks one case.
match and each case end with a colon. The case lines sit four spaces in from match. The print lines sit four spaces in from case. match and case are lowercase. Match with a capital M stops the program.
case _ belongs last. It fits every value. Write it before case 2 and the program stops before it runs. The later case could never be reached, so Python rejects the whole match. _ is the leftover line, not the first line.
The next page repeats lines
This page runs one case, once. The next page is the for loop. It repeats lines.
Say these yourself
- cups = 2 writes tea. case 1 does not run.
- cups = 1 writes water.
- cups = 9 writes none. Only that case runs.
- case _ comes last. Before a named case, the program stops. The next page is the for loop.
Easy to misread
- Expecting tea and none on the same run
- Putting case _ before case 2
- Leaving out a colon after match or case
- Writing Match or Case with a capital letter
- Reading match as if and else with only two paths
Keep
match runs the first case that is the stored value.
cups = 2 writes tea. cups = 1 writes water. cups = 9 writes none.
Only one case runs.
case _ is the leftover, and it comes last. Earlier than that, the program stops.
The next page is the for loop.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top