Newbie: Switch Case
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue May 21 04:35:20 EDT 2002
Marcus Laranjeira <m.laranjeira at datacraft.com.br> wrote in
news:mailman.1021913015.15513.python-list at python.org:
> Is there any switch case control structure in python ? what is the
> syntax ?
>
First off, please turn off the HTML formatting in your email program.
No, there is no switch/case control structure in Python. If you tell us why
you think you need one, I am sure that many of the people here will gladly
suggest alternatives. To get you started:
If all else fails, use if/elif/else.
If you want to convert an internal numeric value into a string (e.g. to
print it out), then you might use a list or a dictionary to hold the
conversions, or you might just use the string value as a token instead of
mapping it to a number in the first place.
You can also use lists or dictionaries to hold functions, so instead of
comparing against a lot of possible values you just do a dictionary lookup
and call the result.
Some people create objects with a 'type' field and use switch statements to
decide what action to perform on an object. A better way to approach this
is to make each type of object a different class and then just call an
overridden function for each action. There are also techniques such as the
visitor pattern which take this idea further.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list