[Tutor] Switch or Select?

Blake Winton bwinton@latte.ca
Fri, 11 Oct 2002 09:30:07 -0400


* James.Rocks@equant.com <James.Rocks@equant.com> [021011 03:50]:
> Hi,
> 
> Just curious ... is there any kind of switch or select statement in Python?
> I know there is if/elif/else but a switch/case/else/break style control
> structure would be quite handy :-)

Yes, there is.  The standard way to write it in Python is:
x = 3
if x == 1:
    pass
elif x == 2:
    pass
elif x == 3:
    pass
else
    pass

(Okay, so there really isn't one.  But I am kind of wondering
 why you think a switch statement is more useful than the if/elif?)

Oh, and I should probably mention that the other way to mimic a
switch statement looks something like this:
def handleOne():
    pass
def handleTwo():
    pass
def handleThree():
    pass
def handleDefault():
    pass
switch = { 1:handleOne, 2:handleTwo, 3:handleThree }

x = 3
function = handleDefault
if switch.has_key( x ):
    function = switch[x]

function()

(This is a very powerful technique, by the way.  Even if you don't
 use it now, you should keep it in the back of your mind...)

Later,
Blake.
-- 
  9:25am  up 5 days, 16:35,  1 user,  load average: 0.00, 0.00, 0.00