In this article, we will try to understand Switch Case in Python (Replacement).
What is the replacement of Switch Case in Python?
Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.
Method 1: Switch Case implement in Python using Dictionary Mapping
In Python, a dictionary is an unordered collection of data values that can be used to store data values. Unlike other data types, which can only include a single value per element, dictionaries can also contain a key: value pair.
The key value of the dictionary data type functions as cases in a switch statement when we use the dictionary to replace the Switch case statement.
Python3
# Function to convert number into string # Switcher is dictionary data type here def numbers_to_strings(argument): switcher = { 0 : "zero" , 1 : "one" , 2 : "two" , } # get() method of dictionary data type returns # value of passed argument if it is present # in dictionary otherwise second argument will # be assigned as default value of passed argument return switcher.get(argument, "nothing" ) # Driver program if __name__ = = "__main__" : argument = 0 print (numbers_to_strings(argument)) |
zero
Method 2: Switch Case implement in Python using if-else
The if-else is another method to implement switch case replacement. It is used to determine whether a specific statement or block of statements will be performed or not, i.e., whether a block of statements will be executed if a specific condition is true or not.
Python3
bike = 'Yamaha' if bike = = 'Hero' : print ( "bike is Hero" ) elif bike = = "Suzuki" : print ( "bike is Suzuki" ) elif bike = = "Yamaha" : print ( "bike is Yamaha" ) else : print ( "Please choose correct answer" ) |
bike is Yamaha
Method 3: Switch Case implement in Python using Class
In this method, we are using a class to create a switch method inside the python switch class in Python.
Python3
class Python_Switch: def day( self , month): default = "Incorrect day" return getattr ( self , 'case_' + str (month), lambda : default)() def case_1( self ): return "Jan" def case_2( self ): return "Feb" def case_3( self ): return "Mar" my_switch = Python_Switch() print (my_switch.day( 1 )) print (my_switch.day( 3 )) |
Jan Mar
Switch Case in Python
In Python 3.10 and after that, Python will support this by using match in place of switch:
Python3
# This code runs only in python 3.10 or above versions def number_to_string(argument): match argument: case 0 : return "zero" case 1 : return "one" case 2 : return "two" case default: return "something" head = number_to_string( 2 ) print (head) |