[Tutor] Tutor Digest, Vol 51, Issue 51

Kinuthia Muchane muchanek at gmail.com
Fri May 23 12:32:05 CEST 2008


tutor-request at python.org wrote:
> Send Tutor mailing list submissions to
> 	tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request at python.org
> 
> You can reach the person managing the list at
> 	tutor-owner at python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. Re: Equivalent 'case' statement (Alan Gauld)
>    2. Re: Equivalent 'case' statement (inhahe)
>    3. Reading only a few specific lines of a file (Jason Conner)
>    4. Re: Reading only a few specific lines of a file (John Fouhy)
>    5. Re: String Replacement question (Faheem)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Fri, 23 May 2008 00:25:23 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Equivalent 'case' statement
> To: tutor at python.org
> Message-ID: <g14vd9$97c$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
> 
> 
> "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)")
> 
Something small here. This
> print switch.[val](val)

should be: 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,
> 



More information about the Tutor mailing list