In article <d15d9993-90f2-43bd-824f-a1df6b7a4...@googlegroups.com>, rusi <rustompm...@gmail.com> wrote:
> On Saturday, November 9, 2013 6:38:25 PM UTC+5:30, John von Horn wrote: > > Another useful tool in the programmer's toolbox > > > Select DayofWeek > > > case "mon" > > > ... > > > end select > > > You can typically write this in python as a dictionary > > cases = {"mon": do_mon-action, > "tue", do_tue_action, > : > : > } > combined with an 'interpreter' > cases[DayofWeek]() > > Some variants: > Need a default? > cases.get(DayofWeek, do_default_action)() > > Sometimes nicer to pass some parameters: > cases[DayofWeek](some_relevant_context) All of the above is true, but a more straight-forward way to emulate a switch/case is with a series of elifs: if day_of_week == "mon": print "mondays suck" elif day_of_week == "tue": print "at least it's not monday" elif day_of_week == "wed": print "humpday!" else: print "it's some other day" I've done both. Both are reasonable translations of switch/case logic from other languages. The elif chain is more straight-forward to understand, especially for somebody new to the language. It also can support more complicated selection logic: elif day_of_week in ['sat', 'sun']: print "it's the weekend" John's version is more modular, and lends itself to doing more dynamic things like passing around sets of actions as function arguments. -- https://mail.python.org/mailman/listinfo/python-list