Usage Of The "==" Operator For Three Objects
Solution 1:
Python has chained comparisons, so these two forms are equivalent:
x == y == z
x == y and y == z
except that in the first, y is only evaluated once.
This means you can also write:
0 < x < 10
10 >= z >= 2
etc. You can also write confusing things like:
a < b == c is d # Don't dothis
Beginners sometimes get tripped up on this:
a < 100isTrue# Definitely don't do this!
which will always be false since it is the same as:
a < 100and100isTrue# Now we see the violence inherent in the system!
Solution 2:
Adding a little visual demonstration to already accepted answer.
For testing equality of three values or variables. We can either use:
>>> print(1) == print(2) == print(3)
123True>>> print(1) == print(2) andprint(2) == print(3)
1223True
The above statements are equivalent but not equal to, since accesses are only performed once. Python chains relational operators naturally. See this docs:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
If the functions called (and you are comparing return values) have no side-effects, then the two ways are same.
In both examples, the second comparison will not be evaluated if the first one evaluates to false. However: beware of adding parentheses. For example:
>>> 1 == 2 == 0False>>> (1 == 2) == 0True
See this answer.
Post a Comment for "Usage Of The "==" Operator For Three Objects"