Many will be surprised that such a user friendly language as python does not provide something a like a switch-case. Wow! Isn’t that something that should come with the language by default. Why did python not opt it in? You could read this chain. But all the more reason to read this article to get around this inability and like all thing in python this too is fairly simple. You would kick yourself for not figuring out. I would put the code in first… here!
def madrid():
print "Welcome to Madrid"
def geneva():
print "Welcome to Geneva"
def hawaii():
print "Welcome to Hawaii"
def unknown():
print "I cannot take you there. Sorry!"
#destinations = {"madrid":madrid,"geneva":geneva,"hawaii":hawaii}
#incorporating drj11's suggestions for he feels awkward and its true.
#Thanks drj11
destinations = dict(madrid=madrid,geneva=geneva,hawaii=hawaii)
destination = raw_input("Where do you want to go today? ")
destinations.get(destination,unknown)()
Two things that you need to take care while using the above given method
- Always create your dictionary after the function definition. You check out what happens if you dont do that
- Make sure sure you pass the second argument to the dict.get method as this works like the “default” case of your standard switch statement.
The code is pretty straightforward and needs no explanation.