In Python, we do not have any switch statements. Instead, we can use the match statement for similar purposes. Please note that the Python match statement works for Python version 3.10 or higher.
For example, the following function will take a status code as an argument. Then, it will compare the status code. If it is 1 or 2, then the function will print the status code. Otherwise, it will print the status code is invalid.
def print_status_code(status):
match status:
case 1:
print("Status code is 1")
case 2:
print("Status code is 2")
case _:
print("Invalid status code")
As we can see the match statement is very similar to the switch statement in Jave or C. The case statements here compare the status code with certain values. And, the “case _:” statement works as a wildcard. It is matched for any status codes that are not 1 or 2 here.
So, if we call the function print_status_code() as print_status_code(4), it will print the following output:
Invalid status code
We can also combine several case statements using “|”. For example,








































0 Comments