Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python boolean comparison and is [duplicate]

Tags:

python

boolean

Python 3.6.2 console:

>>> 11 > 0 is True
False

but

>>> 0 is True
False
>>> 11 > False
True

So, why 11 > 0 is True is False?

like image 284
Alex Avatar asked Jan 17 '26 20:01

Alex


1 Answers

This is an example of comparison chaining since both > and is are comparison operators.

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

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Thus, it is equivalent to:

>>> (11 > 0) and (0 is True)
False
like image 191
juanpa.arrivillaga Avatar answered Jan 19 '26 10:01

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!