Reputation: 305
In Python I have 2>3 == False
which gives False
. But I'm expecting True
. If I use parenthesis i.e (2>3) == False
then I'm getting True
. What is the theory behind this?
Upvotes: 4
Views: 83
Reputation: 104
all the 8 comparison operators have the same precedence.
so in 2 > 3 and 3 == False
the evaluation is from left to Right
first 2>3
is evaluated. the next condition 3==False
will only be evaluated if the first expression holds true. But here 2>3 holds false hence it returns false and doesn't even evaluates third expression
Upvotes: 1
Reputation: 11
In Python, 2 > 3 == False
is evaluated as 2 > 3 and 3 == False
.
This para from the Python reference should clarify:
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.
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).
Upvotes: 1
Reputation: 51037
This is because of a feature of Python which is quite unusual compared to other programming languages, which is that you can write two or more comparisons in a sequence and it has the meaning which is intuitive to mathematicians. For example, an expression like 0 < 5 < 10
is True
because 0 < 5 and 5 < 10
is True
.
Comparisons can be chained arbitrarily; for example,
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).
So, the expression 2 > 3 == False
is equivalent to 2 > 3 and 3 == False
, which is False
.
Upvotes: 6