What is the Python equivalent of a switch statement?
In Python, the equivalent of a switch statement is often implemented using a dictionary mapping. Here’s a basic example:
def switch_case(argument):
switcher = {
1: "January",
2: "February",
3: "March",
# and so on...
}
return switcher.get(argument, "Invalid month")
Usage:
month_name = switch_case(3)
print(month_name)
Output:
March
Another approach is to use a series of if-elif-else statements:
def switch_case(argument):
if argument == 1:
return "January"
elif argument == 2:
return "February"
elif argument == 3:
return "March"
# and so on...
else:
return "Invalid month"
Usage:
month_name = switch_case(3)
print(month_name)
Output: March
Alternatively, you can use a class-based approach:
class Switcher: def case_1(self): return “January”
def case_2(self):
return "February"
def case_3(self):
return "March"
def default(self):
return "Invalid month"
def switch(self, argument):
# Get the method from 'self' by name
method = getattr(self, 'case_' + str(argument), self.default)
# Call the method as we return it
return method()
Usage:
s = Switcher() month_name = s.switch(3) print(month_name)
Output:
March