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

Walter Prins wprins at gmail.com
Mon Jul 5 13:54:46 CEST 2010


On 5 July 2010 08:27, Richard D. Moores <rdmoores at gmail.com> 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.
>

Sorry if this is being overly pedantic, but I thought I'd point out the
above isn't right as stated, although I understand what you're getting at
(re short circuit boolean evaluation) in general.  To be correct, I presume
you meant "OR" where you wrote "AND", as it would be correct in that case
e.g:

x AND y: Will only evaluate y if x is TRUE. (If x is FALSE then you don't
need to evaluate y since the resultant expression will be FALSE regardless,
see footnote 2 in the page you referenced.)

x OR y:  Will only evaluate y if x is FALSE. (If x is TRUE then you don't
need to evaluate y since the resultant expression will be TRUE regardless,
see footnote 1 in the page you referenced.)

See e.g. output of this. <http://pastebin.com/6c6UWcTQ>

So then, to explain this line from the page you reference: x and y:
"if *x*is false, then
*x*, else *y"

*Think about it: As per the above, if x is false, then because it's false,
Python need only and will only evaluate x, and will therefore essentially
return whatever "x" is when evaluating the expression.  If x is true on the
other hand, then by the above rules, it has to *also* evaluate y as well,
and so will end up effectively returning whatever y returns as it determines
what the truth value of the overall expression is.  Shortening that
reasoning, you can say, "if x is false, then x, else y". See?  (The same
sory of reasoning applies for the "or" case if you think it out.)
*
*Hope that helps.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100705/0568a743/attachment.html>


More information about the Tutor mailing list