At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

How to Implement Switch Case in Python

  • By Aishwarya Damani
  • October 15, 2019
  • 933 Views

Switch Case in Python Tutorial

In this blog, I’m going to explain how we can implement Switch case in python with various examples. Implementing Switch-case in Python can be done in one or more simple ways. Before getting into the ways to implement it, you should know what is that function and why it is in use. The switch case statement is such a powerful programming feature that allows you to control the flow of the program with the value of the variable.
When you are talking about the Switch case in Python, you might get this question in mind.
Why there is no switch case in Python like any other languages including Java, or C++?
The answer is quite simple. Many suggestions came out but nobody can give proper implementation that works with Python syntax or an established coding style. Python developers are still trying for a solution but probably none fulfills it. But you might find some good suggestions from the Python community.
The answer to the question is crystal clear that Python doesn’t have Switch case like other programming languages.
So let’s find a way to achieve it in Python.
Let’s consider an example of how we can use switch case in other languages,

string week(int i){
      switch(i){
              case 0:
                      return “Zero”
                      break;
              case 1:
                      return “One”
                      break;
              case 2:
                      return “Two”
                      break;
              default:
                      return “Invalid Number”
      }
 }

But, the above example doesn’t help in Python. As Python doesn’t have any built-in switch case, So to get this work we got to use Python’s default available dictionary.

1. The Simplest Way for Python Switch Case Statement

>>> def numbersToString(i):
       switchDict={
               0:'Zero',
               1:'One',
               2:'Two',
               3:'Three',
               4:'Four'
            }
       return switchDict.get(i,"Invalid number")

Now, Let’s call to numbersToString() method with different values.

>>> numbersToString(1)
Output - ‘One’
>>> numbersToString(2)
Output - ‘Two’
>>> numbersToString(3)
Output - ‘Three’
>>> numbersToString(77)
Output - ‘Invalid number’

Note that if we are passing any number which is not available in the dictionary it shows invalid number. This is because we are using get() method of dictionary. This method returns ‘invalid message’ or the default message if the value is not present in the dictionary.
Note: We can achieve that same using if-elif-else ladder. But, switch case is very much faster than if-elif-else ladder. So, it is better to avoid multiple if-else statements.

2. Another interesting way to implementing the Switch case

The value of the Python dictionary can be of any kind of data type. So, there is no need to fix a data type to constants like integer or string. We can use function and lambda names as values.
Take a look at the following example for a clearer understanding.

def zero():
  return "Zero"
def one():
  return "One"
def two():
  return "Two"
def three():
  return "Three"
def four():
  return "Four"
def numbersToString(i):
  switchDict={
    0:zero,
    1:one,
    2:two,
    3:three,
    4:four
  }
  return switchDict.get(i,"Invalid number")

Now, Let’s call to numbersToString() method with different values.

Success Case

>>> num = numbersToString(0)
>>> print (num)
Output - '<function zero at 0x7f1673ffa5f0>'
>>> print(num())
Output - 'Zero'

Here, numbersToString() is assigned to a variable num and if we print num, it returns the object and if we print num(), it returns the value which is defined in the function definition.

Error Case

>>> num = numbersToString(77)
>>> print(num)
Output - ‘Invalid number’
>>> num = numbersToString(77)
>>> print(num())
Output - 'TypeError: 'str' object is not callable'

In the error case, if we try to give any other argument other than what is specified in the program then, it shows TypeError: ‘str’ object is not callable as an output.
Note: In this example, you can see how we can create a dictionary of functions and use it in switch case. The above functions are quite simple as we are again returning the string value. Yet, you can see the difference between both approaches.
You can use this approach to define a block of code and execute it as per your requirement.
That’s all for switch case. I recommend you to keep an eye on the Python official document for any new update on switch case.
Hire best Python developers for your web development projects easily with Agira technologies. We provide you with dedicated experts who have mastered the latest technologies. Endure the fullest of outsourcing tech experts for your company. Get in touch with our experts to hire freelance Python developers, offshore Python developers and Python web developers who can cater to your company’s requirement.

Turn your vision to magnificent reality with
Our Web and Mobile Solutions

Aishwarya Damani

An aspiring adolescent started her career as Software Engineer Trainee and slowly she's mastering all the rising technologies like Nodejs, Express.js, React.js, MongoDB, Sails. On the other hand, a perfect decision maker who is passionate about coding. Wait! there's half a lie! Yeah, this crazy foodie has an intense long lasting affair on trying different foods & exploring places.