Riccardo
Riccardo

Reputation: 413

Why are this operands returning False?

I have a counter-intuitive issue while writing my script in Python.

>>> def foo():
...     return False
... 
>>> foo()
False
>>> foo()==False
True
>>> i=1
>>> i!=0
True
>>> foo()==False & i!=0
False
>>> (foo()==False) & i!=0
True
>>> 

As you can see foo()==False returns True as i!=0 does, so intuitively I would expect True & True to return True, however when I run foo()==False & i!=0 I receive False and when I run (foo()==False) & i!=0 I get True as was initially expected. What is going on here?

Upvotes: 0

Views: 60

Answers (5)

Tiny.D
Tiny.D

Reputation: 6556

The reason is that there is operator precedence in python, refer to the doc:

Comparisons(==,!=) has lower precedence than Bitwise AND(&):

foo()==False & i!=0 ==> foo()==(False & i)!=0

(foo()==False) & i!=0 ==> ((foo()==False) & i)!=0

Upvotes: 1

prudhvi Indana
prudhvi Indana

Reputation: 829

As per python documentation 6.16. Operator precedence & has higher precedence than == or != therefore when you run foo()==False & i!=0 is evaluated as follows

foo()==False & i!=0
foo() == (False & True)!= 0  #since 1 is nothing but True
Foo() == False != False

which is false.

https://docs.python.org/3/reference/expressions.html#summary

I initially tried to include a table but dont know how to do that in stackoverflow. sorry.

Upvotes: 0

& is the Bitwise operator, you can use it to see if a number is even or odd. Since foo() returns False which is considered 0 and 0 is not considered an odd number, theBitwise operator & will return False because is not an odd number.

Upvotes: 0

Mo Sani
Mo Sani

Reputation: 408

& has higher precedence than == and != in python so use (foo()==False) & (i!=0) to make sure that no operand precedence conflict occurs.

Upvotes: 1

knowa42
knowa42

Reputation: 404

It's simple pythons order of operations. In

foo()==False & i!=0

the bitwise and & has a higher precedence than the ==. Thus, you're really evaluating

foo()==(False & i)!=0

If you replace your bitwise and & with a logical and and, your answer comes out as expected

>>> foo()==False and i!=0
True

Read more about it here

Upvotes: 2

Related Questions