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 default option so you would have to check before it fits in or make sure it will always be valid.
x = 1
print({
1 : "deu um",
2 : "deu dois",
}[x])
Or if you want 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 will have to create functions and call there.
See running on ideone . And no Coding Ground . Also I put GitHub for future reference .
if
and switch
is essentially the same thing. The only real gain from it is the optimization that some languages do, but it makes little sense in Python. switch
may have a higher syntax cost in some cases. Some languages put extra functionality in switch
.
I use a language that switch
has no advantages. I'd rather use if
same.
switch
is not a function it is a language command.