How can I check for a range of values?
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:
- Consider what will be true of the value if it’s in the range. What will it be greater and/or less than?
- How can we use
andto ensure both conditions we want to be true are true?
- Reiterate what is being checked on either side of an operator, otherwise it’s invalid syntax.