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
Top Data Science Skills to Learn | ||
1 | Data Analysis Course | Inferential Statistics Courses |
2 | Hypothesis Testing Programs | Logistic Regression Courses |
3 | Linear Regression Courses | Linear Algebra for Analysis |
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.