// Control Flow
match / case — The Full Picture
The idea!
You've covered match / case, guards, and pattern matching.
This is your reference. Everything in one place.
Come back here whenever you need a reminder.
match / case — the basics
match command:
case "quit":
print("Quitting.")
case "help":
print("Help.")
case "start" | "run":
print("Starting.") # | combines multiple values
case _:
print("Unknown.") # wildcard — always last
One variable. Many cases. First match wins. case _ catches everything else.
Guards — conditions inside cases
match score:
case n if n >= 90:
print("Excellent.")
case n if n >= 70:
print("Good.")
case n if n >= 60:
print("Passed.")
case _:
print("Failed.")
n captures the value. The guard adds the condition. Both must be true for the case to run.
Normalize before matching
match command.lower(): # normalize first
case "quit":
print("Quitting.")
match is case-sensitive. Always normalize strings before matching.
match vs if / elif
# match — one variable, many values
match product:
case "water": price = 1.00
case "coffee": price = 2.00
case _: price = None
# if / elif — complex, multi-variable logic
if score > 90 and attendance > 80:
print("Honours.")
Use match when checking one variable. Use if / elif for complex logic involving multiple variables.
Common Mistakes
matchrequires Python 3.10+ — check your version- Always add
case _— unmatched values are silently ignored - Normalize with
.lower()before matching strings case _always goes last — it matches everything- Use
matchfor one variable —if / eliffor complex logic
What you should understand now
matchchecks one value against multiple cases — first match winscase _is the wildcard — always last, catches everything|combines multiple values in one case- Guards add conditions —
case n if n > 0 matchis available from Python 3.10+ only
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment