Python ,the pretty Language why can’t provide the switch-case statement like other programming languages?? May be there are many dear alternatives for Switch-Case…Python Switch Case Alternative code executes as fast as any other switch case statements..
– Here the Alternatives –
Python provides elif statement by default as alternate of switch-case. if-elif statements are execute at very fast speed as they can use for moderate sized nested conditions. e.g
i = raw_input("Enter choice from 0-3) i = int(i) if i == 0: print "you select 0" elif i==1: print "you select 1" elif i==2: print "you select 2" elif i==3: print "you select 3" else: print "sorry...wrong selection"
Other Alternative for Robust Switch-Case statement is the Programming styled offered by good authors is to store the function names in list ,and then execute the corresponding function by retrieve name from list. e.g
cases = ['zero()','one()','two()','three()'] def zero(): print "method for 0 called..." def one(): print "method for 1 called..." def two(): print "method for 2 called..." def three(): print "method for 3 called..." i = int(raw_input("Enter choice between 0-3 ")) if(i<=len(cases)): exec(cases[i]) else: print "wrong choice"
Above Code will help you in lengthy scripts…..