Register Login

Python Switch Case

Updated Oct 17, 2023

Have you ever seen a menu-driven program where end-users choose options from a list of items? Such programs accept input from the end-users and then check whether the inputs match the given conditions in the Python program. Using Switch Case technique in Python, programmers can create such programs.

But one cannot directly use switch case in Python unlike other programming language. There are alternatives that allow switching and handling multiple conditions in a Python program.

Python Switch Case is a selection control statement. It checks the values of each case with the expression value and executes the associated code block.

There were several methods Pythonistas simulated switch statements back in the day. This article will discuss how to implement Python Switch Cases in four different ways.

What is a Switch Case in Python?

When programmers want to execute multiple conditions based on the value of an expression, they use a switch statement. It is a multiway branch statement in Python, a substitute for long if statements comparing a variable to multiple integral values.

But, note that users cannot use built-in Python Switch Case statements as this programming language does not have, unlike other languages. So to get around this program, users can use the dictionary mapping with functions and lambdas, classes, or if-elif-else statements.

Implementing Python Switch Case statements

Implementation 1:

First, we will see how to implement Switch Case statements using Dictionary mapping:

In Python, a dictionary is an unordered data collection that users can use to store data values. This data structure can store values containing a key: value pair.

The key value of the Python dictionary data type works as a case in a switch statement. When users use the dictionary, it replaces the Switch Case statements and performs execution similar to the witch case with its key-value pair, working as cases.

With the help of dictionaries, users can use two different ways, i.e., functions and lambdas, to implement Switch Case statements:

Switch Case in Python using Functions

Let us define some functions that work as values in the dictionary. The dictionary will execute these functions when users call the values with their associated keys. Thus, it returns the desired output.

Code Snippet:

def January():
    return "1st month"
def February():
    return "2nd month"
def March():
    return "3rd month"
def April():
    return "4th month"
def May():
    return "5th month"
def June():
    return "6th month"
def July():
    return "7th month"
def August():
    return "8th month"
def September():
    return "9th month"
def October():
    return "10th month"
def November():
    return "11th month"
def December():
    return "12th month"
def default():
    return "No month left"

monthlist = {
    1: January,
    2: February,
    3: March,
    4: April,
    5: May,
    6: June,
    7: July,
    8: August,
    9: September,
    10: October,
    11: November,
    12: December,
    }
def demo(name):
    return monthlist.get(name, default)()
print(demo(6))
print(demo(4))
print(demo(16))

Output:

Explanation:

In this Python program, we serially created some functions in the name of the months. Then, we created a dictionary in which we stored distinct key-value pairs. Each value of the dictionary "monthlist" is the function names. Then, we called the functions and got the desired output.

Python Switch Case Using Lambdas

Lambda functions are small anonymous functions where users can give n numbers of inputs as parameters. But these functions can have only one expression.

Thus, we should define anonymous lambda functions to use dictionaries instead of the Switch Case statements. Similar to the above functions, it will represent the values in key-value pairs in dictionaries.

Syntax:

lambda parameters: expression

Code Snippet:

Code Snippet:
def January():
    return "1st month"
def February():
    return "2nd month"
def March():
    return "3rd month"
def April():
    return "4th month"
def May():
    return "5th month"
def June():
    return "6th month"
def July():
    return "7th month"
def August():
    return "8th month"
def September():
    return "9th month"
def October():
    return "10th month"
def November():
    return "11th month"
def December():
    return "12th month"
def default():
    return "No month left"

def demo(name):
    monthlist = {
        1: January,
    2: February,
    3: March,
    4: April,
    5: May,
    6: June,
    7: July,
    8: August,
    9: September,
    10: October,
    11: November,
    12: December,
    }
    return monthlist.get(name, lambda: "no month exist in this number") ()
print(demo(6))
print(demo(4))
print(demo(16))

Output:

Explanation:

In this Python program, we serially created some functions in the name of the months. Then, we created a dictionary in which we stored distinct key-value pairs. Within the dictionary, we created the lambda function.

When we call these values with the help of keys, the particular function gets invoked, and we get the desired output. We can get the desired output stored as values by calling the function with the associated key.

Implementation 2: Implementing Python Switch Case statements with Classes:

A class is a user-defined object constructor where users can create objects. These provide a means of clustering data and functionality together.

When users create a new class, it creates a new object. Now let us see how we can implement Switch Case statements using the Python getattr function in the following example:
The getattr() function gets the attribute values of the objects.

Syntax:

getattr(object, name, default)

The function takes three parameters and these are as follows:

  • object: This parameter specifies the object name whose attribute the method must return. It is a mandatory parameter.
  • name: This parameter specifies a string containing the attribute name of the object. It is also a mandatory parameter.
  • default: If the method does not find the attribute in the object, this parameter returns the default statement. This parameter is optional.

Code Snippet:

class demo:
	def week(a, n):
		default = "Incorrect day"
		return getattr(a, 'month_' + str(n), lambda: default)()
	def month_1(a):
		return "January"
	def month_2(a):
		return "February"
	def month_3(a):
		return "March"
	def month_4(a):
		return "April"
	def month_5(a):
		return "May"
month = demo()
print(month.week(1))
print(month.week(8))
print(month.week(3))

Output:

Explanation:

Here, we created a class named "demo" which returns the month name based on the number input. This happens after serially creating different functions in the names of months inside the class.

Then, we used the getattr() method to check the various conditions associated with each function in the class. These functions will work as the Switch Case statements returning the associated values.

Implementation 3: Implementing Python Switch Case statements with if-elif-else:

Users can use the if-elif-else statement in Python to create a program for decision-making. One can use it instead of the Switch Case in Python, providing all the switch conditions as decisions in the if and elif block. Then, using the else block, they can return the default values.

The if block executes a decision when it finds a makes the condition is true or not. And based on this, it returns the indented expression. But, if the condition is false, the if-elif-else statement will return the indented expression under the else block. Users can run multiple conditions by using as many elif conditions as required between the if and the else block.

Syntax:

if(condition):
    statement
elif(condition):
    statement
else:
    statement

Code Snippet:

demo = 43
if (demo < 0):
    print('This is a negative number')
elif (1 <= demo <= 10):
    print('This number lies in between of one and ten')
else:
    print('The number', + demo, 'is greater than 20')

Output:

Explanation:

In the above example, we assigned a variable with an integer value. Then, using the three conditional statements, if, elif, and else blocks, we provided three different conditions. Then, we returned the statement from these blocks.

Lastly, we used the else statement, which returns the default value when the input does not satisfy other above conditions.

Applications of Switch Case in Python

Programmers often try to find methods that help them provide multiple conditions or create a menu-driven program. Thus, without hassle, they can go for any of the above implementations and write code to create a menu-driven program.

Switch Case statements are multiway branching statements that users can design menu-like programs. These allow handling one choice among multiple choices. These are more efficient solutions to controlling conditional statements and ensuring the code does not multiple clustered if statements.

Conclusion

Python does not provide any built-in technique to use Switch Case statements but gives alternative options. Programmers can use the three different implementations, i.e., dictionary mapping, if-elif-else statements, or classes to implement Switch Cases in Python. Further, the article provided applications of the Switch Case statement in programming.


×