-1

Why do these two equalities produce two different results in Python? I'm not sure why the first one outputs a zero; I was expecting a True.

>>> 0 and 2 >= 0
0
>>> 2 and 0 >= 0
True
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
gcamargo
  • 3,683
  • 4
  • 22
  • 34

4 Answers4

6

Because the first is parsed as

(0) and (2 >= 0)   # 0 evaluates to False

Which is evaluated to

0 and True

Which is

0

Similarly the second is

(2) and (0 >= 0)   # any non-zero digit is evaluated to True

Which is evaluated to

True and True

Which is

True

If you are trying to evaluate both digits, you could do

>>> 0 >= 0 and 2 >= 0
True

Or for many digits if you want to check against some criteria

>>> l = [1,4,6,2,7,3]
>>> all(i >= 0 for i in l)
True
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • But the first outputs 0, not False. –  Nov 13 '14 at 15:33
  • `(0) and (2 >= 0)` is *not* equivalent to `False and True`. – Vladimir Nov 13 '14 at 15:38
  • `(0) and (2 >= 0)` is not evaluated to `False and True` but `0 and True`. In fact, only `0` is evaluated due to short circuiting the expression. – Matthias Nov 13 '14 at 15:38
  • 1
    @delnan that's because Python returns the value that decides the boolean expression's result. This allows things like `config or default`: in a boolean context this will be converted to a `bool` via `__bool__` (Py3) or `__nonzero__` (Py2). – ThinkChaos Nov 13 '14 at 15:39
1

According to reference x and y is evaluated as if x is false, then x, else y. So it returns the first value without conversion to bool type. And the first value is 0.

Vladimir
  • 9,913
  • 4
  • 26
  • 37
0
>>> 2 >= 0
True
>>> 0 and True
0
>>> False and True
False

First it evaluates the expression 2 >= 0 then 0 and True. As in python 0 is equivalent to False that is why anding 0 and True gives result 0

>>> 2 and 0 >= 0
True
>>> 0 >= 0
True
>>> 2 and True
True
>>>

The same way here 2 which is greater than 0 is equivalent True. and anding them gives result True

Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
0

You're seeing the short-circuiting of the and operator. If the first operand does not evaluate to a truth value, then the first value is returned verbatim.

Compare 0 and 0 to False and False

brycem
  • 593
  • 3
  • 9