New to Python: Features

Jeff Shannon jeff at ccvcorp.com
Tue Oct 5 16:53:27 EDT 2004


Dan Bishop wrote:

>Richard Blackwood <richardblackwood at cloudthunder.com> wrote in message news:<mailman.4286.1096945096.5135.python-list at python.org>...
>  
>
>>44. Case or Switch statements with functionality as such:
>>case score
>>when 0...40
>>   puts "Horrible!"
>>when 40...60
>>   puts "Poor"
>>when 60...80
>>   puts "You can do better!"
>>when 80...95
>>   puts "Now that's acceptable"
>>when 95..100
>>   puts "That the best you can do?  j/k"
>>else
>>   puts "Didn't take the test?"
>>end
>>    
>>
>
>Python does not have a switch/case construct.  Your example would
>normally be written as an if...elif...else ladder.
>  
>

Or, in situations where the case conditions can be narrowed to a single 
value (possibly with the aid of a custom classification function), one 
could use a dictionary dispatch.

def func1():
    print "Func1"
def func2():
    print "Func2"
def func3():
    print "Func3"

dispatcher = { 0: func1, 1: func2, 2: func3 }

i = int(score / 10)
myfunc = dispatcher[i]
myfunc()

This idiom requires a bit more in the way of setup (you're choosing an 
object, not a statement, so statements must be wrapped in 
functions/classes; the selection criteria must be a hashable value), but 
the result is (imho) a much cleaner structure.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list