Does Python have an equivalent to 'switch'?

Viewed 49438

I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise it is 'ON'.

Is there a more concise way to write this code with a switch-like feature?

6 Answers

As of Python 3.10.0 (alpha6 released March 30, 2021) there is an official true syntactic equivalent 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")

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.

A switch statement is a very useful construction in the C language. In Python it can be in most cases replaced with dictionaries.

I think that switch statements are also very useful when implementing state machines, and Python does not have a replacement for this. It usually leads to a "bad" programming style to a long function. But it is the switch statement, that divides the state function to little pieces. In Python, the if - elif construction must be used. Most uses of a switch statement can be replaced in a more elegant way, some in a little bit less elegant way.

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

`

Related