"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Implement Logical XOR for Non-Boolean Variables in Python?

How Can I Implement Logical XOR for Non-Boolean Variables in Python?

Published on 2024-11-14
Browse:669

How Can I Implement Logical XOR for Non-Boolean Variables in Python?

Xor Operation in Python: Beyond Bitwise Logic

Understanding the logical XOR operation in Python can be tricky, especially when comparing non-boolean variables like strings. The bitwise ^ operator, commonly used for bitwise XOR, falls short for this purpose.

Solution: Boolean XOR

If the goal is to check if exactly one of two variables contains a True value, a simple solution is the != operator. This checks if the boolean values of the two variables differ. So, for strings:

bool(str1) != bool(str2)

This will return True if one variable is not None or an empty string while the other is, fulfilling the XOR condition.

Example

Using the example code:

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

This code will correctly determine whether only one string contains a non-empty value and print "ok" in that case.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3