7/9 Conditionals


#1

I got a bit confused with the conditionals used. My code is this

def get_letter_grade(score):
if score>=90:
return 'A'
elif score>=80:
return 'B'
elif score>=70:
return 'C'
elif score>=60:
return 'D'
else:
return 'F'
print get_letter_grade(get_average(lloyd))

which returns 'B', the correct grade for student Lloyd. However, I saw someone using this code

def get_letter_grade(score):
if score>=90:
return 'A'
if score>=80:
return 'B'
if score>=70:
return 'C'
if score>=60:
return 'D'
return 'F'
print get_letter_grade(get_average(lloyd))

which uses multiple 'ifs' with no 'elifs', but also returned 'B' as Lloyd grade, which is correct. Wouldn't the computer return B, C, D and F for Lloyd's score too? Unless once the the second 'if' condition is fulfilled, the computer no longer checks the rest of the conditions, which, in this case, makes me confused what the difference between using 'if' and 'elif' is in python.
And also, is using 'else' redundant since the second code returns only 'B'?


#2

@fionyao,

Maybe a diagram helps...

The construct IF ELIF ELSE must be seen as one BIG-statement.

This BIG-statement will be left at the FIRST possibilty....
and this after executing the { code-block }


[input]
   |
   |
   v
   if computerChoice < 0.34:
       computerChoice = "rock"   - -> - - - +
   |                                        v
   v                                        | 
   |                                        |
   elif computerChoice <= 0.67:             |
   |   computerChoice = "paper"  - -> - - - +
   |                                        |
   |                                        v
   v                                        |
   |                                        v
   else                                     |
       computerChoice = "scissors"   - ->- -|
                                            |
                                            v
                                          [exit]
                                  =   Value of     =
                                  = computerChoice =
                                  = has been set   =