[Tutor] Equivalent 'case' statement

Alan Gauld alan.gauld at btinternet.com
Fri May 23 01:25:23 CEST 2008


"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote

> Is there an equivalent to the C/C++ 'case' (or 'switch') statement 
> in Python?

No, just if/elif

However you can often achieve similar results with a dictionary:

def func1(v): return v

def func2(v): return v*2


switch = { 'val1': func1,             # use a function for each value
                'val2': func2,
                 'val3': lambda v: "this is three!" }     # or use 
lambda if preferred

val = raw_input("Value? (val1,val2,val3)")

print switch.[val](val)


### which is equivalent to:

if val == 'val1': print func1(val)
elif val == 'val2': print func2(val)
elif val == 'val3': print "this is three"

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list