What is Switch Case in Python?
There are no built-in switch case statements in Python. However, Python offers multiple methods to replace the switch case functionality to harness all the above benefits. Let's understand more!
In this article, we will discuss these methods and how they are used to implement switch cases in Python. So, without further ado, let’s get started.
Table of Content
- What is a switch case statement?
- Introduction to Python Switch Case
- Methods to Implement Switch Case in Python
- Switch Case Example in Python
What is switch case statement?
The switch case statement can be described as a cleaner form of an if-else statement in programming languages like C, C++, Java, etc. The significance of the switch case involves:
- Easy maintenance of the code
- Easy Debugging
- Values can be checked and verified more effectively
- Improved code readability
Explore free C courses | Explore free C++ courses |
Explore free Java courses | Explore programming courses |
Introduction to Switch Case in Python
Switch Case in Python is a selection control statement, similar to Python if-else – the switch expression is first evaluated and then compared to each case. If there is a match, the associated block of code is executed, else the control moves forward.
The above flow chart illustrates the working of the switch case.
Using Python switch cases can make the program easier to read and understand because it will not be cluttered by too many if-else statements.
Explore free Python courses
Methods to Implement Switch Case in Python
1. Using Dictionary
A common way to implement a switch statement in Python is to use a dictionary to map cases to their corresponding actions. Here’s an example:
def run_case(case): options = { 'case_1': case_1, 'case_2': case_2, 'case_3': case_3 } options.get(case, default)()
def case_1(): print("Running case 1")
def case_2(): print("Running case 2")
def case_3(): print("Running case 3")
def default(): print("Invalid case")
run_case('case_1') # Output: Running case 1run_case('case_2') # Output: Running case 2run_case('case_4') # Output: Invalid case
Output
Running case 1
Running case 2
Invalid case
Explanation
In the above example, we define a function run_case(case) that takes a single argument, case, which represents the case to be executed. We create a dictionary that maps cases to their corresponding functions.
Here, we have three cases case_1, case_2, and case_3 that map to the functions case_1(), case_2(), and case_3(), respectively.
In the run_case() function, we use the get() method of the dictionary to look up the function associated with the provided case. If the case is found in the dictionary, its associated function is executed. If the case is not found in the dictionary, the default() function is executed.
One important thing to note here is that in Python, the cases are strings and the functions are defined separately and are not anonymous.
2. Using Classes
Another way to implement a switch statement in Python is by using classes and polymorphism. Let’s look at the following example:
class Case1: def execute(self): print("This is case 1")
class Case2: def execute(self): print("This is case 2")
class Switch: def __init__(self, case): self.case = case
def execute(self): self.case.execute()
case1 = Case1()case2 = Case2()
switch = Switch(case1)switch.execute() # prints "This is case 1"
switch = Switch(case2)switch.execute() # prints "This is case 2"
Output
This is case 1
This is case 2
Another way is to use the singleton pattern by adding class methods to achieve the case-like behavior:
class Case1: def execute(self): print("This is case 1")
class Case2: def execute(self): print("This is case 2")
class Case1: @classmethod def execute(cls): print("This is case 1")
class Case2: @classmethod def execute(cls): print("This is case 2")
Case1.execute() # prints "This is case 1"Case2.execute() # prints "This is case 2"
Output
This is case 1
This is case 2
3. Using Cif-elif Statements
Although the above examples show different ways to implement a switch-like functionality in Python, they both have a few limitations –
- They both rely on the cases' names being provided as strings. This means that if the cases' names change, the code will have to be updated accordingly.
- Additionally, both examples can make the code less readable, especially when there are many cases to consider.
So, we can use another way to achieve the same effect. By using if-elif statements, where elif represents else-if. Here’s an example of how:
def run_case(case): if case == 'case_1': case_1() elif case == 'case_2': case_2() elif case == 'case_3': case_3() else: default()
This method is more readable and explicit, and it doesn’t have the problem of hardcoding cases as strings, but it could be less elegant in case of large number of cases.
Switch Case Example in Python
Using Dictionary
Given below is an example of using a switch-like functionality in Python to handle different types of user input in a simple command-line calculator application:
def run_case(operator, num1, num2): options = { '+': add, '-': subtract, '*': multiply, '/': divide, } options.get(operator, default)(num1, num2)
def add(num1, num2): print(f"{num1} + {num2} = {num1 + num2}")
def subtract(num1, num2): print(f"{num1} - {num2} = {num1 - num2}")
def multiply(num1, num2): print(f"{num1} * {num2} = {num1 * num2}")
def divide(num1, num2): if num2 == 0: print("Cannot divide by 0") else: print(f"{num1} / {num2} = {num1 / num2}")
def default(num1, num2): print(f"Invalid operator. Supported operators are +, -, *, /.")
while True: num1 = float(input("Enter first number: ")) operator = input("Enter operator: ") num2 = float(input("Enter second number: ")) run_case(operator, num1, num2)
Output
Enter first number: 23
Enter operator: +
Enter second number: 2
23.0 + 2.0 = 25.0
Enter first number:
Explanation
In this example, the run_case() function takes three arguments: operator, num1, and num2. The operator argument represents the type of operation to be performed (addition, subtraction, multiplication, or division). The num1 and num2 arguments represent the operands for the operation.
The run_case() function uses a dictionary to map operators to their corresponding functions. In this example, we have four operators +, -, *, and / that map to the functions add(num1, num2), subtract(num1, num2), multiply(num1, num2), and divide(num1, num2), respectively.
In the run_case() function, we use the dictionary's get() method to look up the function associated with the provided operator. If the operator is found in the dictionary, its associated function is executed with num1 and num2 as arguments. The default(num1, num2) function is executed if the operator is not found in the dictionary.
The program runs in a while loop, prompting the user to enter the first number, operator, and second number. Then, it calls the function run_case to perform the desired operation by passing the operator and operands as arguments.
Endnotes
Hope this article was helpful for you in understanding switch case in Python. In conclusion, the switch-case statement is not a built-in feature in Python, but it can be implemented using a combination of if-elif-else statements, classes, or using a dictionary that maps the cases to its corresponding behavior. It can be a useful tool in situations where you have a large number of options and you want to avoid a long chain of if-else statements.
Check Our More Python Blogs
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio