Skip to content

Instantly share code, notes, and snippets.

@James-E-A
Last active April 7, 2025 16:15
Show Gist options
  • Save James-E-A/5b99bf2fc5a1d44c8824f6ce2c5ec3c1 to your computer and use it in GitHub Desktop.
Save James-E-A/5b99bf2fc5a1d44c8824f6ce2c5ec3c1 to your computer and use it in GitHub Desktop.
Python boolean XOR
#!/usr/bin/env python3
__all__ = ['logical_xor']
def logical_xor(a, b):
# technically, all of the parentheses on the following line may be removed
return ((not b) and a) or ((not a) and b)
# correct
assert logical_xor(True, False)
assert logical_xor(False, True)
assert not logical_xor(True, True)
assert not logical_xor(False, False)
# pythonic: in the return-truthy path, the sole truthy operand will be returned as-is
assert (42 or 0) == logical_xor(42, 0) == 42
assert (0 or 42) == logical_xor(0, 42) == 42
# pythonic: in the two-falsies path, the latter operand will be returned as-is
assert type(0 or 0.0) == type(logical_xor(0, 0.0)) == float
assert type(0.0 or 0) == type(logical_xor(0.0, 0)) == int
# pythonic: in the two-truthies path, literal False is returned due to semantic negation
assert (not 42) is logical_xor(42, 69) is False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment