[ACCEPTED]-Does Python have an equivalent to 'switch'?-switch-statement

Accepted answer
Score: 41

No it doesn't. When it comes to the language 7 itself, one of the core Python principles 6 is to only have one way to do something. The 5 switch is redundant to:

if x == 1:
elif x == 5:
elif x == 10:

(without the fall-through, of 4 course).

The switch was originally introduced 3 as a compiler optimization for C. Modern 2 compilers no longer need these hints to 1 optimize this sort of logic statement.

Score: 13

Try this instead:

def on_function(*args, **kwargs):
    # do something

def off_function(*args, **kwargs):
    # do something

function_dict = { '0' : off_function, '1' : on_function }

for ch in binary_string:

Or you could use a list 2 comprehension or generator expression if 1 your functions return values:

result_list = [function_dict[ch]() for ch in binary_string]
Score: 7

As of Python 3.10.0 (alpha6 released March 30, 2021) there is an official true syntactic equivalent 7 now!

digit = 5
match digit:
    case 5:
        print("The number is five, state is ON")
    case 1:
        print("The number is one, state is ON")
    case 0:
        print("The number is zero, state is OFF")
    case _:
        print("The value is unknown")

Bringing this in as an answer for every 6 future user coming across this question. Since 5 most popular questions on this topic are 4 already closed for answering, I've written 3 up this other StackOverflow answer where I try to cover everything you 2 might need to know or take care of regarding 1 match.

Score: 0

else-if is bad practice, since they are 3 unsafe when they get too long, and involve 2 unnecessary conditional branching (maybe 1 affecting compiler / caching).

try this...

class Functions():
    def func():
        print("so - foo")
    def funcWithArgs( junk ):
        print(junk, "foo")

# fill in your cases here...
cases = {
    "a" : Functions.func ,
    "b" : Functions.funcWithArgs ,
    "c" : Functions.funcWithArgs

def switch( ch, cases, *args ):
        len(*args)  # empty args
    except TypeError:
        return cases[ ch ]( )
    return cases[ ch ]( *args )

# try out your switch...
switch("a", cases)  # "so - foo"
switch("b", cases, "b -")  # "b - foo"
switch("c", cases, "c -")  # "c - foo"
Score: 0

Switch statement is a very usefsul construction 13 in the C-language. In python it can be in 12 most cases replaced with dictionaries. I 11 think that switch statements are also very 10 useful when implementing state machines, python 9 does not have a replacement for this. It 8 usually leads to a "bad" programming 7 style to a long function. But it is the 6 switch statement, that divides the state 5 function to little pieces. In python, if 4 - elif construction must be used. Most uses 3 of switch statement can be replaced in a 2 more elegant way, some in a little bit less 1 elegant way.

Score: 0

since python 3.10 there is match-case statement `

def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:        
            return 0   # 0 is the default case if x is not found



More Related questions