[Tutor] question concerning Boolean operators

Steve Willoughby steve at alchemy.com
Fri Mar 21 01:02:10 CET 2008


On Thu, Mar 20, 2008 at 04:55:17PM -0700, jim stockford wrote:
>  >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>  >>> jackson = string1 or string2 or string3
>  >>> jackson
> 'Trondheim'

The key here is the "or" operator which, in an expression like

    a or b

will return a if a is a True boolean value or b otherwise.  The upshot
is that the result will be True if a OR b is True, and False only if they
are both False.  The *actual* value returned will be the value of a or b.

so here we have:

    string1 or string2 or string3

If string1 is True (which a string is if it's not empty), then that's
the result returned, and we can stop right there.

    non_null = '' or 'Trondheim' or 'Hammer Dance'

However, string1 ('') is empty, which in a Boolean context is False,
so Python goes on to string2 ('Trondheim')  That's non-empty (or True)
so we get that value and don't look further.

    non_null = 'Trondheim'

which is a True value.  If you said:

    if non_null:
        print non_null, 'is not null'
    else:
        print "it's null"

The result would be to print:

    Trondheim is not null



Hope that helps
steve

> On Mar 20, 2008, at 4:32 PM, Guba wrote:
> 
> > Dear list,
> >
> > from Guido's tutorial:
> >
> > It is possible to assign the result of a comparison or other Boolean
> > expression to a variable. For example,
> >
> > 	>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
> > 	>>> non_null = string1 or string2 or string3
> > 	>>> non_null
> > 	'Trondheim'
> >
> > How does this work?? How does Python know that we are looking for
> > non_null? After all, we don't provide this information here, right? (I
> > take non_null is a variable.)
> > I must be missing something... Can anyone help?
> >
> > Many thanks,
> >
> > Guba
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list