Newbie: switch question in Python
Greg Ewing
greg.ewing at compaq.com
Fri Dec 3 09:51:46 EST 1999
"William J. King" wrote:
>
> -- so I wrote a switch and would like to know if
> its ok to do this or if you have any other better
> ideas...
Using exec for things like this is extremely inefficient,
and tends to suffer from scoping problems. A neater way
would be
def case1:
for m in range(1,3):
print m
def case4:
for m in range(4,7):
print m
#...etc...
switch = {
1: case1,
4: case4,
...
}
# ...and to call it...
switch[q]()
But unless you really need the speed, it's a lot clearer
still just to write a series of if...elifs.
Greg
More information about the Python-list
mailing list