switch

rzzzwilson rzzzwilson at gmail.com
Tue Dec 8 21:07:04 EST 2009


On Dec 9, 1:00 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> On Tue, Dec 8, 2009 at 8:53 PM, hong zhang <henryzhan... at yahoo.com> wrote:
> > List,
>
> > Python does not have switch statement. Any other option does similar work?
> > Thanks for help.
>
> Use a dict instead, where the keys are the different cases and the
> values are usually callable objects (such as functions)
> options = {"a" : do_a, "b",do_b, "c", do_c}
>
> option = "a"
>
> try :
>     options[option]()
> except KeyError :
>     do_default()
>
> > --henry
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

Even better (well, shorter!):
options = {"a" : do_a, "b",do_b, "c", do_c}
options.get(option, do_default)()

Ross



More information about the Python-list mailing list