Home >Backend Development >Python Tutorial >How to Achieve XOR Behavior with Logical Values in Python?
XORing Logical Values in Python
When dealing with logical values in Python, particularly when performing checks on string variables, it can be necessary to determine whether exactly one of them is True (i.e., not None or an empty string). The logical XOR operator ^ is not suitable for this purpose, as it performs bitwise operations and is not universally defined for objects.
Solution: Boolean Inequality
To achieve the desired XOR behavior, convert the variables to boolean values using the bool() function and then apply the != operator. This effectively evaluates whether the boolean values of the two variables are unequal, which satisfies the XOR condition:
<code class="python">bool(a) != bool(b)</code>
For instance, in Python, an empty string evaluates to False:
bool("") == False
Therefore, the following code snippet will output "ok" if only one of the input strings is non-empty:
<code class="python">str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if bool(str1) != bool(str2): print "ok" else: print "bad"</code>
The above is the detailed content of How to Achieve XOR Behavior with Logical Values in Python?. For more information, please follow other related articles on the PHP Chinese website!