2 Simple Ways to Implement Python Switch Case Statement

Python course with 57 real-time projects - Learn Python

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 Language 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

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

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)

Output

‘Tuesday’
>>> week(0)

Output

‘Sunday’
>>> week(7)

Output

‘Invalid day of week’
>>> week(4.5)

Output

‘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.

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)

Output

‘Invalid’
>>> indirect(2)

Output

‘two’
>>> indirect(1)

Output

‘one’
>>> indirect(0.5)

Output

‘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)

Output

‘two’
>>> s.indirect(4)

Output

‘Invalid’
>>> s.number_1()

Output

‘one’

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

Python Interview Questions on Switch Case Statement

  1. Does Python have a switch case statement?
  2. How do you implement a switch case in Python?
  3. What is a case in switch statement in Python?
  4. Explain Python switch case statement with example.
  5. How many cases can you have in switch statement in Python?

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.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

13 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?

    • DataFlair says:

      I think you are asking that why we did not implement the switch cases in Python as we do with other programming languages like C++. If yes, the reason is there is no predefined switch construct in Python to use directly. So, we implement the same operation using other constructs like if-else, functions, and classes.

  4. Camilo says:

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

    • DataFlair says:

      Hi Camilo,
      If there is a function inside a class that is defined as def number_1(self,arg), then when we want to call that function using an object ‘obj’ of that class by passing the argument as 5. Then we can call it by writing obj.number_1(5). Hope I clear your doubt.

  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….

    • DataFlair says:

      We know that method() is a function that we want to call based on the value of ‘i’. Sice we are trying to call a function with another function, we are writing method(). I hope I made it clear.

Leave a Reply

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