How do you get the logical xor of two variables in Python?
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"