>>> 5 > 4 & 6 > 5
Why does the above expression give False
in Python, if 5 > 4
is True
and 6 > 5
is also True
?
>>> 5 > 4 & 6 > 5
Why does the above expression give False
in Python, if 5 > 4
is True
and 6 > 5
is also True
?
Because &
(bitwise "and") has a higher precedence than >
, so 5 > 4 & 6 > 5
is actually evaluated as 5 > 4 > 5
which is obviously False
.
Operator precedence on Python docs.
In python the &
operator represents the bitwise AND operator, which basically takes the binary form of an integer, and masks the binary form of the first number by the second number.
For example, 10 & 3
returns 2
because the binary form of 10
is 1010
, and with the mask of 3
, we take the last three digits, and find the value of the resulting binary. In this case, it's 010
, which in decimal is 2
.
The operator you're looking for is the literal and
operator!:
>>> 5 > 4 and 6 > 5
True
Or better (I believe you already know this):
>>> 6 > 5 > 4
True