In Python we have the switch function?

Asked

Viewed 25,845 times

12

In Python we have the function switch? wanted to create a program but didn’t want to use many if, and that’s why the function switch help, but I’ve seen several videos Python lessons and no talk of switch, by chance does not exist in Python?

1 answer

17


No, in general the solution is to use if and elif:

x = 1
if x == 0:
    print("imprime 0")
elif x == 1:
    print("imprime 1")
elif x == 2:
    print("imprime 2")
else:
   print("imprime outra coisa")

Or a dictionary that generates something close, but has no option default then you would have to check before it fits into any or make sure it will always be valid.

x = 1
print({
        1 : "deu um",
        2 : "deu dois",
    }[x])

Or if you want me to do something:

print({
        1 : lambda x: x + 2,
        2 : lambda x: x - 2,
        3 : lambda x: x * 2
}[x](5))

If you want something more complex then you have to create functions and call there.

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

if and switch is essentially the same thing. His only real gain is the optimization that some languages do, but it makes little sense in Python. The switch may have a higher syntax cost in some cases. Some languages put extra functionality in switch.

I use a language that switch does not bring advantages. I prefer to use the if even.

switch is not a function is a language command.

  • Thank you so much, you helped so much :)

  • Only an addendum. There is a difference yes, even if little. On the switch for example you can not break and evaluate two or more expressions at the same time. With Elif you can’t do it, just doing an if sequence without Else, but it will slow down. What’s more, internally switch is faster according to some benchmarks, but it is questionable.

  • @Niero when you say: 'I use a language that switch does not bring advantages. I prefer to use the if even. switch is not a function is a language command' You use the if only by preference, or there is some loss of performance when using the switch ? ( in languages that allow this command)

  • @Luizaugusto In most languages switch is faster and use, in this case there is no gain the syntax is a little worse in the switch so I prefer not to use it, but it’s a very specific thing of that language. The command doesn’t even call switch in it, only he is similar and exists for reasons of legacy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.