Does Python need an 'xor' operator?

Ken Peek Ken.Peek at SpiritSongDesigns.comNOSPAM
Sun Apr 14 18:18:06 EDT 2002


"David Eppstein" <eppstein at ics.uci.edu> wrote in message
news:eppstein-7156A5.13521614042002 at news.service.uci.edu:

| < snip >
|
| If (a xor b) is true, it must be because exactly one of
| a and b is true. So, in that case, it seems reasonable
| to return the one that is true. I'm not sure what value
| would make most sense to return when (a xor b) is false
| though.
|
| < snip >

Ahhhh!!!  that's a GREAT idea!  That way, you could write
something like:

# give me either a or b, but only if one
# of them is true, else give me false:
c = a xor b

# the above would be equivalent to:
def xor(a,b):
    if   a and not b: return a
    elif b and not a: return b
    else:             return false

c = xor(a,b) # get either a or b, or false

This would indeed make 'xor' work very similar to the 'and'
(as well as the 'or') operator(s)...

Bengt Richter pointed out that if we want a boolean result
we can just use the '!=' operator (and he is right), but
the above behavior of 'xor' would be also useful...

Good thinking Dave!






More information about the Python-list mailing list