2 Simple Ways to Implement Python Switch Case Statement

Keeping you updated with latest technology trends, Join DataFlair on Telegram

1. Objective

In our last Python tutorial, we studied XML Processing in Python 3. Today, we will study How to implement Python Switch Case Statement. Unlike other languages like Java Programming Langauge and C++, Python does not have a switch-case construct. Along with this, we will see how to work a loophole for Python switch case statement.
So, let’s discuss different ways of Implementation for Python Switch Case Statement.

2 Simple Ways to Implement Python Switch Case Statement

2 Simple Ways to Implement Python Switch Case Statement

2. Python Switch Case Statement

Python does not have a simple switch case construct. Coming from a Java or C++ background, you may find this to be a bit odd.
In C++ or Java, we have something like this:

string week(int i){
       switch(i){
               case 0:
                       return “Sunday”
                       break;
               case 1:
                       return “Monday”
                       break;
               case 2:
                       return “Tuesday”
                       break;
               case 3:
                       return “Wednesday”
                       break;
               case 4:
                       return “Thursday”
                       break;
               case 5:
                       return “Friday”
                       break;
               case 6:
                       return “Saturday”
                       break;
               default:
                       return “Invalid day of week”
       }
  }

But Python does not have this. So, to get around this, we use Python’s built-in dictionary construct to implement cases and decided what to do when a case is met. We can also specify what to do when none is met.
Follow this link to know more about Python Dictionary
A switch case has been requested for Python, but never made it. You can refer to the following link to find out what happened:

3. Solutions for Python Switch Case Statement

One way out would be to implement an if-elif-else ladder. Rather, we can use a dictionary to map cases to their functionality. Here, we define a function week() to tell us which day a certain day of the week is. A switcher is a dictionary that performs this mapping.

>>> def week(i):
        switcher={
                0:'Sunday',
                1:'Monday',
                2:'Tuesday',
                3:'Wednesday',
                4:'Thursday',
                5:'Friday',
                6:'Saturday'
             }
         return switcher.get(i,"Invalid day of week")

Now, we make calls to week() with different values.

>>> week(2)

‘Tuesday’

>>> week(0)

‘Sunday’

>>> week(7)

‘Invalid day of week’

>>> week(4.5)

‘Invalid day of week’

As you can see, for values other than the ones we mention in the switcher, it prints out “Invalid day of week”. This is because we tell it to do so using the get() method of a dictionary.
Do you know How can Python Send Email Via SMTP Server

a. Using Python Functions & Lambdas

We can also use functions and lambdas in the dictionary.

>>> def zero():
        return 'zero'
>>> def one():
        return 'one'
>>> def indirect(i):
        switcher={
                0:zero,
                1:one,
                2:lambda:'two'
                }
        func=switcher.get(i,lambda :'Invalid')
        return func()
>>> indirect(4)

‘Invalid’

>>> indirect(2)

‘two’

>>> indirect(1)

‘one’

>>> indirect(0.5)

‘Invalid’

b. With Python Classes

Using this concept with classes lets us choose a method at runtime.

>>> class Switcher(object):
          def indirect(self,i):
                   method_name='number_'+str(i)
                   method=getattr(self,method_name,lambda :'Invalid')
                   return method()
          def number_0(self):
                   return 'zero'
          def number_1(self):
                   return 'one'
          def number_2(self):
                   return 'two'
>>> s=Switcher()
>>> s.indirect(2)

‘two’

>>> s.indirect(4)

‘Invalid’

>>> s.number_1()

‘one’

So, this was all about Python Switch Case Statement. Hope you like our tutorial.

4. Conclusion

Hence, we conclude that Python does not have an in-built switch-case construct, we can use a dictionary instead. Furthermore, if you have any queries regarding Python Switch case Statements, feel free to ask in the comment section.
Related Topic – Python GUI Programming 
For reference

10 Responses

  1. Jayeswaran says:

    Will be good if we know the module name to use appropriate for the beginners.

    • Data Flair says:

      We Respect Your Opinion!
      But in this “Python Switch Case Statement” tutorial, we do not make use of any module to implement a switch case in Python. The two ways we choose are
      1. Python Functions
      2. Python classes.
      You do not need to import any module for this.

  2. Lagu Stephen says:

    You Rock!

  3. Nisar Ali says:

    why the switch stat…. not implemented in .py?

  4. Camilo says:

    Hi, how i can pass arg in the methods ej (def number_1(self, arg):)

  5. Hamid says:

    This is not very useful to me! typically one wants to define a set of operations after each case not just look up a variable.

    • DataFlair Team says:

      Hey Hamid,

      To understand how to implement a switch case we look at an easy explanation. You are right this would be more helpful when one wants to perform multiple set of operations. So by understanding this one can easily use switch case as per their requirements.

  6. Matt says:

    1) The switch argument (key) is usually passed as a value of a variable – how would it work with classes?
    2) Under switch I also usually use functions taking arguments – I second Camilo’s question. For switch-case construction in other languages it’s straightforward, but in Python I really don’t know.

    In short – the general use of switch would be switch(key, args): … replacing
    switch key:
    case ‘a’: result=function(args)
    case ‘b’: …
    Anything short of that is not a replacement nor an implementation of switch.

  7. Me la pelan says:

    Putos me la pelan

  8. K Lam says:

    Hi! I’m new in python and I have a kinda stupid question needs some help me out:

    >>> class Switcher(object):
    def indirect(self,i):
    method_name=’number_’+str(i)
    method=getattr(self,method_name,’Invalid’)
    return method()
    def number_0(self):
    return ‘zero’
    def number_1(self):
    return ‘one’
    def number_2(self):
    return ‘two’

    why do we need to call method() instead of method? when I take off the parathesis it returns the address of my identifier, I’m so confused, don’t know how this happened. Can someone explain this to me, please….

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.