Implementing Switch Case in Python

By | January 9, 2019

Implementation of Switch case in Python is quite different from switch case in a traditional programming language. Switch case is important for many situations where you need to do different flow for different values of the variable.

switch-case-python

A usual switch case in other programming languages will be like:

// switch statement 
switch(variable/expression)
{

   case value1 :
      // Programming Statements
      break; // optional

   case value2 :
      // Programming Statements
      break; // optional
   .
   .
   .
   case valuen :
      // Programming Statements
      break; // optional


   // We can have any number of case statements
   // default statement is executed when none of the above cases hits. 
   // No break is needed in the default case.
   default : 
      // Statements
}

 

How does the switch case works?

  • A jump table will be created for cases in the switch statement. This concept may differ in different languages.
  • The compiler evaluates the switch variable/expression and decides which block of code to execute by looking up the jump table.

Other popular programming languages like Java, PHP and C++ have friendly switch case implementation. Unfortunately or intentionally python doesn’t have the same type of implementation.

Many are using if else as an alternative to Switch in python but that’s not the actual way to do it. One of the main disadvantages of using if case the program has to evaluate every time while checking conditions. It also increases the complexity of the program making hard for code maintenance.

Python provides dictionary mapping to do it. I have implemented a piece of code that returns the Month name using Switcher implemented with a dictionary.

In the below example, we have a dictionary named my_switcher which holds the key-value pair required. We can call the get method of the dictionary passing key (which is case value in usual switch implementation) as the first argument. The second argument is the default result that we want of there is no match in the dictionary.

def switch_implementation(argument):
    my_switcher = {
        1: "January",
        2: "February",
        3: "March",
        4: "April",
        5: "May",
        6: "June",
        7: "July",
        8: "August",
        9: "September",
        10: "October",
        11: "November",
        12: "December"
    }
    print my_switcher.get(argument, "Invalid input")

 

Functions for Cases

Now comes the interesting part usually there will a piece of code you need to execute for every case as in traditional switch case. To attain that we can create a function for each case and call each function based on the result.

This may make your code look long but trust me this is going to be easier to maintain if you plan well.

In the below code, we have functions for each month possible in the switch case. Here it is simply returning the strings but you can implement the action you want to do in that function.

Python is not strict towards the data type of the values for the dictionary. So you don’t have to restrict yourself to using constants (integers, strings), you can also use function names and lambdas.

 

def one():
    return "January"
 
def two():
    return "February"
 
def three():
    return "March"
 
def four():
    return "April"
 
def five():
    return "May"
 
def six():
    return "June"
 
def seven():
    return "July"
 
def eight():
    return "August"
 
def nine():
    return "September"
 
def ten():
    return "October"
 
def eleven():
    return "November"
 
def twelve():
    return "December"
 
 
def numbers_to_months(argument):
    my_switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
        5: five,
        6: six,
        7: seven,
        8: eight,
        9: nine,
        10: ten,
        11: eleven,
        12: twelve
    }
    # Get the function from switcher dictionary
    func = my_switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print func()

Python way of watch case has advantages like changing switcher dictionary at runtime. This will help a lot with the development process.

Input: numbers_to_months(1)
Output: One
 
Input: my_switcher[1]=two #changing the switch case
Input: numbers_to_months(1)
Output: Two

 

Switch case is a powerful concept in programming and implementing that in python is quite tricky. Python also exposes how switch-case operates in the traditional way. It makes the clear that using a dictionary is far better than if-else in terms of code maintenance and performance.

Leave a Reply

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