Why is the expression (0==0 & 1==1) evaluating to False?

試著忘記壹切 提交于 2019-12-01 17:06:59

问题


Similarly (-1==-1 & 1==1) is also False.

Apologies if this is something obvious but I can't find an explanation for it.


回答1:


& is the bitwise AND operator. As mentioned in the documentation, Bitwise operators have higher precedence than logical operators, so

0 == 0 & 1 == 1

Becomes

0 == (0 & 1) == 1

And you can imagine it goes downhill from there:

   0 == (0 & 1) == 1
=> 0 == 0 == 1
=> 0 == 0 and 0 == 1
=> True and False 
=> False

Assuming what you wanted was a logical AND, the python way to do that would be using and:

0 == 0 and 1 == 1

Which gives you True as you'd expect.




回答2:


Lets break this up.

The highest priority sign here is the brackets. Except we're wrapping the entire expression, so they don't do anything.

Next we have the bitwise operator &.

0 & 1 which equals 0.

This leaves us with 0 == 0 == 1

As 0 does not equal 1, we get False.

For reference, here is the python documentation about operator precedence.



来源:https://stackoverflow.com/questions/46782825/why-is-the-expression-0-0-1-1-evaluating-to-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!