[英]python XOR for two integers
Coming from a Java background into Python and working my way through CodingBat ( Python > Warmup-1 > pos_neg ) the following confused me greatly: 从Java背景进入Python并通过CodingBat( Python > Warmup -1 > pos_neg )运行时,以下内容使我非常困惑:
>>> True ^ False
True
>>> 1<0 ^ -1<0
False
I appreciate the following: 我感谢以下内容:
>>> (1<0) ^ (-1<0)
True
But what is python interpreting 1<0 ^ -1<0
as to return false? 但是,python将
1<0 ^ -1<0
为返回false是什么?
^
has higher precedence than <
. ^
优先级高于<
。
Thus, what is being evaluated is actually 1 < -1 < 0
, where 0 ^ -1 = -1
因此,要评估的实际上是
1 < -1 < 0
,其中0 ^ -1 = -1
And thus you rightly get False
, since the inequality clearly does not hold. 因此,您正确地得到
False
,因为不平等显然不成立。
You almost never have to remember the precedence table. 您几乎不必记住优先级表。 Just neatly use parenthesis.
只需整齐地使用括号即可。
You might want to check this out as well, which discusses an identical situation. 你可能想看看这出为好,其中讨论了相同的情况。
0 ^ -1
equals -1
. 0 ^ -1
等于-1
。 1 < -1 < 0
is False
since 1 is greater than -1. 1 < -1 < 0
为False
因为1大于-1。 Python chains relational operators naturally, hence 1 < -1 < 0
is equivalent to (1 < -1) and (-1 < 0)
. Python自然地链接关系运算符,因此
1 < -1 < 0
等效于(1 < -1) and (-1 < 0)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.