[Tutor] and-or precedence

ZIYAD A. M. AL-BATLY zamb at saudi.net.sa
Mon Oct 10 17:35:24 CEST 2005


On Mon, 2005-10-10 at 17:58 +0530, Krishna wrote:
> >>> 1 or 2 and 3
> 1
> 
> Why does the above expression return 1? As per my understanding of
> boolean operations, this is what should have happaned:
> 
> 1 or 2 => 1 and then
> 1 and 3 => 3
> 
> The library reference also suggests that 'or' has higher priority than 'and'.
> http://docs.python.org/lib/boolean.html
> 
> Thanks
This is called "lazy evaluation"¹ and is used in a lot in computer
world.

Here's how it work (I'll use your example with Python):
What Python sees is this: "1 or (2 and 3)" (because of the "Left to
Right" evaluation rule).

Now, Python evaluate that first step: 1 or (something else).  What's the
outcome of that evaluation?  Remember, Python tries hard so that the
output is True.  "1" in this case is True.  For that reason Python
doesn't have an obligation to continue as it got what it wants, a
True.  
No matter what the outcome of "2 and 3" is, the result is always True.
So, it stops right there (yes, it doesn't even evaluate "2 and 3" at
all!).

To illustrate:
        >>> 0 or 2 and 3
        3

Applying what I said above:  0 or (something else) is not guaranteed to
be True since 0 is False and there's a possibility (or "hope") that
"something else" will evaluate to True, and that's the reason Python
will continue to evaluate "2 and 3" which will give us "3".

The same thing applies when using "and" instead of "or":
        >>> 1 and 2 or 3
        2
"1 and 2" is always "2" which is True.  Python stops right there.

        >>> 0 and 2 or 3
        3
In this example, what Python sees is (0 and 2) or (3).  "0 and 2" is "0"
which is False, but since there's hope because of the "or", Python
continues to evaluate the rest.  (It will be like: "0 or 3"


I'm very bad at explaining and to tip-it-off, English isn't my native
language, but I hope it was clear enough and it was helpful for you.
Ziyad.

References:
     1. http://en.wikipedia.org/wiki/Lazy_evaluation



More information about the Tutor mailing list