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 :)
– Bianca San
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.
– Marco
@Niero when you say: 'I use a language that
switch
does not bring advantages. I prefer to use theif
even.switch
is not a function is a language command' You use theif
only by preference, or there is some loss of performance when using theswitch
? ( in languages that allow this command)– Luiz Augusto
@Luizaugusto In most languages
switch
is faster and use, in this case there is no gain the syntax is a little worse in theswitch
so I prefer not to use it, but it’s a very specific thing of that language. The command doesn’t even callswitch
in it, only he is similar and exists for reasons of legacy.– Maniero