AME AME - 4 months ago 15
Python Question

Does Python have an equivalent to 'switch'?

I am trying to check each index in an 8 digit binary string. If it is

'0'
then it is
'OFF'
otherwise its
'ON'
.

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

Answer

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

if x == 1:
    pass
elif x == 5:
    pass
elif 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.