P2.2.1The XOR operator
There is no exclusive-or operator provided "out of the box" by Python, but one can be constructed from the existing operators. Find two different ways of doing this. (The XOR truth table is provided below).
| P | Q | P xor Q |
|---|---|---|
| True | True | False |
| False | True | True |
| True | False | True |
| False | False | False |
Show solution
The following is equivalent to the missing exclusive-or operator a xor b
(not a and b) or (not b and a)
Alternatively, if a and b are boolean values, a != b is the same as the above. If they are not, they must be converted first:
bool(a) != bool(b)