How can I check for a range of values?


#1

Question

How can I check for a range of values?

Answer

There are a few key parts of converting sentences to logic, like we must in this problem. One such sentence is “90 or higher should get an ‘A’”. How do we write this in code?
While this one is given in the hint, let’s use it to understand how we could check for a range of values or write any other English sentence in logical code form.
90 or higher tells us that it can be equal to 90 or greater. Great! We know that the comparator >= handles both of those things by itself!
What about more complex things, like ranges, though? I don’t know of any comparator we’ve learned of that checks for a value to be in a range like 80-89. But! I do know that we can combine comparators and boolean operators to achieve this!
If a number is in a range, it will be true that it is less than the max, and greater than or equal to the minimum values in that range. For example, if we wanted to check if grade is in the range 10-29, we could write if grade < 30 and grade >= 10.
Notice how we have to reiterate what we are comparing on both sides of the and, otherwise we get a syntax error, like this: if grade < 30 and >= 10, because the right side has no idea what you are comparing 10 to.

So the key elements to remember are:

  1. Consider what will be true of the value if it’s in the range. What will it be greater and/or less than?
  2. How can we use and to ensure both conditions we want to be true are true?
  3. Reiterate what is being checked on either side of an operator, otherwise it’s invalid syntax.

FAQ: Learn Python - Conditionals & Control Flow - The Big If
#2

Extra Study

From a straight control flow point of view, we can do this without using logical and, using a strict order of conditionals.

spoiler
if grade < 60: letter = 'F'
elif grade < 70: letter = 'D'
elif grade < 80: letter = 'C'
elif grade < 90: letter = 'B'
else: letter = 'A'

Something of note is that Python supports mathematical inequality expressions with multiple operands/operators to help with ranges between two values.

>>> x = "G"
>>> "A" <= x <= "M"
True
>>> x = 75
>>> 70 <= x < 80
True

In the first example the unseen numerical value is the ordinal of the letter. ‘G’ => 71; ‘A’ => 65, ‘M’ => 77.

The beauty is in their simplicity: 70 <= x < 80 versus 70 <= x and x < 80. We have options, now. Either form is valid and up to the author to choose.

>>> a = 6
>>> b = 7
>>> c = 8
>>> a < b < c
True
>>> 

#3

This is wrong you stupid bot


#4

Okay, please point out what is wrong, and how to correct it. If there is no reply today, your account will be suspended for causing a disruption and insulting other members.