Checking Numeric Ranges
As you’ve seen before,
and is frequently used to connect conditions which describe the lower and upper limits of a range of numbers. To be between
10 inclusively, a number must be at least
0 and less than or equal to
you can call it a few times.
5 is greater than or equal to
0, and it’s less than or equal to
10. Since both our expressions are true, the
and of them is
True, and this function will return
You can test if a number is in a different range by supplying values for those parameters. In this case,
20 is greater than or equal to
10, and it is less than or equal to
40, so the whole thing is true.
and is used when you want to check if a number is within a certain range. However, if you want to check if a value is outside a given range, you have to use
or. If a number is not within the range of
10 inclusively, then it’s either less than
0 or greater than
You can do this in Python as well. The expression
0 <= x <= 10 is valid in Python. So I could replace the
and operation in this function with
start <= number <= end. Save this, restart the REPL, and import it again.
And they do. Please notice that most other languages do not allow this syntax. Next, and finally, you’ll look at how
and can be used to chain function calls where one function call actually depends on the success of a previous one.
Become a Member to join the conversation.