[Tutor] Equivalent 'case' statement

Dinesh B Vadhia dineshbvadhia at hotmail.com
Sat May 24 12:36:48 CEST 2008


The dictionary of functions was the way to go and does perform much faster than if/elif's.  Thank-you!  


----- Original Message ----- 
From: inhahe 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Thursday, May 22, 2008 4:15 PM
Subject: Re: [Tutor] Equivalent 'case' statement


no, but you can
a) use elifs
if c==1:
  do this
elif c==2:
  do this
elif c==3:
  do this

b) make a dictionary of functions (this is faster)

def case1: do this
def case2: do that
def case3: do the other

cases = {1: case2, 2: case2, 3:case3}

cases[c]()

if your functions are one expression you could use lambdas

cases = {
1: lambda: x*2
2: lambda: y**2
3: lambda: sys.stdout.write("hi\n")
}

cases[c]()

your functions and lambdas can also take parameters of course




On Thu, May 22, 2008 at 5:53 PM, Dinesh B Vadhia
<dineshbvadhia at hotmail.com> wrote:
> Is there an equivalent to the C/C++ 'case' (or 'switch') statement in
> Python?
>
> Dinesh
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080524/34699c5a/attachment.htm>


More information about the Tutor mailing list