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.

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.

You have attempted of activities on this page