One value. Many cases.
The problem...
You have one variable. And ten possible values it could be. So you write ten elif blocks.
It works. But it's long. Repetitive. And harder to read than it should be.
if command == "quit":
print("Quitting.")
elif command == "help":
print("Showing help.")
elif command == "start":
print("Starting.")
elif command == "pause":
print("Pausing.")
else:
print("Unknown command.")
Every line repeats command ==. Python can do better.
The idea!
match takes one value and checks it against multiple cases. Cleaner syntax. Same logic. Available from Python 3.10 onwards.
The syntax
match value:
case option_1:
# runs if value == option_1
case option_2:
# runs if value == option_2
case _:
# runs if nothing matched — like else
case _ is the wildcard — it catches everything that didn't match. The equivalent of else.
Your first match
command = input("Enter command: ")
match command:
case "quit":
print("Quitting.")
case "help":
print("Showing help.")
case "start":
print("Starting.")
case "pause":
print("Pausing.")
case _:
print("Unknown command.")
Same logic as the if / elif chain above. But the variable is named once. Each case is clean and focused.
Matching numbers
import random
roll = random.randint(1, 6)
match roll:
case 1:
print("One — try again.")
case 6:
print("Six — you win!")
case _:
print(f"Rolled {roll} — keep going.")
Multiple values in one case
day = input("Enter a day: ").lower()
match day:
case "saturday" | "sunday":
print("Weekend.")
case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
print("Weekday.")
case _:
print("Not a valid day.")
The | operator lets you match multiple values in a single case. No need for separate blocks.
Heads up!
matchis available from Python 3.10 — check your version if it doesn't workcase _is the wildcard — always put it last|combines multiple values in one case- Only the first matching case runs — same as
if / elif - No
breakneeded — unlike some other languages
The mindset shift
Stop thinking: "I need an elif for every possible value."
Start thinking: "One value, many cases — match handles it cleanly."
What you should understand now
matchchecks one value against multiple casescase _catches everything that didn't match — likeelse|combines values in a single case- First match wins — the rest are skipped
- Available from Python 3.10 onwards