[ Curiosity,Experimentation ]

Random stuff from the parallel universe of Ones and Zeroes

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


5 Responses to “An alternative to If-Else and Switch [Python]”

  1. Nice idea!

    Thanks for such a wonderful post, giving me a lot of new information 🙂

  2. John C said

    It’s stuff like this that makes me enjoy Python so much. You might want to check out this blog post from Jonathan Hartley: http://tartley.com/?p=805

  3. aswinatgec said

    Wow! That is a good idea!

  4. neo2904 said

    Good idea pal…..really wonderful….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: