Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 19 March, 2024

118.41K+ views
14 min read

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

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

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!

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.

Frequently Asked Questions (FAQs)

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

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

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