简体   繁体   中英

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:

    >>> 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?

^ has higher precedence than < .

Thus, what is being evaluated is actually 1 < -1 < 0 , where 0 ^ -1 = -1

And thus you rightly get False , since the inequality clearly does not hold.

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 . 1 < -1 < 0 is False since 1 is greater than -1. Python chains relational operators naturally, hence 1 < -1 < 0 is equivalent to (1 < -1) and (-1 < 0) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM