落殇飞羽 发表于 2015-12-19 19:59:55

Python的"&"与'"and"的关系,逻辑运算结果不一致

本帖最后由 落殇飞羽 于 2015-12-19 21:05 编辑

x = 1;y = 2;z = 3
>>> x < y <z
True
>>> x < y <z & (x < y and y < z)
False
>>> x < y < z & (x < y and y < z)
False
>>> x < y < z & (x < y and y < z)
False
>>> x < y and y < z
True
为什么会出现下面代码的输出结果?为什么“&”与“and”结果会不一样,而且是左右双方都为“True“的时候
>>> x < y & y < z
True
>>> x < y <z & (x < y and y < z)
False
>>> x < y <z and (x < y and y < z)
True
>>> x < y <z and (x < y & y < z)
True

落殇飞羽 发表于 2015-12-19 20:55:47

本帖最后由 落殇飞羽 于 2015-12-19 20:59 编辑

~风介~ 发表于 2015-12-19 20:14
楼主自己对比一下~

谢谢 @~风介~
我去查了一下帮助文档:”The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).
其实是这段代码先运行了( z & (x < y & y < z),输出为1),造成整体运行错误,只需要加前面一个括号就ok了,代码如下:
>>> x < y <z & (x < y & y < z)
False
>>> (x < y <z )& (x < y & y < z)
True
>>> z & (x < y & y < z)
1
>>> y <z & (x < y & y < z)
False

落殇飞羽 发表于 2015-12-19 20:00:36

请各位鱼油赐教!!

~风介~ 发表于 2015-12-19 20:14:03

楼主自己对比一下~

苦哈哈 发表于 2015-12-22 10:10:07

顶一下,支持一下
页: [1]
查看完整版本: Python的"&"与'"and"的关系,逻辑运算结果不一致