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