How to Implement a Switch/Case Statement Equivalent in Python?

Neha Chaudhary

Blog Writer
SEO Writer
Technical Writer
Blogger.com
Google Drive
Notion
A switch-case statement is equivalent to an if-else statement in other languages like Java and C++. The switch-case statement allows to execution of a particular block of code based on the user’s input. These statements are useful when the programmer needs to verify certain inputs and provide convenient debugging. The switch case statement is easier to read making it more understandable.
Unfortunately, in Python, a switch-case statement does not exist, unlike in other languages. To implement a switch-case statement in Python, other methods are used which are discussed in this article.

How to Implement a Switch/Case Statement Equivalent in Python?

A switch case statement is helpful when a program needs to be tested for different values. The code will be improved if a switch case is added to it. Checking the code by providing the values can get really hectic. Here is how a basic switch case statement looks:
The Python language does not contain any inherent switch case statements. To implement the equivalent switch-case functionality in Python, we use the following ways:
Using the match keyword
Using a dictionary mapping
Using if elif else
Using classes
Using User-Defined Functions and Lambda Functions
Let us discuss each case in greater detail.
Method 1: Using the match keyword
The match case statement contains a number of case blocks. Each of the blocks provides information about the pattern that is to be matched against the value. The code gets executed when a particular match is made. The method is efficient and convenient. The following code explains how to implement the switch case functionality in Python using the match() keyword:
ent_num = int(input("Enter a number to let us know about your respective industry.\n"))match ent_num:        case 1:         print( "Writing")        case 2:         print( "Gaming")        case 3:         print( "Aviation")        case 4:         print( "Construction")        case 5:         print( "Automation")
In the above code,
A variable ent_num is defined which takes the user input from 1 to 6. The input is taken in the form of a string which is converted to an integer.
The match function matches the value of ent_num to different cases.
The result is printed according to the user input.
Output
The user input is 2 which corresponds to the case 'Gaming' hence it will be printed. The following output displays how a switch case functionality is implemented using the match case statement in Python:
Method 2: Using Dictionary Mapping
A Python dictionary stores the data in an unorganized way. The dictionary can store two values in a single item which is known as a key-value pair. The key value of the dictionary can act as a case in a switch case statement. The following code explains how a switch case functionality can be implemented in Python using dictionary mapping:
def get_info(num):    info = {        1: "Gaming industry deals with game development, AR, VR, XR and using tools like unreal engines .",        2: "Writing industry includes developing articles and blogs that run traffic to your site.",        3: "Art industry involves creating fine arts, animations, and so much more.",        4: "Translation industry involves translating content between languages.",        5: "Programming industry focuses on software development and coding.",        6: "The health and fitness industry focuses on the physical and mental well-being of an individual and also talks about the nutrition and diet a person should follow.",    }    return info.get(num, "Industry not found.")inp = input("Enter a number (1-6) to know about the industy: ")num = int(inp)ind_desc = get_info(num)print(f"Industry {num}: {ind_desc}")
In the above code,
A function get_info is defined which takes the parameter value of num.
Inside the function, a dictionary object info is defined that contains the keys as numbers from 1 to 6 which will be the cases and the values that give the information about the industry.
The get function is called on info. It takes the key values that represent the cases as num. If the value of num is not in the range of 1 to 6, the function prints ‘Industry not found,’
The inp variable will get the input from the user and it will be converted to an integer using int and stored in num.
The get_info function is called on num and the resulting information about the key-value pair is stored in the variable ind_desc.
The industry number and its respective information are then printed.
Output
The user gives the input of 1 which gives information about the gaming industry. Choosing a different number ranging from 1 to 6 will provide information about the respective key the value is stored against. The following output displays how a switch case functionality can be implemented in Python using the dictionary mapping:
Method 3: Using if elif else
If-elif else can be considered a condensed form of the if-else sequence. The if-elif statement can be used along with the else statement. The else statement is executed only when all the above if-elif statements are true. This enables to execution of multiple functionalities inside a single block. The following code shows how an if-elif-else statement can be used to implement the switch functionality in Python:
def food_choice(i):    if i == '1':        print("My favourite food is pasta.")    elif i == "2":        print("My favourite food is pizza.")    elif i == "3":        print("My favourite food is biryani.")    else:        print("I am not a huge fan of eating food.")inp = input("Select a number to choose your favorite food\n")food_choice(inp)
In the above code,
A function food_choice is defined that tells the food choice of the user depending upon the user input. The function takes the parameter value of i.
The first if statement equates the value of i to 1 which prints ‘My favourite food is pasta.’. The elif statement continues which equates the value of i to 2 printing ‘My favourite food is pizza.’ and if the value of i is 3 the function prints ‘My favourite food is biryani.’ If the i values is not 1, 2 or 3 the function prints ‘I am not a huge fan of eating food.’
The inp variable stores the input taken from the user.
The function food_choice is called on inp to get the favourite food of the user.
Output
The user gives the input value of 1 which prints the string value ‘My favourite food is Pizza’. The following output displays how if elif else statement in Python can be used to implement the switch functionality in Python:
Method 4: Using Classes
A class can create a Python object that contains all the functionalities of object-oriented programming. Classes can be used to implement the switch case functionality in Python. Here is a code that uses classes to execute the switch case functionality:
class industry:    def __init__(self):        self.industries = {            1: "Gaming",            2: "Writing",            3: "Art",            4: "Translation",            5: "Programming",            6: "Health and Fitness"        }    def info(self, num):        return self.industries.get(num, "Industry not found")inp = input("Enter the industry number (1-6): ")num = int(inp)switch = industry()ind = switch.info(num)print(f"Industry {num}: {ind}")
In the above code,
A class industry is defined
The class contains an __init__ function that takes the parameter value of self. Inside the __init__ function, the industries dictionary is defined whose keys have integer values representing different cases and the values contain the strings naming different industries.
Another function info is defined which takes sum and num as arguments. The function utilizes the get method to take the number to print the respective industry. If the number does not range from 1 to 6, the function will return ‘Industry not found’.
The variable int takes the input from the user which is converted to an integer using int and stored in the variable num. 
An instance of the industry class, switch is created
To get the required industry, the info method of the switch instance is called while taking num as an argument. The returned value is stored in the variable ind which has the information about the industry.
The industry number and the respective industry are printed.
Output
The user has given the value 5 which corresponds to the fifth key(case) inside the dictionary having the string value ‘Programming’. If the user gives input as 1 or 2, their respective string values which are ‘Gaming’ and ‘Writing’ will get printed. If the user gives an input value that does not lie in the range of 1 to 6, the string value ‘Industry not found’ will be printed. The following output displays how Python classes are used to implement the switch case functionality in Python:
Method 5: Using Lambda and User-Defined Functions
Lambda functions are anonymous functions that a user defines but they are nameless. They can be stored in different variables and can be utilized as normal functions. The following code explains how a  switch case functionality can be implemented using Lambda and the user-defined functions:
def first():        return 'Writing'def second():        return 'Programming'def industry(i):        switch={                0:first,                1:second,                2:lambda:'Gaming',                3:lambda:'Fitness'                }        func=switch.get(i,lambda :'Invalid')        return func()print(industry(1))print(industry(2))print(industry(5))
In the above code,
The functions first() and second() are user-defined functions that when called return the string values of ‘Writing’ and ‘Programming’.
The industry function takes i as an argument which executes different cases depending upon the value of i.
The industry function contains a dictionary switch that maps different values of i (keys) to their respective user-defined and Lambda functions. Notice here the keys are treated as the cases.
func=switch.get(i,lambda:'Invalid') extract each value of i from the dictionary, and in case no i is not available in the dictionary, the lambda expression returns the string value ‘Invalid’.
The function is called on different values of i to test the switch case functionality.
Output
The function industry() is called on 1, 2, and 5. The 1 key inside the dictionary has a corresponding value of second which is a user-defined function. It will be called and the string value ‘Programming’ will be printed. The 2 key in the dictionary has a corresponding value of a lambda expression that returns the string ‘Gaming’. 5 is not found in the dictionary so the lambda expression will return ‘Invalid case’. The following output displays how a switch case functionality can be executed using the lambda and user-defined functions in Python:
Conclusion
The most common method to implement the switch case functionality in Python programming is by using the match case statement while the alternative methods include using dictionary mapping, if elif else, classes, user-defined, and lambda functions. There is no switch case statement provided in Python so we have to use alternative ways to execute the switch/case functionality in Python. The article discusses different methods to implement the switch case functionality and illustrates each method with an example.
Partner With Neha
View Services

More Projects by Neha