[ Curiosity,Experimentation ]

Random stuff from the parallel universe of Ones and Zeroes

Archive for February, 2010

An alternative to If-Else and Switch [Python]

Posted by appusajeev on February 4, 2010

You know there are times (especially in lab programs) when we have to print a menu on screen,get the choice from the user,do the usual,mechanical if-else-if or switch checks to invoke a function.
The same could be achieved with very little effort from Python avoiding condition checks

Create a list(or a tuple) containing 3-element tuples as the list members,the first member of the tuple being the string to be printed,the second being the function to be invoked and the third member being a list containing the arguments to be passed to the function.
Print the 0th element of the tuples present in the list in order,read a choice from the user and invoke the function as shown in the code.

Since python supports functional paradigm,functions are treated as first class members and hence they can inserted into lists,tuples etc
For dealing with function arguments,it would be good to have the function accept a list as its argument from which it can extract the needed arguments (which,well maynot be a good idea in cases we dont know the arguments to be passed to the function beforehand)
In case the functions that do accept any arguments,make the function accept a dummy lust as argument.

Heres an example based on the good ol’  Binary Search Tree

An alternative to If-Else and Switch

An alternative to If-Else and Switch


Posted in Python | Tagged: | 5 Comments »