[Tutor] if...elif question

Ignacio Vazquez-Abrams ignacio@openservices.net
Tue, 2 Oct 2001 21:24:21 -0400 (EDT)


On Tue, 2 Oct 2001, Chris Keelan wrote:

> I know the answer is staring me right in the face, but why does this little
> code snippet:
>
> ## a function to convert percentages to letter grades
> def grades(percent):
>
>     if percent < 60:
>         return 'F'
>
>     elif percent >= 60 < 70:
>         return 'D'
>
>     else:
>         return 'A'
>
> ##test the function
>
> percent=75
> mark=grades(60)
>
> print "%s percent is a grade of %s" % (percent, mark)
>
> ...produce this output:
>
> >> 75 percent is a grade of D
>
> ?!?
>
> Shouldn't the value of 75 fail the second elif test and return the 'else'
> value?
>
> What am I doing wrong?

It should read "elif percent>=60 and percent<70:". As you have it, it
evaluates "percent>=60" and then compares that against 70. Since the result of
the first is always less than 70 (either 0 or 1), it is always true.

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>