11.7. Using elif correctly¶
In the grade printing program on the previous page, the program checked each possible grade starting with the highest (“A”) and working down to the lowest option (“F”):
if score >= 90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F")
This ordering is important, because in an if/elif/else chain, Python will not skip ahead
to “the correct” option. If we put the various grades in a mixed up order, the first if
or elif
whose condition is true is the one that will run.
In this version of the program, a score of 83 will NOT be a B. Can you see why? Try running it in codelens mode.
To avoid issues like that, we always need to put the if
/elif
options in order from
highest to lowest, or from lowest to highest. The program below shows starting with the
lowest option and working our way up. Assumes x represents a percentile and we want to
indicate which quartile it is in.
- x is in the first quartile - x <= .25
- This will only print if x is less then or equal to .25.
- x is in the second quartile - .25 < x <= .5
- This will print if the other if's were not true, and if x is less than or equal to .5. By moving lines 6-7 before lines 4-5 this will never print.
- x is in the third quartile - .5 < x <= .75
- This will print if the other if's are not true and if x is less than or equal to .75. So, moving lines 6-7 before lines 4-5 messes up what this code is intended to do and incorrectly prints that .5 is in the third quartile.
- x is in the fourth quartile - .75 < x <= 1
- This will only print if all of the other if's were false.
What would be printed if you moved lines 6-7 before lines 4-5 and set x equal to .5?
Write the code for the function tempDescription
. It should take temp
as a parameter
that represents a temperature in degrees F. It should return the string "Hot"
if the temp
is above 80, "Warm"
if it is not above 80 but is above 70, "Cool"
if it is not above 70
but is above 60, and "Cold"
otherwise (below 60).
Hint: You don’t have to solve it all at once. You can start with just an if
that only
handles temp’s greater than 80. Then add an elif
to handle the Warm temps.
Then add one for Cool…
Make sure to return
the answers and not just print
them.