[Tutor] question concerning Boolean operators

Alan Gauld alan.gauld at btinternet.com
Fri Mar 21 01:56:52 CET 2008


"Guba" <listsdl04 at yahoo.de> wrote

> >>> 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.)

You created non_null as a variable when you did the assignment.

>>> non_null = string1 or string2 or string3

That's how we create variables in Python by assigning a value

The next oddity is that an 'or' operation returned a string rather
than a boolean value. That's because of two features of Python:

First, Python evaluates boolean expressions using "short circuit"
evaluation. That means that for an OR it evaluates the first
element and if its True it doesn't bother with the rest since
if any one is True the whole must be true.

Second, Python considers any non zero/non empty value to
be true, so a string is deemed to be a True value in boolean
terms to Python.

Putting that all together, you created a variable called non_null,
assigned it the value of a boolean or expression which
because of short circuit evaluation turned out to be the
first element.

> I must be missing something... Can anyone help?

You don't say if you already program in another language
but if not you will probably find one of the non-programmers
tutorials easier than Guido's official tutor which assumes
some previous experience.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list