What is Switch Case in Python?

What is Switch Case in Python?

5 mins read396 Views Comment
Updated on Aug 16, 2024 14:42 IST

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!

2023_01_MicrosoftTeams-image-120-1.jpg

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

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

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.

2023_01_switch-statement-in-python-1.jpg

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 1
run_case('case_2') # Output: Running case 2
run_case('case_4') # Output: Invalid case
Copy code

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"
Copy code

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"
Copy code

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()
Copy code

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 in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more
All About Switch Statement in C++
All About Switch Statement in C++
A switch statement in C++ allows variables to be tested for equality against set of values called case. It evaluates a given expression and executes statements associated with it based...read more
Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

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)
Copy code

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

How to Check if a Python String is a Palindrome
How to Check if a Python String is a Palindrome
A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods how to check if...read more

How to Generate Random Numbers in Python?
How to Generate Random Numbers in Python?
In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data....read more

For Loop in Python (Practice Problem) – Python Tutorial
For Loop in Python (Practice Problem) – Python Tutorial
For loops in Python are designed to repeatedly execute the code block while iterating over a sequence or an iterable object such as a list, tuple, dictionary, or set. This...read more

Calculator Program in Python: A Step-By-Step Guide
Calculator Program in Python: A Step-By-Step Guide
Looking for a powerful and user-friendly calculator program in Python? In this blog, we will discuss three different methods for calculator programs in Python. A calculator performs arithmetic operations along...read more

Conditional Statements in Python – Python Tutorial
Conditional Statements in Python – Python Tutorial
A conditional statement as the name suggests itself, is used to handle conditions in your program. These statements guide the program while making decisions based on the conditions encountered by...read more

How to Find an Armstrong Number Using Python
How to Find an Armstrong Number Using Python
Learn how to find Armstrong numbers using Python with our step-by-step guide. Discover the algorithm to identify these special numbers, which are equal to the sum of their own digits...read more

Difference Between Module and Package in Python
Difference Between Module and Package in Python
Confused with modules and packages in python, then this article is for you. This article briefly discusses the Difference Between Module and Package in Python. If you have a basic...read more

Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Difference Between Methods and Functions in Python
Difference Between Methods and Functions in Python
In Python, methods and functions have similar purposes but differ in important ways. Functions are independent blocks of code that can be called from anywhere, while methods are tied to...read more

Star Pattern in Python
Star Pattern in Python
Pattern programs in Python are a type of problem that uses nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog, we will dive...read more

Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more

Top 7 Online Python Compiler Picks for 2024
Top 7 Online Python Compiler Picks for 2024
Are you tired of installing Python on your computer? Don’t worry; we’ve got you covered with the top 7 online Python compilers for 2024! These compilers are like having a...read more

How to Compute Euclidean Distance in Python
How to Compute Euclidean Distance in Python
Euclidean Distance is one of the most used distance metrics in Machine Learning. In this article, we will discuss Euclidean Distance, how to derive formula, implementation in python and finally...read more

Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
The Bubble Sort algorithm is a simple sorting method that iterates through a given list, compares every pair of neighboring items, and exchanges them if they are out of order....read more

How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more

Types of Functions in Python
Types of Functions in Python
A function is a block of code in Python that performs a particular task. It may take zero or more inputs and may or may not return one or more...read more

Difference Between Mutable and Immutable in Python
Difference Between Mutable and Immutable in Python
Data types in Python are categorized into mutable and immutable data types. Mutable data type is those whose values can be changed, whereas immutable data type is one in which...read more

ord() and chr() Function in Python
ord() and chr() Function in Python
ord () and chr() functions of Python are built-in functions that are used to convert a character to an integer and vice-versa. In this article, we will learn how to...read more
About the Author

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