Boolean confusion

Diez B. Roggisch deets at nospam.web.de
Wed May 9 08:45:12 EDT 2007


Greg Corradini wrote:

> 
> Hello all,
> I'm having trouble understanding why the following code evaluates as it
> does:
> 
>>>> string.find('0200000914A','.') and len('0200000914A') > 10
> True
>>>> len('0200000914A') > 10 and string.find('0200000914A','.')
> -1
> 
> In the 2.4 Python Reference Manual, I get the following explanation for
> the 'and' operator in 5.10 Boolean operations:
> " The expression x and y first evaluates x; if x is false, its value is
> returned; otherwise, y is evaluated and the resulting value is returned."
> 
> Based on what is said above, shouldn't my first expression (
> string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to
> false b/c my 'x' is false? And shouldn't the second expression evaluate to
> True?

The first evaluates to True because len(...) > 10 will return a boolean -
which is True, and the semantics of the "and"-operator will return that
value.

And that precisely is the reason for the -1 in the second expression. 

y=-1

and it's just returned by the and.

in python, and is implemented like this (strict evaluation nonwithstanding):

def and(x, y):
    if bool(x) == True:
       return y
    return x

Diez



More information about the Python-list mailing list