Lesson explanation
After this lesson, you will be able to:
case patterns._.|.Python's match statement is useful when one value can take several known shapes or commands. It is similar to switch in other languages, but Python calls it structural pattern matching.
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
printPython checks cases from top to bottom and runs the first matching case. There is no fall-through, so you do not add break after each branch.
Use | when several literal values should share one result. A guard adds an if condition after a pattern when matching the value alone is not enough.
For simple thresholds such as score >= 90, regular if / elif / else remains clearer. This lesson focuses on literal routing, alternatives, fallbacks, and one guarded case—not advanced sequence or object patterns.
💡 Tip: Keep the wildcard fallback last. It matches anything that earlier cases did not handle.
Each literal case handles one known command.
command = "pause"
match command:
case "start":
print("Worker: starting")
case "pause":
print("Worker: paused")
case _:
Output:
Worker: pausedOnly the first matching case runs.
The wildcard _ handles values that were not listed explicitly.
export_format = "xml"
match export_format:
case "csv":
print("Exporter: CSV")
case "json":
print("Exporter: JSON")
case _:
Output:
Exporter: unavailableThe wildcard should appear after the specific cases.
Use | when several patterns lead to the same branch.
method = "HEAD"
match method:
case "GET" | "HEAD":
print("Request: read")
case "POST" | "PUT":
print("Request: write"
Output:
Request: readThe branch runs when either literal matches.
A guard refines a matched case with an additional condition.
event_type = "payment"
amount = 1250
match event_type:
case "payment" if amount >= 1000:
print("Payment: manual review")
case "payment":
Output:
Payment: manual reviewThe guarded payment case must come before the broader payment case.
| Goal | Pattern |
|---|
break after each case; Python does not fall through to the next case.case _ before specific cases.match for ordinary numeric thresholds that are clearer with if / elif.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 6 tasks completed
| Match one literal | case "start": |
| Match either literal | `case "GET" |
| Add another condition | case "payment" if amount > 0: |
| Handle everything else | case _: |