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?
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.
From the docs:
Comparisons can be chained arbitrarily; for example,
x < y <= zis equivalent tox < y and y <= z, except thatyis evaluated only once (but in both caseszis not evaluated at all whenx < yis found to be false).
So, the expression 2 > 3 == False is equivalent to 2 > 3 and 3 == False, which is False.
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).
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