Multi-way Branching with match / case
When you are checking one value against many fixed options, a long if / elif chain works but can get noisy. Python's match statement (added in 3.10) reads cleanly for that job.
You match a value, then list case patterns. The first matching case runs. The underscore _ is the catch-all, like else:
def describe(day):
match day:
case "sat":
return "weekend"
case "sun":
return "weekend"
case _:
return "weekday"
print(describe("sun")) # weekend
print(describe("mon")) # weekdayOne case can match several values with | (read it as "or"):
def kind(status):
match status:
case 200 | 201 | 204:
return "ok"
case 404 | 410:
return "missing"
case _:
return "other"
print(kind(404)) # missingYou can even add a condition to a case with if, called a guard:
def sign(n):
match n:
case 0:
return "zero"
case _ if n > 0:
return "positive"
case _:
return "negative"For one-value-to-many-outcomes branching, match is often the most readable choice.
Define a function http_label(code) using a match statement. Return "ok" for 200 or 201, "redirect" for 301 or 302, "not found" for 404, and "unknown" for anything else (use _). Combine values in one case with |.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.