Introduced in Python 3.10, the match-case statement provides structural pattern matching. It is very similar to the switch-case statements found in other programming languages like C, Java, or JavaScript.
Instead of writing long, repetitive if-elif-else chains to check the value of a single variable, you can use match.
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks.
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
print(http_error(404))
print(http_error(500))
_)The case _: acts as the default or wildcard case. If the value does not match any of the patterns defined above it, this block will execute (similar to else).
You can combine several literals in a single pattern using the | ("or") operator:
match status:
case 401 | 403 | 404:
return "Not allowed"
Note: Pattern matching is incredibly powerful in Python 3.10+. It goes beyond simple value comparisons and allows you to "unpack" complex data structures like lists and dictionaries directly inside the case statements!