Alternatives to switch case in Python
Ever wondered if there is a way to avoid writing those extensive if-else statements? Switch Case is a cleaner and faster alternative to if-else conditions in your code.
Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.
Implementing Switch Case
Python allows us to implement a Switch Case in two notable ways.
1. Switch case using a dictionary
The idea behind a dictionary is to store a key-value pair in the memory.
Let’s take an example to better understand the process of creating switches ourselves.
Example
Suppose you wish to write a piece of code which returns the season corresponding to a certain input.
- You will start off by creating separate functions for each case that you wish to handle.
def spring():
return "Spring"
def summer():
return "Summer"
def autumn():
return "Autumn"
def winter():
return "Winter"
def default():
return "Invalid Season!"
Note: Make sure that you handle the default case.
- The next step is to create the dictionary.
switch_case = {
1: spring,
2: summer,
3: autumn,
4: winter
}
- The last step is to simply create a function which will take as input an integer and will automatically invoke the corresponding function after the dictionary lookup.
def switch(x):
return switch_case.get(x, default)()
Run the following code to see how all this comes together!
def spring():return "It is Spring"def summer():return "It is Summer"def autumn():return "It is Autumn"def winter():return "It is Winter"def default():return "Invalid Season!"switch_case = {1: spring,2: summer,3: autumn,4: winter}def switch(x):return switch_case.get(x, default)()print switch(1)print switch(5)
2. Switch Case using a class
Classes may also be used to implement switch case functionality.
Example
In continuation with our previous example, we will proceed as follows to effectively create a switch case.
- Start off by making a Switch class which will have a basic switch function.
def Switch():
def switch(self, season):
default = "Invalid Season!"
return getattr(self, 'season_' + str(season), lambda:default)()
Note:
getattr()in Python is used to invoke a function call.The
lambdakeyword in Python is used to define an anonymous function. In case the user gives an invalid input,lambdawill invoke the default function.
- Define separate functions for each case, same as before.
Execute the following code and see how this would work.
class Switch():def switch(self, season):default = "Invalid Season!"return getattr(self, 'season_' + str(season), lambda:default)()def season_1(self):return "It is Spring"def season_2(self):return "It is Summer"def season_3(self):return "It is Autumn"def season_4(self):return "It is Winter"my_switch = Switch()print (my_switch.switch(1))print (my_switch.switch(10))
Use either one of these methods to make your code speedy and neat!
Free Resources