30
votes

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.?

5
Are you trying to do [{'0':'Off', '1':'On'}.get(b) for b in "01101101"] - joeforker

5 Answers

39
votes

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.

12
votes

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]
3
votes

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")

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

0
votes

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

try this...

class Functions():
    @staticmethod
    def func():
        print("so - foo")
    @staticmethod
    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 ):
    try:
        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"
-1
votes

Switch statement is a very usefsul 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, 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, if - elif construction must be used. Most uses of switch statement can be replaced in a more elegant way, some in a little bit less elegant way.