missing 'xor' Boolean operator

Nobody nobody at nowhere.com
Fri Jul 17 03:16:53 CEST 2009


On Thu, 16 Jul 2009 14:59:22 -0700, Emile van Sebille wrote:

>>>> If the question was "Why is there no 'or' operator ?", would "because
>>>> A or B <=> not(not A and not B)" be a proper answer ?
>>> Note that in Python A or B is in fact not equivalent to not(not A and
>>> not B).
>> 
>> Ah, but it *is* "equivalent"; it isn't "identical", but that's not the
>> point.
> 
> I'm not sure I'd call it equivalent.

That depends upon what definition of "equivalent" you are using. Apart
from all manner of vague, informal definitions, there is a formal
definition:

A relation "=" is an equivalence relation if the following hold for all
x, y, and z:

	x = x
	x = y => y = x
	x = y and y = z => x = z

An equivalence relation partitions its domain into equivalence classes,
such that an element is "=" (equivalent) to every element in the same
class, and not "=" to every element in every other class.

This is a lesser notion of equality to "identity", which also requires
that x = y => f(x) = f(y) for all f.

Python's notion of boolean values treats x and y as equivalent if
bool(x) == bool(y).

On this basis, the result of "A or B" is *equivalent* to the result of
"not(not A and not B)". If you use either result as a boolean value (e.g.
the test of an "if" or "while" statement, as an operand to "and" or "or",
etc), the effect is the same. The results aren't *identical*, as there
exist ways to distinguish the two.

As for the utility of this behaviour, returning an actual value rather
than True/False allows the operators to be used as "gates". The term
"gate" in digital logic follows from the axioms: 

	0 and x = 0
	1 and x = x

	0 or x = x
	1 or x = 1

[0 = False, 1 = True]

If you consider the left operand as the "control" and the right operand as
the "data", the control determines whether or not the data can pass
through the gate to the output (i.e. whether the gate is open or closed).

In Python:

and:
	False and 7	=> False
	False and 0	=> False
	True and 7	=> 7
	True and 0	=> 0

or:
	False or 7	=> 7
	False or 0	=> 0
	True or 7	=> True
	True or 0	=> True





More information about the Python-list mailing list