days
-1
-3
hours
0
-6
minutes
0
-5
seconds
-1
-8
search
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.

 

Read also: An introduction to the Python programming language

When Guido van Rossum developed Python, he wanted to create a “simple” programming language that bypassed the vulnerabilities of other systems. Due to the simple syntax and sophisticated syntactic phrases, the language has become the standard for various scientific applications such as machine learning.

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.


Leave a Reply

19 Comments on "How to implement a switch-case statement in Python"

avatar
400
  Subscribe  
Notify of
Elena Lauren
Guest

Your Article is very Interesting

Daniel Lauck
Guest

Nice!

Juan M. Gonzalez
Guest

This article gives much more insight into this language than just switch cases. Thank you for showing how easy it is to tap into the power of python so concisely.

Mahendra
Guest

User is actually able to edit the above code

Brian
Guest

This demonstrates yet another reason why python is actually a poor language. People who continue to admire it even after reading this convoluted way to get around the lack of a case statement are simply members of a cult.

Jeff Wells
Guest

You’ll need to clarify which way you’re talking about, I see four different ways to replace the case statement, three of which are significantly more flexible than case, the other of which is more self contained.

The only advantage a traditional case has over the first alternative, the simple dictionary mapping, is fallthrough, which is more of a bug-prone side effect than a feature.

Andres
Guest

Just to demonstrate:

months = [“January” , “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]
nums = [x for x in range (1, 13)]
mapping = dict(zip(nums, months))

print(mapping[2])
>>> Output: “February”

Andres
Guest

I can write this in three lines. It’s not that Python is a poor language, it’s that the author isn’t a good Python coder.

Megamind
Guest

Sad but true my friend. Python has always made me wonder why Visual Basic is not the king instead. Who knows

mukul sharma
Guest

Nice work

Sonam
Guest

Thanks for sharing! It was very informative for me.

SomeGuy
Guest

Python doesn’t need a switch statement. You can do exactly the same thing with if/elif/else statements.

Jeff Wells
Guest

A switch/case statement is significantly more readable than a series of if/elif/else statements. The dictionary mapping is the real alternative to a switch/case statement, it seems better to me in just about every way.

Senad
Guest

Every language can implement it.
But some languages have it already so you don’t need to implement it by yourself.

Megamind
Guest

Are you serious? c´mon!

Megamind
Guest

nice try, but eludes the significance of the real SWITCH. If you know what I mean
alpha [a-zA-Z]
digit [0-9] %% [ \t\n]
switch return SWITCH;
int return INT;
case return CASE;
break return BREAK;
default return DEFAULT;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
. return yytext[0]; %%

Orlando Towing Partners - I-Drive
Guest

I’m glad I came across this site; very informative post.

Kim Letkeman
Guest

We can build switchers in any language, and sometimes that is exactly the right thing to do. But for clear, concise, INLINE code, the case statement easily stomps the “custom solution every time” method. I work in Python every day, and every day I scratch my head about some little thing that mitigates clarity. But I’m still a fan.

Hevlla
Guest

Thanks, help me a lot. Especially because I’m studying “Algorithm Analysis and Technique”.