In this tutorial, I am going to show you how to implement Switch Case using Python. Unlike other languages like C, C++ and Java, Python doesn’t have a Switch Case struct. But as you can see in this tutorial, it is possible to implement a structure identical to the Switch Case using Python.
You don’t need to have installed anything more than your Python interpreter.
As you can see in the code below, there is a class called “Switcher”, this class defines your Switch Case, this is where you insert the code you want to execute in each case, as you can see in example code (#comments).
In this example you need to insert the numbers in your python console, if you insert the numbers 1, 2 or 3 in the console, then you can see which case is executed, through the print made by the program. If you insert another number or letter, you see “Invalid Option”, which is the default value. inside the “if method ==” Invalid Option “ you can place any code you want to execute when the chosen option does not exist.
Create a new file “switchCase.py” and copy the code below to your file and save it. Then run the code and see the program’s prints on the console.
# Class of Switch-Case class Switcher(object): def service_switcher(self, argument, informations): """Dispatch method""" method_name = 'case_' + str(argument) # Get the method from 'self'. Default is "Invalid option". method = getattr(self, method_name, "Invalid option") if method == "Invalid option": return method # Call the method as we return it return method(method_name) def case_1(self, information): # here you can insert your case code return information def case_2(self, information): # here you can insert your case code return information def case_3(self, information): # here you can insert your case code return information a = Switcher() information = "Init program" while True: ## Get input (case choice) ### choice = input('Enter your choice [1-3] : ') information = a.service_switcher(choice, information) print(information)