How to Implement Switch Case Functions in Python? [2025]
By Rohit Sharma
Updated on Mar 12, 2025 | 14 min read | 119.0k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Mar 12, 2025 | 14 min read | 119.0k views
Share:
Table of Contents
Have you ever wondered if there’s a better way to write complex if-else statements in Python? If you want to avoid multiple if conditions cluttering your code, you should consider using the switch case in Python for a cleaner and more efficient control flow. While Python doesn’t have a built-in switch case like C++, Java, or Ruby, there are some smart workarounds to achieve similar functionality.
For example, you can write custom code snippets that work like a Python switch case, helping you organize conditions more effectively. Later in this blog, we’ll explore different ways to implement it. If you're interested in learning more about Python, check out our data science courses.
In general, the switch is a control mechanism that tests the value stored in a variable and executes the corresponding case statements. Switch case statement introduces control flow in your program and ensures that your code is not cluttered by multiple ‘if’ statements.
Hence, your code looks meticulous and transparent to viewers. It is a wonderful programming feature that programmers use to implement the control flow in their code. Switch case statement works by comparing the values specified in the case statements with variables in your code.
A switch case in Python enables a computer to select one of several possible execution routes depending on the value of a specified expression, which helps to streamline decision-making procedures. Now, the question arises ‘does Python have switch case statement?’. We should know that switch-case is not supported natively by Python; nonetheless we can get comparable results with alternative methods.
Our learners also read – python free courses!
The most common way to simulate switch case in Python is to use if-elif statements. More than 15.7 million developers use Python as their main coding language. Using an input expression as a guide, this fundamental method generates a sequence of if-elif conditions representing many scenarios.
An alternative method of managing several conditions, which differs from the traditional if-elif structure, is demonstrated in the Python switch statement example as illustrated below:
Dot Net
switch_case_example(input_value) def:
If ‘case1’ is the value of input_value:
#Code in case #1
If input_value is equal to ‘case2’:
#Code in case #2
If input_value == ‘case3’, then
# Case 3 code
#… more elif criteria as necessary
alternatively:
# Default scenario when none of the parameters are met
You can use this structure to run particular code blocks according to the value of input_value. Even while this method works, it may become burdensome when the number of cases increases.
If-elif chains may grow cumbersome as the number of cases rises, affecting the code’s readability and maintainability. We investigate methods to optimize and arrange these chains to address this.
Using the if-elif statement’s fall-through feature is one method. It enables a case to move on to the next if its condition is not met. When many cases should run the same code, this Python case statement example helps:
Dot Net
The code def optimized_switch_case(input_value) should be copied.
If input_value is present in (‘case1’, ‘case2’, ‘case3’), then
# Programming for cases 1, 2, and 3. elif input_value == ‘case4’:
# Programming for case number four: elif input_value == ‘case5’
# Case 5 code #… more elif conditions as required else:
# Default scenario when none of the parameters are met
This method shortens the code and eliminates redundancy.
The dictionaries in Python provide a sophisticated and efficient way to create switch-case logic. You can make a dictionary where the values correspond to the related code blocks, and the keys represent cases in place of a sequence of if-elif expressions, as illustrated below.
Dot Net
Switch case using dictionary def input_value(input_value):
cases: ~
‘case1’: print(“Code for case1”), lambda
‘case2’: print(“Code for case2”), lambda
‘case3’: print(“Code for case3”), lambda
#… additional instances as required
# If input_value is not in cases, default case
cases.get(lambda: print(“Default case”), input_value)Then
This method adheres to Python’s clear and expressive design principles while also streamlining and simplifying your code.
Now that you know the answer to “is there switch case in Python?” and “Does Python support switch case?”, you can use Python switch syntax skillfully by becoming proficient in these if-elif statement strategies. You can then modify your approach according to your code’s complexity and scalability requirements.
Using functions as cases is another way to simulate Python switch case syntax. This method gives each scenario its own function, improving the code’s readability and modularity. Let’s see how to apply this strategy in practice.
Step 1: Define the Case Functions
Provide distinct functions that capture the particular behavior related to each scenario. For instance:
Dot Net
case1() def:
print(“Case 1: Executing Code”)
case2() def
print(“Case 2: Executing Code”)
case3() def:
print(“Case 3 is being executed”)
#… provide more case functions as necessary
The organization and maintainability of the code are enhanced by the fact that each function contains the logic relevant to a particular scenario.
Step 2: Construct a Mapping Dictionary
Create a dictionary now that associates case names with their corresponding functions:
Dot Net
Replicate the code case_functions = { ‘case1’: case1, ‘case2’: case2, ‘case3’: case3, #… other cases as required }
This dictionary links case names to their corresponding functions as a lookup table.
You can dynamically execute case functions based on user input if you have functions representing cases and a dictionary that maps case names to functions in place. Your switch case in Python gains flexibility from its dynamic execution.
Step 3: Conduct Dynamic Case Functions
Create a system that receives input from the user, looks up the appropriate function in the dictionary, and then runs it. Here’s one instance:
Dot Net
Replicate this code: function execute_case(case_name):
# Use the dictionary to get the matching function: case_function = case_functions.get(case_name)
In the event that case_function: case_function(), #execute the case function
alternatively:
output(“Case not found”)
Using user_input as an example, input(“Enter a case:”)
run the case (user input)
By seamlessly integrating with user input, this system enables the execution of certain case functions in response to the case name entered.
Using this approach results in an expandable and modular code structure. It, therefore, only takes declaring or changing functions to add or modify situations, improving the maintainability and scalability of your application. The case statement in Python emphasizes being clean and modular to be aligned with the use of functions as cases.
The switch case in Python emphasizes being clean and modular to be aligned with the use of functions as cases.
Eager to put your Python skills to the test or build something amazing? Dive into our collection of Python project ideas to inspire your next coding adventure.
With the help of Python’s Enum class, we can easily create enumerations and include a Python switch case with structured programs. Enumerations provide a neat and structured method of expressing different situations within a program. They are simply a collection of named values.
Step 1: Establish a List
Let’s begin by reviewing the fundamentals of making enumerations with a select case in Python. You may define an enumeration like this by using the enum module:
Dot Net
from a list import. List
MyEnum(Enum) class:
Case No. 1
Case No. 2
Case No. 3
#… add more instances as necessary
Here, CASE1, CASE2, and CASE3 represent the three separate cases comprising the enumeration MyEnum. A distinct value is assigned to each switch case in Python, giving your code a concise and comprehensible depiction of the various situations it may run into.
Now that we have our enumeration, let’s explore how to use it to mimic a select case using a switch case in Python.
Step 2: Using Enumerations in Switch-Like Statements
Enumerations provide a more Pythonic solution to conventional switch-case structures. The following is an illustration of how to use enumerations within a case statement in Python:
Dot Net
Switch case using enum (case) def:
# When using Python 3.10 and later, a match statement
case of match:
MyEnum.CASE1 case:
print(“CASE1’s executing code”)
a MyEnum case.Case #2
print(“CASE2’s executing code”)
MyEnum.CASE3 case:
print(“CASE3 is being executed”)
issue _:
“Default case” is printed.
# Usage example:
Using enum, switch case (MyEnum.CASE2)
In this Python switch example, we design a switch-case-like structure using a match statement (first introduced in Python 3.10). Because every case is defined explicitly, the code is easier to comprehend and retains the expressiveness for which Python is renowned.
There are various benefits to using enumerations in Python for switch-case-like behavior.
Using enumerations improves the readability and beauty of your Python code and offers a reliable workaround for situations requiring switch-case logic. This approach is especially effective if your application deals with a limited number of unique scenarios.
In Python, decorators can be very useful tools. Let’s understand the use of decorators to construct a switch-case mechanism to improve the code’s maintainability and organization.
Discover the world of designing case decorators. Learn how to create and use decorators, specialized functions that offer a logical and structured switch-case logic for better maintainability and readability of Python scripts.
A versatile system that may be tailored to various conditions is achieved by combining decorators and dynamic case selection. This combination makes modifications adaptable and improves system responsiveness. Illustrative examples will demonstrate how to use these techniques in real-world Python programming.
Check out all trending Python tutorial concepts in 2024
If you have always coded in languages like C++ or Java, you may find it odd that Python does not have a switch case statement. Instead, Python offers numerous workarounds like a dictionary, Python classes, or Python lambda functions to implement switch-case statements.
If you want to know the exact reason behind not having a switch case in python, then you should check PEP 3103.
Before diving deep into these alternatives, let us first see how a switch case function typically works in other programming languages.
Must read: Free excel courses!
switch (monthOfYear) {
case 1:
printf(“%s”, January);
break;
case 2:
printf(“%s”, February);
break;
case 3:
printf(“%s”, March);
break;
case 4:
printf(“%s”, April);
break;
case 5:
printf(“%s”, May);
break;
case 6:
printf(“%s”, June);
break;
case 7:
printf(“%s”, July);
break;
case 8:
printf(“%s”, August);
break;
case 9:
printf(“%s”, September);
break;
case 10:
printf(“%s”, October);
break;
case 11:
printf(“%s”, November);
break;
case 12:
printf(“%s”, December);
break;
default:
printf(“Incorrect month”);
break;
}
Now, let us go further into Python switch case function alternatives and understand how these alternatives work with the help of examples.
Read: Career Opportunities in Python: Everything You Need To Know
If you are familiar with other programming languages, then you must be knowing that the dictionary uses key-value pairs to store a group of objects in memory. When you are using a dictionary as an alternative to switch-case statements, keys of the key-value pair work as a case.
The following example shows the implementation of the switch case statement using a dictionary. Here, we are defining a function month() to print which month, a month of the year is.
First, start by creating case statements and write individual functions for each case. Make sure that you write a function that tackles the default case.
def january():
return “January”
def february():
return “February”
def march():
return “march”
def april():
return “April”
def may():
return “may”
def june():
return “June”
def july():
return “July”
def august():
return “august”
def september():
return “September”
def october():
return “October”
def november():
return “November”
def december():
return “December”
def default():
return “Incorrect month”
Next, create a dictionary object in Python and store all the functions that you have defined in your program.
switcher = {
0: ‘january’,
1: ‘february’,
2: ‘march’,
3: ‘april’,
4: ‘may’,
5: ‘june’,
6: ‘july’,
7: ‘august’,
8: ‘september’,
9: ‘october’,
10: ‘november’,
11: ‘december’
}
Lastly, create a switch function in your program that should accept an integer as an input, perform a dictionary lookup, and invoke the corresponding functions.
def month(monthOfYear):
return switcher.get(monthOfYear, default)()
def january():
return “January”
def february():
return “February”
def march():
return “march”
def april():
return “April”
def may():
return “may”
def june():
return “June”
def july():
return “July”
def august():
return “august”
def september():
return “September”
def october():
return “October”
def november():
return “November”
def december():
return “December”
def default():
return “Incorrect month”
switcher = {
0: ‘january’,
1: ‘february’,
2: ‘march’,
3: ‘april’,
4: ‘may’,
5: ‘june’,
6: ‘july’,
7: ‘august’,
8: ‘september’,
9: ‘october’,
10: ‘november’,
11: ‘december’
}
def month(monthOfYear):
return switcher.get(monthOfYear, default)()
print(switch(1))
print(switch(0))
February
January
Also Read: 42 Exciting Python Project Ideas & Topics for Beginners
upGrad’s Exclusive Data Science Webinar on the Future of Consumer Data in an Open Data Economy –
You can also use Python classes as an alternative to implementing switch-case statements. A class is an object constructor that has properties and methods. Let us understand this further with the help of the same above example. Here, we will define a switch method inside a Python switch class.
Must read: Data structures and algorithm free!
First, we will define a switch method inside a Python switch class that takes a month of the year as an argument, converts the result into a string.
class PythonSwitch:
def month(self, monthOf Year):
default = “Incorrect month”
return getattr(self, ‘case_’ + str(monthOf Year), lambda: default)()
Note: In the above example, we have used two things: keyword lambda and getattr() method.
Now, create individual functions for each case.
def january(self):
return “January”
def february(self):
return “February”
def march(self):
return “March”
def april(self):
return “April”
def may(self):
return “May”
def june(self):
return “June”
def july(self):
return “July”
def august(self):
return “August”
def september(self):
return “September”
def october(self):
return “October”
def november(self):
return “November”
def december(self):
return “December”
class PythonSwitch:
def month(self, monthOf Year):
default = “Incorrect month”
return getattr(self, ‘case_’ + str(monthOf Year), lambda: default)()
def january(self):
return “January”
def february(self):
return “February”
def march(self):
return “March”
def april(self):
return “April”
def may(self):
return “May”
def june(self):
return “June”
def july(self):
return “July”
def august(self):
return “August”
def september(self):
return “September”
def october(self):
return “October”
def november(self):
return “November”
def december(self):
return “December”
my_switch = PythonSwitch()
print (my_switch.month(1))
print (my_switch.month(10))
January
October
Check out: Python Developer Salary in India
In this blog, you’ve learned about switch-case statements in Python, their alternatives, and how to use them. As explained earlier, Python doesn’t have a built-in switch case function, but you can use these alternatives to implement a switch case in Python, keeping your code clean, organized, and efficient.
If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Source:
https://peps.python.org/pep-3103/
https://www.statista.com/statistics/1241923/worldwide-software-developer-programming-language-communities/#:~:text=According%20to%20the%20survey%2C%20the,programmers%2C%20with%2015.7%20million%20developers.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources