XOR运算符未给出预期结果吗?

时间:2018-12-19 14:41:47

标签: python operators xor

我熟悉在Python中使用'and','not'和'or'运算符,并且我刚刚学习了'XOR'运算符的工作方式。

但是,当我编写此代码时,它似乎不起作用:

a = 2
b = 12

if a == 2 ^ b == 12:
    print("You must be broken") # because TRUE XOR TRUE IS FALSE

if a == 10 ^ b > 12:
    print("You must also be broken") # because FALSE XOR FALSE IS FALSE

if a < 10 ^ b > 13:
    print("This should print because TRUE XOR FALSE IS TRUE")

if a > 3 ^ b == 12:
    print("This should print because FALSE XOR TRUE IS TRUE")

程序不打印任何内容吗?

3 个答案:

答案 0 :(得分:8)

您误解了Python's operator precedence

这种情况:

a < 10 ^ b > 13

表示

a < (10^b) > 13

这意味着

(a < 10^b) and (10^b > 13)

所以它是错误的。

大概你是说:

(a < 10) ^ (b > 13)

与您的其他条件类似。

答案 1 :(得分:3)

尝试一下,您会得到疑问:

if (a == 2) ^ (b == 12):
    print("You must be broken") # because TRUE XOR TRUE IS FALSE

if (a == 10) ^ (b > 12):
    print("You must also be broken") # because FALSE XOR FALSE IS FALSE

if (a < 10) ^ (b > 13):
    print("This should print because TRUE XOR FALSE IS TRUE")

if (a > 3) ^ (b == 12):
    print("This should print because FALSE XOR TRUE IS TRUE")

之所以发生这种情况,是因为那些运营商没有像您那样思考。 查看Grant在评论中发布的有用链接。

答案 2 :(得分:1)

您错过了括号,请选中​​operators precedence,运算符^的优先级高于==

一个简单的解决方法:

a = 2
b = 12
if ( a == 2 ) ^ ( b == 12 ):
    print("You must be broken") # because TRUE XOR TRUE IS FALSE

if ( a == 10) ^( b > 12 ):
    print("You must also be broken") # because FALSE XOR FALSE IS FALSE

if ( a < 10) ^ (b > 13):
    print("This should print because TRUE XOR FALSE IS TRUE")

if  ( a > 3) ^( b == 12):
    print("This should print because FALSE XOR TRUE IS TRUE")