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.
Python allows us to implement a Switch Case in two notable ways.
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.
Suppose you wish to write a piece of code which returns the season corresponding to a certain input.
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.
switch_case = {
1: spring,
2: summer,
3: autumn,
4: winter
}
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)
Classes may also be used to implement switch case functionality.
In continuation with our previous example, we will proceed as follows to effectively create a switch case.
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
lambda
keyword in Python is used to define an anonymous function. In case the user gives an invalid input,lambda
will invoke the default function.
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