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).

# 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

Unknown said…
Or you can make it even without dict:

num = raw_input("Enter a number between 0 and 3")

getattr(sys.modules[__name__], "fnc%s" % num, errorMessage)()

something like this ;)
Paul Wand said…
This comment has been removed by the author.
Paul Wand said…
You know, its probably better to avoid the use of the dict/switch statement and implement this with the use of inheritance/duck typing
Taoelism said…
Thanks! Looks pretty neat. Ofcourse it won't be a really good replacement for case/switch.
Anonymous said…
@Rapolas has the right idea for avoiding the redundancy of the dictionary, but doing a getattr() on the current module is unusual... just use globals(). Better yet, those functions should be methods on an object, in which case you'd be using getattr(self, 'fnc%s' % num). This is a widely used convention, often referred to using the term "dispatching".

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code