Celebrations: Happy Thanksgiving to all our American readers!
No in-built switch statement here

How to implement a switch-case statement in Python

Sreeram Sceenivasan
© Shutterstock / LoopAll

Switch-case statements are a powerful tool for control in programming. In this article, Sreeram Sceenivasan goes over you can use a switch-case statement in Python.

Switch-case statement is a powerful programming feature that allows you control the flow of your program based on the value of a variable or an expression. You can use it to execute different blocks of code, depending on the variable value during runtime. Here’s an example of a switch statement in Java.

public static void switch_demo(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
} 

Here’s how it works:

  1. Compiler generates a jump table for switch case statement
  2. The switch variable/expression is evaluated once
  3. Switch statement looks up the evaluated variable/expression in the jump table and directly decides which code block to execute.
  4. If no match is found, then the code under default case is executed

In the above example, depending on the value of variable month, a different message will be displayed in the standard output. In this case, since the month=8, ‘August’ will be printed in standard output.

Switch statements

Although popular languages like Java and PHP have in-built switch statement, you may be surprised to know that Python language doesn’t have one. As such, you may be tempted to use a series of if-else-if blocks, using an if condition for each case of your switch statement.

However, because of the jump table, a switch statement is much faster than an if-else-if ladder. Instead of evaluating each condition sequentially, it only has to look up the evaluated variable/expression once and directly jump to the appropriate branch of code to execute it.

SEE MORE: Python jumps past Java, Javascript is still most popular language for GitHubbers

How to implement switch statement in Python

The Pythonic way to implement switch statement is to use the powerful dictionary mappings, also known as associative arrays, that provide simple one-to-one key-value mappings.

Here’s the Python implementation of the above switch statement. In the following example, we create a dictionary named switcher to store all the switch-like cases.

def switch_demo(argument):
    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 switcher.get(argument, "Invalid month") 

In the above example, when you pass an argument to the switch_demo function, it is looked up against the switcher dictionary mapping. If a match is found, the associated value is printed, else a default string (‘Invalid Month’) is printed. The default string helps implement the ‘default case’ of a switch statement.

Dictionary mapping for functions

Here’s where it gets more interesting. The values of a Python dictionary can be of any data type. So you don’t have to confine yourself to using constants (integers, strings), you can also use function names and lambdas as values.

For example, you can also implement the above switch statement by creating a dictionary of function names as values. In this case, switcher is a dictionary of function names, and not strings.

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):
    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 = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print func() 

Although the above functions are quite simple and only return strings, you can use this approach to execute elaborate blocks of code within each function.

SEE MORE: Python’s growth comes from the enormous expansion of data science and machine learning

In fact, if you’re calling methods on objects, you can even use a dispatch method to dynamically determine which function needs to be called during runtime.

class Switcher(object):
    def numbers_to_months(self, argument):
        """Dispatch method"""
        method_name = 'month_' + str(argument)
        # Get the method from 'self'. Default to a lambda.
        method = getattr(self, method_name, lambda: "Invalid month")
        # Call the method as we return it
        return method()

    def month_1(self):
        return "January"

    def month_2(self):
        return "February"

    def month_3(self):
        return "March"

... 

Based on the passed argument, the in-built getattr() function will retrieve object methods with the particular name.

Input: a=Switcher()
Input: a.numbers_to_months(1)
Output: January 

Advantage of Python’s approach

Since you can alter Python dictionaries during runtime (add, remove or update key-value pairs), you can easily change your very switch statement on the fly. Here’s an example,

def zero():
    return "zero"

def one():
    return "one"

def two():
    return "two"

switcher = {
        0: zero,
        1: one,
        2: two
    }


def numbers_to_strings(argument):
    # Get the function from switcher dictionary
    func = switcher.get(argument, "nothing")
    # Execute the function
    return func()

Input: numbers_to_strings(1)
Output: One

Input: switcher[1]=two #changing the switch case
Input: numbers_to_strings(1)
Output: Two 

Switch case is a very useful programming construct that not only provides better performance than an if-else statement but also leaves you with a more manageable code. If you’ve felt limited by the lack of switch statement in Python, then hopefully, the above tutorial will help you implement it.

Author

Sreeram Sceenivasan

For more than 8 years, Sreeram Sreenivasan has worked with various Fortune 500 Companies in areas of Business Intelligence, Sales & Marketing Strategy. He regularly writes at Fedingo about a wide range of business growth & marketing topics. He’s also the Founder & CEO of Ubiq BI, a cloud-based BI Platform for SMBs & Enterprises.


Comments
comments powered by Disqus