How do you get the logical xor of two variables in Python?
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 (is not None or the empty string):
str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad"
The ^
operator seems to be bitwise, and not defined on all objects:
>>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str'
The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1. Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations. For example, when used between two integers, the XOR operator returns an integer.
The logical XOR operator is not present in C++ because it is simply an equivalent, not equal to operator with Boolean values. So a general syntax would be: A and B are Boolean values. If we look at the truth table of XOR , we know that XOR is nothing but an inequality checker for boolean values.
Exclusive or (XOR, EOR or EXOR) is a logical operator which results true when either of the operands are true (one is true and the other one is false) but both are not true and both are not false. In logical condition making, the simple "or" is a bit ambiguous when both operands are true.
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With