What is the Python equivalent for a case/switch statement?

PythonSwitch StatementMatchCase

Python Problem Overview


Is there a Python equivalent for the switch statement?

Python Solutions


Solution 1 - Python

Python 3.10 and above

In Python 3.10, they introduced the pattern matching.

Example from the Python documentation:

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"

        # If an exact match is not confirmed, this last case will be used if provided
        case _:
            return "Something's wrong with the internet"
Before Python 3.10

While the official documentation are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

Solution 2 - Python

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python";.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn AlleyView Question on Stackoverflow
Solution 1 - PythonPrashant KumarView Answer on Stackoverflow
Solution 2 - PythonLennart RegebroView Answer on Stackoverflow