This baffles me. Even without knowing the precedence order, one can check that the two possible ways to gather the expression would give False
:
>>> (0 is 0) == 0 False >>> 0 is (0 == 0) False
But
>>> 0 is 0 == 0 True
How come?
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
One can argue that 0/0 is 0, because 0 divided by anything is 0. Another one can argue that 0/0 is 1, because anything divided by itself is 1. And that's exactly the problem! Whatever we say 0/0 equals to, we contradict one crucial property of numbers or another.
You are using comparison operator chaining. The expression is interpreted as:
(0 is 0) and (0 == 0)
From the Comparisons documentation:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
0 is 0
is true because Python interns small integers, an implementation detail, so you get (True) and (True)
producing True
.
When chaining comparison operators in Python, the operators aren't actually applied to the result of the other operators, but are applied to the operands individually. That is x ? y ?? z
(where ?
and ??
are supposed to stand in for some comparison operators) is neither equivalent to (x ? y) ?? z
nor x ? (y ?? z)
, but rather x ? y and y ?? z
.
This is particularly useful for >
and co., allowing you to write things like min < x < max
and have it do what you want rather than comparing a boolean to a number (which would happen in most other languages).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With