What is the Python equivalent for a case/switch statement?
The Python equivalent for a case/switch statement is the if-elif-else
structure. Here is an example code snippet:
def switch_example(case_value):
if case_value == 1:
print("case 1")
elif case_value == 2:
print("case 2")
elif case_value == 3:
print("case 3")
else:
print("default case")
switch_example(1) # prints "case 1"
switch_example(2) # prints "case 2"
switch_example(3) # prints "case 3"
switch_example(4) # prints "default case"
Watch a video course
Python - The Practical Guide
Note that in python, elif
is short for "else if" and is used in place of the "case" keyword.