switch-case alternative in Python
Python has so 'switch - case' support unlike most other common languages. Of course you can use If-else block to serve your purpose. But there is an elegant alternative to 'switch-case' in python, using dictionary. Go though the following code (you should try running it).
Hope you will find it interesting!
# this is the default function
def errorMessage():
print "Incorrect input. Please enter a number between 0 and 3."
def fnc0():
print "This is function 0"
def fnc1():
print "This is function 1"
def fnc2():
print "This is function 2"
def fnc3():
print "This is function 3"
fncDict = {'0': fnc0, '1': fnc1, '2': fnc2, '3': fnc3}
num = raw_input("Enter a number between 0 and 3")
# if num is found as a key in the dictionary fncDict, then corresponding function is called
# else the function errorMessage is called
fncDict.get(num, errorMessage)()
Hope you will find it interesting!
Comments
num = raw_input("Enter a number between 0 and 3")
getattr(sys.modules[__name__], "fnc%s" % num, errorMessage)()
something like this ;)