Does Python have an equivalent to 'switch'?
Solution 1
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:
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.
Solution 2
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:
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]
Solution 3
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
.
AME
Updated on October 26, 2021Comments
-
AME over 2 years
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?
-
Glenn Maynard over 14 yearsAnyone who thinks Python "only has one way to do something" is very confused.
-
Sami Ahmed Siddiqui over 14 yearsFixed. I guess I could have claimed that it was python-esque pseudo-code, hehe.
-
Daniel Pryden over 14 years@Glenn Maynard: There may be more than one way to do it, but "There should be one -- and preferably only one -- obvious way to do it", per PEP 20 ("The Zen of Python").
-
Bastien Léonard over 14 yearsI believed
switch
's purpose was to tell the compiler to build a jump table? (I know current compilers don't need this.) -
Sami Ahmed Siddiqui over 14 years@Glenn do understand that while there are many redundant python modules, the actual core language has little in the way of redundant functionality.
-
Chris Morgan over 13 years@Soviut: by "angle brackets" I presume you meant "curly braces" (or equivalent, by locale;
{}
instead of<>
)? -
Jason over 7 yearsthe functions are needed to pass variables into scope
-
Peter Mortensen over 2 yearsA switch statement was introduced with Python 3.10 (2021).