Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
Vasu Ch Avatar asked Jan 26 '23 12:01

Vasu Ch


2 Answers

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.

like image 71
kaya3 Avatar answered Jan 28 '23 01:01

kaya3


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).

like image 34
vishnu-muthiah Avatar answered Jan 28 '23 02:01

vishnu-muthiah