[Tutor] Equivalent 'case' statement

inhahe inhahe at gmail.com
Fri May 23 01:15:39 CEST 2008


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
>
>


More information about the Tutor mailing list