How to use Switch Case in Python

Switch-Case statement is a powerful tool that helps to control the flow of the program based on the value of a variable or an expression.
Unlike other languages like Java and C++, Python does not have a switch-case construct.
Using Dictionary Mapping
we use Python’s built-in dictionary to implement cases and decided what to do when a case is met. We can also specify what to do when none is met. The keys of the dictionary will work as case
.
n1 = 4 n2 = 5 print("Press \n1 for sum\n2 for difference\n3 for multiply\n4 for division") choice = int(input("Enter choice: ")) def add(): print(n1+n2) def diff(): print(n1-n2) def mul(): print(n1*n2) def div(): print(n1/n2) def default(): print("Enter valid choice") switch = { 1: add, 2: diff, 3: mul, 4: div } switch.get(choice, default)()
Using if-elif-else
Constructing python switch case statement using if-elif-else ladder is very much similar as the dictionary mapping
n1 = 4 n2 = 5 print("Press \n1 for sum\n2 for difference\n3 for multiply\n4 for division") choice = int(input("Enter choice: ")) if choice == 1: print(n1+n2) elif choice == 2: print(n1-n2) elif choice == 3: print(n1*n2) elif choice == 4: print(n1/n2) else: print("Enter valid choice")
Subscribe
Login
Please login to comment
0 Discussion