Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconHow to Implement Switch Case Functions in Python? [2024]

How to Implement Switch Case Functions in Python? [2024]

Last updated:
30th Nov, 2023
Views
Read Time
14 Mins
share image icon
In this article
Chevron in toc
View All
How to Implement Switch Case Functions in Python? [2024]

Introduction

Have you ever wondered if there is an alternative to write those complex If-else statements in Python? If you do not want multiple ‘If’ statements to clutter your code, you should consider using the Switch case statement that provides a cleaner and quicker way to implement control flow in your code. Unlike C++, Java, Ruby, and other programming languages, Python does not provide a switch case statement, but it offers few workarounds to make this statement work.

For example, Python allows you to create your code snippets that work like Python Switch case statements in the other programming languages. You will get to know more about the ways of implementing switch-case statements later in this blog. If you are interested to learn more about python, check out our data science courses.

What is a Switch Statement in Python?

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 Python switch case statement 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!

Method 1: If-Elif Expressions

The Basis: Basic Structure for if-elif

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

Copy the programming

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.

Code Simplification: Maximizing if-elif Chains

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.

Elegant Python: Employing Dictionaries for Case Switch in Python

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

Copy the programming

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.

Method 2: Employing Cases in Functions

Making the Most of Functions: Determining Case Functions

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

Copy the programming

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.

Execution in Motion: Execution in Motion of a Case

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 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.

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.

Method 3: Listing Switch-Like Behavior

The Enum Class in Python: Generating Enumerations

With the help of Python’s Enum class, we can easily create enumerations and include a case switch in Python with structure 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

Copy the programming

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 case switch in Python, giving your code a concise and comprehensible depiction of the various situations it may run into.

Using the Force: Switch-Case with Listings

Now that we have our enumeration, let’s investigate how to use it to mimic a select case in Python switch-case expressions.

 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

Copy the programming

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.

The Advantages of Listing

There are various benefits to using enumerations in Python for switch-case-like behavior.

  • Readability: Using enumerations to express various scenarios is a clear and self-documenting method.
  • Maintainability: The code stays orderly, and adding or changing cases is simple.
  • Pythonic: This method adheres to the simplicity and clarity of Python switch syntax.

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.

Method 4: Applying Decorators to Switch-Like Action

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.

Creating Case Decorators in Design

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.

Selecting Cases Dynamically with Decorators

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

How to Implement Python Switch Case Statement

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 statement 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!

In the below example, we have used the C programming language

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

Explore our Popular Data Science Courses

Using Dictionary Mapping

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 integer as an input, performs a dictionary lookup, and invokes the corresponding functions.

def month(monthOfYear):

    return switcher.get(monthOfYear, default)()

The complete code will look like this

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

The above code prints the following output

February

January

Also Read: 42 Exciting Python Project Ideas & Topics for Beginners

Top Data Science Skills to Learn

upGrad’s Exclusive Data Science Webinar on the Future of Consumer Data in an Open Data Economy –

Using Python Classes

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!

Read our popular Data Science Articles

Example

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. 

  • We use the lambda keyword to define an anonymous function in Python. Lambda keyword invokes the default function when a user enters invalid input.
  • getattr() method is used to invoke a function in Python.

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”

The complete code will look like this

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

The above code prints the following output

January

October

Check out: Python Developer Salary in India

Conclusion

In this blog, you have learned about switch-case statements, what are the alternatives of switch-case statements, and how to use them. As explained above, Python does not have an in-built switch case function, but you can always use these alternatives to make your code look neat and clean and get better performance. 

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1Differentiate between an ordinary dictionary and a Python dictionary.

Python Dictionary or “Dict” is an inbuilt data structure of Python that is used to store an unordered collection of elements. Unlike other Python data structures that store single values, the dictionary data structure stores key-value pairs where every key is unique. It does not remember the insertion order of key-value pairs and iterates through the keys. On the other hand, an Ordered Dictionary or OrderedDict keeps a track of the insertion order of key-value pairs. It also consumes more memory than a regular dictionary in Python due to its doubly linked list implementation. If you delete and re-insert the same key, it will be inserted in its original position as an OrderedDict remembers the insertion order.

2What operations of namedtuple make it a convenient option to be used for switch cases?

The namedtuple in Python performs various operations. The following is a list of some of the most common operations performed by the namedtuple. The elements in a namedtuple can be accessed by their indices, unlike a dictionary. The alternative way to access the elements is by their key name. The make() function returns a namedtuple. The _asadict() function returns an ordered dictionary that is constructed from the mapped values. The _replace() function takes a key name as its argument and changes the values mapped to it. The _fileds() function returns all the key names of the given namedtuple.

3When do we prefer lists for storing data?

Python list is considered to be the best data structure to store the data in the following scenarios - A list can be used to store various values with different data types and can be accessed just by their respective indices. When you need to perform mathematical operations over the elements, a list can be used since it allows you to mathematically operate the elements directly. Since a list can be resized, it can be used to store the data when you are not certain about the number of elements to be stored. The list elements are easily mutable and it can also store duplicate elements, unlike set and dictionary.

Explore Free Courses

Suggested Blogs

4 Types of Trees in Data Structures Explained: Properties & Applications
61561
In this article, you will learn about the Types of Trees in Data Structures with examples, Properties & Applications. In my journey with data stru
Read More

by Rohit Sharma

31 May 2024

Searching in Data Structure: Different Search Methods Explained
40468
The communication network is expanding, and so the people are using the internet! Businesses are going digital for efficient management. The data gene
Read More

by Rohit Sharma

29 May 2024

What is Linear Data Structure? List of Data Structures Explained
54827
Data structures are the data structured in a way for efficient use by the users. As the computer program relies hugely on the data and also requires a
Read More

by Rohit Sharma

28 May 2024

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
317967
Summary: In this Article, you will learn about what are the 4 Types of Data in Statistics. Qualitative Data Type Nominal Ordinal Quantitative Data
Read More

by Rohit Sharma

28 May 2024

Python Developer Salary in India in 2024 [For Freshers & Experienced]
909018
Wondering what is the range of Python developer salary in India? Before going deep into that, do you know why Python is so popular now? Python has be
Read More

by Sriram

21 May 2024

Binary Tree in Data Structure: Properties, Types, Representation & Benefits
89433
Data structures serve as the backbone of efficient data organization and management within computer systems. They play a pivotal role in computer algo
Read More

by Rohit Sharma

21 May 2024

Data Analyst Salary in India in 2024 [For Freshers & Experienced]
23077
Summary: In this Article, you will learn about Data Analyst Salary in India in 2024. Data Science Job roles Average Salary per Annum Data Scient
Read More

by Shaheen Dubash

20 May 2024

Python Free Online Course with Certification [2024]
135794
Summary: In this Article, you will learn about python free online course with certification. Programming with Python: Introduction for Beginners Le
Read More

by Rohit Sharma

20 May 2024

13 Interesting Data Structure Projects Ideas and Topics For Beginners [2023]
249467
 In the world of computer science, understanding data structures is essential, especially for beginners. These structures serve as the foundation for
Read More

by Rohit Sharma

20 May 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon