[Tutor] (no subject)

Danny Yoo dyoo at hashcollision.org
Thu May 15 06:20:44 CEST 2014


On Wed, May 14, 2014 at 9:15 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>>         if curraverage>= 90:
>>             grade= "A"
>>             lettergrades.append(grade)
>>         else:
>>             if curraverage >= 80 and curraverage < 90:
>>                 grade= "B"
>>                 lettergrades.append(grade)
>>             else:
>>                 if curraverage >= 70 and curraverage < 80:
>>                     grade= "C"
>>                     lettergrades.append(grade)
>>                 else:
>>                     if curraverage < 70:
>>                         grade= "F"
>>                         lettergrades.append(grade)
>
>
> Just wanted to note that this style of cascading if statements is a
> little unusual here.  Since you know that only one of the tests is
> going to be true, you can use a more parallel structure.


Sorry, I had combined two ideas in my post, one of which (the
exclusivity hint) is totally not relevant in this situation.  We can
do the code transformation unconditionally.  The exclusivity of the
tests doesn't matter here.


So when we see ourselves doing:

##################
if test1:
   ...
   else:
        if test2:
            ...
        else:
            if test3:
                ...
            else:
                ...
##################

we should always be able to flatten this out to this shape instead.

##################
if test1:
    ...
elif test2:
    ...
elif test3:
    ...
else:
    ...
##################


Sorry about the confusion.


More information about the Tutor mailing list