The Switch-Case
statement is an important decision-making programming feature that is widely used in modular programming, enabling you to execute different blocks of code based on a variable value during runtime. Unlike many other languages, Python does not directly support switch or a case statement.
The reason for this is, instead of sequentially analyzing each statement, it evaluates the expression or variable and jumps explicitly to the following branch code to execute.
This tutorial explains Python’s built-in ways like a dictionary
, lambda function
, and classes to create custom Python switch-case statements.
We’ll be covering the following topics in this tutorial:
Switch Case using a Dictionary
An efficient dictionary mapping, also known as associative arrays, is a pythonic way of implementing a switch-statement that offers one-to-one key-value mappings. Follow the below steps.
1.First, creating separate function for each case and make sure there is a default case to handling function.
def monday(): return "monday" def tuesday(): return "tuesday" def wednesday(): return "wednesday" def thursday(): return "thursday" def friday(): return "friday" def saturday(): return "saturday" def sunday(): return "sunday" def default(): return "Invalid day"
2. Next, build a dictionary object(It store key-value pair in the memory) and save each function.
switcher = { 1: monday, 2: tuesday, 3: wednesday, 4: thursday, 5: friday, 6: saturday, 7: sunday }
3 Write a switch()
function that accepts the day of the week as an argument.
def switch(dayOfWeek): return switcher.get(dayOfWeek, default)()
4 Switch()
calls the get()
method on the dictionary object, which returns and concurrently invokes function that match the argument.
print(switch(1)) print(switch(0))
Example: Implement Python Switch Case Statement using Dictionary
def monday(): return "monday" def tuesday(): return "tuesday" def wednesday(): return "wednesday" def thursday(): return "thursday" def friday(): return "friday" def saturday(): return "saturday" def sunday(): return "sunday" def default(): return "Invalid day" switcher = { 1: monday, 2: tuesday, 3: wednesday, 4: thursday, 5: friday, 6: saturday, 7: sunday } def switch(dayOfWeek): return switcher.get(dayOfWeek, default)() print(switch(1)) print(switch(0))
The output is as follows:
Monday Invalid day
Here when we pass an argument to the switch function, the switcher’s dictionary mapping is scanned. The associated value is printed if a match is found. Otherwise, a default string ('Invalid day')
is printed. The default string helps to implement the switch 'default case.'
Switch Case using a Class
Python classes may also be used as an alternate way to execute switch-case statements. Let’s use an example to do so.
• First, There is a switch class, which specifies the switch()
method.
• The day of the week
is an argument, it is converted to a string, and it is appended to the 'case_ '
literal. The resulting string is then passed to the getattr()
function.
• The getattr()
method returns the matching function of the type.
• If the string doesn’t find a match, getattr()
returns the default lambda function.
# Implement Python Switch Case Statement using Class class Switch: def switch(self, dayOfWeek): default = "Invalid day" return getattr(self, 'case_' + str(dayOfWeek), lambda: default)() def case_1(self): return "Monday" def case_2(self): return "Tuesday" def case_3(self): return "Wednesday" s = Switch() print(s.switch(1)) print(s.switch(0))
The output is as follows:
Monday Invalid day
Switch Case using Python functions
The Python dictionary values may be of any data. Therefore, we don’t have to use constants (integers, strings). Function names and lambdas may also be used as values.
E.g., by building a dictionary of function names as values, we can also implement this switch statement. It is convenient to use with the Python switch case statement. We have a few steps to consider.
• First, for each case, specify the individual functions.
• Make sure there is a default case handling function.
• First, create a dictionary object and store each of the functions.
• After that, write a switch()
function that accepts the number of months as arguments.
• The switch()
calls a get()
method on a dictionary object that returns and concurrently calls a function matching the argument.
In this case, a switcher is a function names dictionary without strings.
def monday(): return "monday" def tuesday(): return "tuesday" def wednesday(): return "wednesday" def thursday(): return "thursday" def friday(): return "friday" def saturday(): return "saturday" def sunday(): return "sunday" def switch(dayOfWeek): switcher = { 1: monday, 2: tuesday, 3: wednesday, 4: thursday, 5: friday, 6: saturday, 7: sunday } func = switcher.get(dayOfWeek, lambda: "Invalid day") print func()