How can I implement logical XOR for two variables in Python?

How can I implement logical XOR for two variables in Python? I want to check if only one of two variables, expected to be strings, contains a True value (is not None or an empty string).

Here’s an example of what I’m trying to do:

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

However, when I try to use the ^ operator for strings, I get an error:

TypeError: unsupported operand type(s) for ^: 'str' and 'str'

How can I fix this error and implement logical XOR correctly in Python?

If you’ve already converted the inputs to booleans, you can use the != operator as the logical XOR:

bool(a) != bool(b)

This expression will evaluate to True if only one of a or b is True, and False otherwise.

In Python, the logical OR (or) operator returns A if bool(A) is True, otherwise it returns B. Similarly, the logical AND (and) operator returns A if bool(A) is False, otherwise it returns B.

For a logical XOR operation, you can define a function like this:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

This function will return a, b, or False based on the XOR logic:

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'

For a simple and easy-to-understand logical XOR operation in Python, you can use:

sum(bool(a), bool(b)) == 1

This expression will return True if only one of a or b evaluates to True, and False otherwise.

If you need to select exactly one choice out of n arguments, you can expand it to multiple arguments like this:

sum(bool(x) for x in y) == 1

This expression will return True if exactly one of the elements in y evaluates to True, and False otherwise.