[Note: This tutorials is for beginners only]
Once you start programming in Python, very soon you encounter with the scenario that there is no direct support of switch case. The community has various alternatives for the purpose namely,
- Using dictionaries
- Using lambdas
- Using Exceptions
- and many others!
For a beginner it is faster and easier to go with if-else construct to get the switch case functionality. Below code rests the case. Syntax adheres to Python 3.
# Dummy function_one def function_one(): print("You called Function One") # Dummy function_two def function_two(): print("You called Function Two") # Defining the switch case equivalent in an infinite while loop, # until the user decides to break def main(): while True: print("Menu") print("--------------") print("1-Function_one\n2-Function_two\n3-Exit") print("--------------") print("Enter your choice\n") choice = input() if choice == '1': function_one() elif choice == '2': function_two() else: print("Program Terminates") break # Call the main() main()
The code can also be obtained from github from the following link:
switch Case in Python Using if-else