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

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

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

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.

Our learners also read – python free courses!

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

17 Must Read Pandas Interview Questions & Answers [For Freshers & Experienced]
49979
Pandas is a BSD-licensed and open-source Python library offering high-performance, easy-to-use data structures, and data analysis tools. Python with P
Read More

by Rohit Sharma

04 Oct 2023

13 Interesting Data Structure Project Ideas and Topics For Beginners [2023]
222461
In the world of computer science, data structure refers to the format that contains a collection of data values, their relationships, and the function
Read More

by Rohit Sharma

03 Oct 2023

How To Remove Excel Duplicate: Deleting Duplicates in Excel
1316
Ever wondered how to tackle the pesky issue of duplicate data in Microsoft Excel? Well, you’re not alone! Excel has become a powerhouse tool, es
Read More

by Keerthi Shivakumar

26 Sep 2023

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

by Rohit Sharma

20 Sep 2023

Information Retrieval System Explained: Types, Comparison & Components
52572
An information retrieval (IR) system is a set of algorithms that facilitate the relevance of displayed documents to searched queries. In simple words,
Read More

by Rohit Sharma

19 Sep 2023

40 Scripting Interview Questions & Answers [For Freshers & Experienced]
13569
For those of you who use any of the major operating systems regularly, you will be interacting with one of the two most critical components of an oper
Read More

by Rohit Sharma

17 Sep 2023

Best Capstone Project Ideas & Topics in 2023
2492
Capstone projects have become a cornerstone of modern education, offering students a unique opportunity to bridge the gap between academic learning an
Read More

by Rohit Sharma

15 Sep 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
294972
Summary: In this Article, you will learn about 4 Types of Data Qualitative Data Type Nominal Ordinal Quantitative Data Type Discrete Continuous R
Read More

by Rohit Sharma

14 Sep 2023

Data Science Course Eligibility Criteria: Syllabus, Skills & Subjects
46044
Summary: In this article, you will learn in detail about Course Eligibility Demand Who is Eligible? Curriculum Subjects & Skills The Science Beh
Read More

by Rohit Sharma

14 Sep 2023

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