A switch-case statement is equivalent to an if-else statement in programming languages like Java and C++. The switch-case statement allows the users to execute a certain block of code according to 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 which makes it more understandable.
Unfortunately, in Python, a switch-case statement does not exist, unlike in other programming languages. To implement a switch-case statement in Python, other methods are used as an alternative to the switch case which will be discussed in this article using suitable examples.
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. However, Python does not contain any inherent switch case statements. To implement the switch-case equivalent functionality in Python, use one of the following ways:
- Method 1: Implement a Switch Case Using the Match Keyword
- Method 2: Implement a Switch Case Using Dictionary Mapping
- Method 3: Implement a Switch Case Using if elif else
- Method 4: Implement a Switch Case Using Classes
- Method 5: Implement a Switch Case Using User-Defined Functions and Lambda Functions
Before diving into the practical implementation of the above-stated methods let’s consider the following flowchart to learn how a basic switch case statement works:
Let us discuss each case in greater detail.
Method 1: Implement a Switch Case Using the Match Keyword
The match 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. This method is efficient, convenient, and recommended to use as an alternative to the switch statement.
The following code explains how to implement the switch case functionality in Python using the match keyword:
ent_num = int(input("Enter a number between 1-5 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 5. The input is taken in the form of a string which is converted/transformed 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: Implement a Switch Case 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 industry: ") 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. The following output displays how a switch case functionality can be implemented in Python using the dictionary mapping:
Similarly, choosing a different number from the range of 1 to 6 will provide information about the key against which the respective value is stored.
Method 3: Implement a Switch Case Using if elif else
If-elif else can be considered a condensed form of the if-else condition. 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 false. This enables the 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 favorite food is pasta”. The elif statement continues which equates the value of i to 2 printing “My favorite food is pizza”, and if the value of i is 3 the function prints “My favorite food is biryani”. If the entered value is not equal to 1, 2, or 3 the function prints “I am not a huge fan of eating food”.
- The inp variable stores the user-entered value/input.
- The function food_choice is called on inp to get the favorite food of the user.
Output
The user gives the input value of 1 which prints the string value “My favorite 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: Implement a Switch Case Using Classes
A class can create a Python object that contains all the functionalities of object-oriented programming. Classes can be utilized to implement/execute 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 named 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 named “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 named switch is created.
- To get the required industry, the info() method of the switch instance is called while taking num as an argument. The retrieved value is kept in the variable named 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”. The following output displays how Python classes are used to implement the switch case functionality in Python:
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.
Method 5: Implement a Switch Case Using User-Defined and Lambda 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 named 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. An important point to be noticed here is that the keys are treated as cases.
- func=switch.get(i,lambda:’Invalid’) extracts each value of i from the dictionary, and in case 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 is 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 returns “Invalid case”.
The output displays how a switch case functionality can be executed using 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 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.