Comparison with Python if Statements
Before we dive into the examples of the Python Switch Case statement, let's compare it with the traditional if-elif-else
statements.
Consider the following example of matching HTTP response codes:
response_code = 200
if response_code == 200:
print("OK")
elif response_code == 404:
print("404 Not Found")
elif response_code == 500:
print("Internal Server Error")
We can rewrite the same example using the Python Switch Case statement as follows:
response_code = 201
match response_code:
case 200:
print("OK")
case 404:
print("404 Not Found")
case 500:
print("Internal Server Error")
As you can see, the Python Switch Case statement is more concise and easier to read compared to the if-elif-else
statements.
Here is the syntax for a switch case statement:
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
The term
is the value that you want to match against the patterns. The pattern can be a single value, a tuple, a list, a builtin class, or a combination of these using the or operator (|
). The _
is a catch-all pattern that matches any value.