# How do you get the logical xor of two variables in Python?

How do you get the logical xor of two variables in Python?

If you’re previously regularizing the inputs to booleans, then **!= is xor.**

bool(a) != bool(b)

You may always use the explanation of** xor** to compute it from other** logical operations**:

(a and not b) or (not a and b)

But this is often a touch too prolix on behalf of me, and is not significantly clear initially look. in our own way to try and do it is:

bool(a) ^ bool(b)

The xor operator on 2 booleans is logical xor (unlike on ints, wherever it’s bitwise). that is sensible, since bool is simply a taxonomic category of int, however is enforced to solely have the values zero and one. And logical xor is similar to bitwise xor once the domain is restricted to zero and one.

def logical_xor(str1, str2): return bool(str1) ^ bool(str2)

xor = bool(a) ^ bool(b)

Personally, I favor a slightly different dialect:

xor = bool(a) + bool(b) == 1

• This idiom is galvanized from a logical schematisation language I learned at school wherever** “OR”** was denoted by a box containing ≥1 (greater than or capable 1) and **“XOR”** was denoted by a box containing =1.

• This has the advantage of properly implementing exclusive or on multiple operands.**“1 = a ^ b ^ c…”** means the number of true operands is odd. This operator is “parity”.

•** “1 = a + b + c…”** means exactly one operand is true. This is “exclusive or”, meaning “one to the exclusion of the others”.

For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value,

str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad"

For example,

x = True y = False # Output: x and y is False print('x and y is',x and y) # Output: x or y is True print('x or y is',x or y) # Output: not x is False print('not x is',not x)

**Exclusive-or is already built-in to Python, in the operator module:**

*from** operator import xor
xor(bool(a), bool(b))*