Quantcast
Viewing all articles
Browse latest Browse all 314

XOR (Exclusive Or) in Python

This article explains XOR (Exclusive Or) – what it is, why it’s used, and how to implement it in the Python programming language.

What is XOR / Exclusive OR

XOR – Exclusive Or – is a logical operation commonly used in computer programming.

Logically, an XOR condition is true only if the supplied arguments differ.

XOR compares two inputs and outputs, true or false, only if they are different. Those inputs are usually true/false boolean values or the result of a logical operation that returns a boolean value.

For example, XOR on two values – 1 and 1 is false – they do not differ.

XOR on two values – 0 and 1 is true, as they differ.

Uses for XOR

XOR is widely used in cryptography and when comparing data.

Checksums are used to verify data integrity – the data generated and the comparison use XOR operations to do this. There’s a really good breakdown of how this is done here, but it’s beyond the scope of this article.

More generally, you’ll find yourself using XOR in many logical comparison operations – you may have used it already and just not known that it has a name.

XOR in Python

Implementing XOR in Python is easy – get the boolean value of two variables or values and compare them for inequality – if they are not equal, the statement will return true.

This is an XOR statement in Python:

bool(value1) != bool(value2)

Super simple. The result from other logical operations can also be used:

(value1 == 3) != (value2 == 3)

Above, two variables (value1 and value2) are compared separately to see if they are equal to 3, and the XOR is calculated. If one value is equal to 3 and the other is not, the XOR will return true. If both are equal to 3 or neither is, the XOR will return false.

View the original article from LinuxScrew here: XOR (Exclusive Or) in Python


Viewing all articles
Browse latest Browse all 314

Trending Articles