Python 3 布尔条件打印 false 而不是 true
Python 3 boolean condition prints false instead of true
为什么会这样?
>>> print(1==1 & 6<9)
False
>>> print(1==1 & 5<9)
True
&是按位与,见https://wiki.python.org/moin/BitwiseOperators。
一切不为 0 的都为真。你需要“和”而不是“&”。
我相信你打算组合多个条件,所以你应该使用逻辑运算符“and”而不是“&”,它是按位运算符。
将您的代码更改为以下内容:
print(1==1 and 6<9)
print(1==1 and 5<9)
1==1&6<9,
这里&先评价。
1&6
按位与,将计算为 0。
1&5
是按位和,计算结果为 1。
1==1&6<9 => 1==0<9
1==1&5<9 => 1==1<9
根据链接 (https://docs.python.org/3/reference/expressions.html#comparisons) 两者都将计算为:
1==0 and 0 < 9 ==> False
1==1 and 1 < 9 ==> True
为什么会这样?
>>> print(1==1 & 6<9)
False
>>> print(1==1 & 5<9)
True
&是按位与,见https://wiki.python.org/moin/BitwiseOperators。 一切不为 0 的都为真。你需要“和”而不是“&”。
我相信你打算组合多个条件,所以你应该使用逻辑运算符“and”而不是“&”,它是按位运算符。
将您的代码更改为以下内容:
print(1==1 and 6<9)
print(1==1 and 5<9)
1==1&6<9,
这里&先评价。
1&6
按位与,将计算为 0。
1&5
是按位和,计算结果为 1。
1==1&6<9 => 1==0<9
1==1&5<9 => 1==1<9
根据链接 (https://docs.python.org/3/reference/expressions.html#comparisons) 两者都将计算为:
1==0 and 0 < 9 ==> False
1==1 and 1 < 9 ==> True