Vasu Ch
Vasu Ch

Reputation: 305

Basic Boolean expression in Python producing surprising results

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

Answers (3)

Rohit Dwivedi
Rohit Dwivedi

Reputation: 104

Comparision Docs

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

vishnu-muthiah
vishnu-muthiah

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

kaya3
kaya3

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.

From the docs:

Comparisons can be chained arbitrarily; for example, 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).

So, the expression 2 > 3 == False is equivalent to 2 > 3 and 3 == False, which is False.

Upvotes: 6

Related Questions