[Tutor] "x and y" means "if x is false, then x, else y"??

Steve Willoughby steve at alchemy.com
Mon Jul 5 09:55:28 CEST 2010


On 05-Jul-10 00:27, Richard D. Moores wrote:
> See<http://docs.python.org/py3k/library/stdtypes.html#boolean-operations-and-or-not>.
> I am quite familiar with the meaning of "x and y" in Python, and how
> it is evaluated -- first x, and only if x is False, then evaluate y.
> But I just can't read "if x is false, then x, else y" that way. In
> fact, I can't read it at all. Is this a mistake in the Python 3 docs?
> If not, can someone tell me how to make sense of it?

Yes, in fact this was a common idiom before Python picked up the (x if p 
else y) syntax, and something of this nature is still commonplace in the 
Perl world (even though it has the ?: operator anyway).

You already know about the "short circuiting" effect of "and" and "or", 
which affects whether the right argument is even evaluated at all, but 
the other piece of this puzzle is that the _return value_ of the 
expression is not a pure Boolean value of True or False, but is in fact 
either the value x or y itself.

So in the case of
     x and y
if x is true, then we need to evaluate y, in which case y is returned. 
If y happened to be true, then that means both x and y were true, and 
hence the entire expression is true.  The particular "true" value we 
return here happens to be the (true) value of y.

If y is false, then returning it yields the correct false value for the 
whole expression, although the actual (false) value of y is what we return.

If x if false, then we need go no further and simply return x.

So.


1 and 2  ==>  2    (true and true ==> true)
0 and 5  ==>  0    (false and true ==> false)
'hello' and '' ==> '' (true and false ==> false)
'xx' and 'yy' ==> 'yy' (true and true ==> true)

x and y  ==>  x if x is false, else y


Some people like using this to set values to defaults if no (true) value 
was input, in a semantically pleasing manner, thus:

def __init__(self, a=None, b=None):
   self.a = a or 123
   self.b = b or 456




More information about the Tutor mailing list