How to Compare 3 Numbers in Python Just Like in Math
One of the main ways that you are used to do comparisons in a programming language is the following:
a < b
Now, if you need to do a comparison with a third variable, it gets a bit clunky:
a
Yes, it does work like this, however, since you are reading this article, you probably can tell by now that there is indeed a simpler method that you can use to compare numbers.
And it is also quite straightforward.
You do not need to memorize any fancy method whatsoever. It’s just like a Math expression that you memorize from school.
If you have a value and you want to compare it whether it is between two other values, there is a simple expression that you use in Math:
1 < x < 10
That is the algebraic expression that we learn in elementary school. However, you can also use that same expression in Python as well.
Yes, you read that right. You have probably done comparisons of such form up until now:
1 < x and x < 10
For that, you simply need to use the following in Python:
1 < x < 10
Needless to say, but you can also do the other way around:
a > b > c
And yes, you can also use the equal sign with both “>” and “<”:
a >= b >= c
That’s not a new reinvention of a wheel or rocket science, but it can still be worth knowing that such a simple comparison does exist in Python.
I am a bit surprised that I do not see it being used or mentioned in more places.
More content at plainenglish.io