Does Python have an equivalent to 'switch'? Does Python have an equivalent to 'switch'? python python

Does Python have an equivalent to 'switch'?


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

if x == 1:    passelif x == 5:    passelif x == 10:    pass

(without the fall-through, of course).

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


Try this instead:

def on_function(*args, **kwargs):    # do somethingdef off_function(*args, **kwargs):    # do somethingfunction_dict = { '0' : off_function, '1' : on_function }for ch in binary_string:   function_dict[ch]()

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

result_list = [function_dict[ch]() for ch in binary_string]


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


digit = 5match 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")

I've written up this other Stack Overflow answer where I try to cover everything you might need to know or take care of regarding match.