+ 2

In CPP we've the "switch-case" statement for comparing a value with many cases. What's the equivalent for it in python?

what's the equivalent for switch statement in python other than the elif chain?

26th Sep 2017, 6:47 AM
KKS Junior
KKS Junior - avatar
4 Réponses
+ 4
Here is a neat way using a dictionary: choices = {'a': 1, 'b': 2} result = choices.get(key, 'default') You can always use if/elif/else: if x == 'a': # Do the thing elif x == 'b': # Do the other thing if x in 'bc': # Fall-through by not using elif, but now the default case includes case 'a' elif x in 'xyz': # Do yet another thing else: # Do the default
26th Sep 2017, 10:04 PM
David Ashton
David Ashton - avatar
+ 4
if: elif: (repeat as much as you want) else: Sorry bro Python is too simple, no other way. Others include if: else: if: else: if: else: (not advisable)
26th Sep 2017, 6:51 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
"elif" is same as "else-if' in CPP, there might be some easier methods.
26th Sep 2017, 6:53 AM
KKS Junior
KKS Junior - avatar
0
He is asking for Python mu friend
26th Sep 2017, 6:55 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar