How can I check for a range of values?


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:

  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.

Extra Study

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

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"
>>> x = 75
>>> 70 <= x < 80

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

From the spoiler you posted, why doesn’t the opposite work?
For example:
def grade_converter(grade):
if grade_converter >= 90:
return “A”
elif grade_converter >= 80:
return “B”
elif grade_converter >= 70:
return “C”
elif grade_converter >= 65:
return “D”
return “F”

If I enter a value of 75, why doesn’t it see that it’s not greater than 90, then continue on to check the next elif and see that it’s not above 80, then check the next elif and return a value of ‘C’?

I wrote the exercise this way and it didn’t give the right answers - I’m just curious what I’m not understanding.

EDIT: I realize now that I was using the wrong name for my variable. I should have used “grade”, not “grade_converter”, in my if and elif statements. Once I changed that, everything worked fine.


@mtf could you possibly comment on this? This method seems to work and in my mind why over complicate things if it is unneeded. Would this method be acceptable and is there any possible reasons why this is not the best way?

That comes down to whomever is also in on the project, and what the boss expects. We have a handful of general precepts… Spec, Standards and Style Guide, plus best practices. A one-off program doesn’t need to be efficient or scalable so long as it gets the job done. Those programs we don’t fuss over. But on a long term basis, code that has to work every time and must work quickly and efficiently (meaning minimal CPU ticks) needs to meet all the criteria, and best is not one of them.

Any program that can return the letter grade for this exercise and pass the SCT is suitable. There is no best. When we are able to determine the answer to this question on our own, it would be the most meaningful. Until then I suggest learn all you can and put this sort of question aside. Don’t look for the best. Learn all the ways without bias or prejudice, but with interest.

>>> def grader (grade):
  for i, x in enumerate([60, 70, 80, 90]):
    if grade < x:
      return ['F', 'D', 'C', 'B'][i]
  return 'A'

>>> grader(89)
>>> grader(79)
>>> grader(69)
>>> grader(59)
>>> grader(90)

Got it! Thanks for the response - good to know for setting early habits.


And if we’ve wrote if grade < 30 or grade >= 10 rather than if grade < 30 and grade >= 10. Is it wrong ?

We cannot use or if both cases must be True. In such a case we must use and.

1 Like

Hello, please I’ve got a problem with an exercise, Can you help me ?.
The exercise is below

I can’t create in Python a loop that advances 5 in 5 ?

Le mer. 30 janv. 2019 à 22:25, Roy via Codecademy Forums [email protected] a écrit :

Why would a loop be required? Simple differences should be enough information to work with.

1 Like

So if I understand correctly I should test all values directly from 5 to 5 ie if speed == 75 … elif speed == 80 … elif speed == 85 … and and so on

speed - 70

This is the first basic difference that opens the next branch if greater than zero. Floor dividing a positive difference will give the demerits to be levied.

>>> speed = 85
>>> x = speed - 70
>>> x = 0 if x < 0 else x
>>> d = x // 5
>>> d
>>> speed = 65
>>> x = speed - 70
>>> x = 0 if x < 0 else x
>>> d = x // 5
>>> d

For people having problems with problem number 15 of Conditionals & Control Flow and are trying to figure out how to get a number range, here’s an amateur explanation.

let us take grade range B for an example. It asks to make it where if someone makes a 80-89 on the grading scale, give them a B. Seems simple, but it can be confusing.

What I tried to do at first was:
elif grade >= 80 and <= 89:
which is simply incorrect. As you see, it will give you a syntax error because it doesn’t know what 89 belongs to/is comparing (I believe). If you did like I did, you basically thought about it too much.
In this example, you have to use an and like below.
elif grade >= 80 and 89:

To put it in simple terms, its is solving the extra steps for you. By adding the and you are saying “else if grade is greater than or equal to 80 - 89.” It is checking all numbers between 80 and 89. If it doesn’t detect a number between 80-89, it goes down the list.

This is the great works of Python!

That code will not perform as you expect due to the way short-ciruting behaves in Python: Boolean short-cricuits-

grade = 100
if grade >= 80 and 89:
    print('Yes, this is True')
Out: 'Yes, this is True'
# Hold on. It shouldn't be...
# sanity check:
print(grade >= 80 and 89)
Out: 89
# That's not what we wanted.

You could perform the original method with all the relevant objects referenced (covered at the top of this FAQ page):

grade < 30 and grade >= 10
# This works by evaluating (grade < 30) and (grade >= 10) separately \
# It then performs a logical AND so if and only if both evalute to True \
# is the output True
A slightly more advanced method if you were particularly interested-

If you wanted to explore a shorter method you could look into chaining comparisons together for simple comparisons (since more complex ones are difficult to read): Comparisons and chaining

As an example-

for x in range(10):
    if 3 < x < 5:  # exclusively between 3 and 5 (for an integer this would be: 4)
Out: 4

The range() function can be used to check the range of values, this will give the precise result
if grade >=90:
return “A”
elif grade in range(80,89):
return “B”
elif grade in range(70,79):
return “C”
elif grade in range(65,69):
return “D”
return “F”

>>> 89 in range(80, 89)

If it won’t match 89, what about 89.5, or 89.99?

Range is fine for just integers, but we need to consider floats, as well, which doesn’t take any more logic, just the right logic.