[Edu-sig] Truth values and comparisons

John Zelle john.zelle at wartburg.edu
Mon Oct 30 18:07:04 CET 2006


On Monday 30 October 2006 10:49 am, Arthur wrote:
> davelist at mac.com wrote:
> >I've not used .any or .all, but having just taught my CS1 students about
> > boolean operators, I was reminded that Python works as the following
> > example describes:
> >
> >x = a and b
> ># if both a and b are true, x is assigned b, otherwise x is assigned a
> >x = 2 and 3 # x is assigned 3
> >x = 0 and 2 # x is assigned 0
> >
> >x = a or b
> ># if a is true, x is assigned a, if a is true, x is assigned a, if a is
> > false and b is true, x is assigned b, if both a and b are false, x is
> > assigned False
> >
> >You need to determine what should make vertex_map[tp] be true...
>
> thanks, but having some trouble:
>  >>> import Numeric as N
>  >>> a=N.array([0,0,0])
>  >>> b=N.array([0,0,1])
>  >>> a and b
>
> array([0, 0, 0])

This tells me that a zero array is being treated as False (the logical 
extension to arrays of 0 being false. 
>
>  >>> b and  a
>
> array([0, 0, 0])

Right. In both cases, the answer is False, which Python gives to you by 
handing you the first False expression. In either case the false part of the 
and is the 0 array, while the other is True (a non-zero array).

You can check this out:

>>> not(a)
True

>>> not(b)
False

>
> Can this be?  Either both a and b are true, or they are not,  so can it
> be returning the "a" in both cases? Something screwy, other than my
> comprehension here?

Because a is False ;-). They're not both true.

> Same problem with
>
>  >>> a or b
>
> array([0, 0, 1])
>
>  >>> b or a
>
> array([0, 0, 1])
>

This works the same way, but returns the first True expression as the value 
of "True."

>  >>> any(a)
>
> False
>
>  >>> all(a)
>
> False
>
>  >>> any(b)
>
> True
>
>  >>> all(b)
>
> False
>
> Though anyone growing up with the Python boolean operator might wonder
> why it is as it is - i.e. when 0 was the way to spell False this
> behavior is fairly well expected.  Now that False is spelled "False",
> having "0" any less true than "1", when thinks one is dealing with
> numbers as numbers, is likely to catch the less geeky unaware, IMO.

This is why in teaching I prefer to use explicit tests:

if x != 0:
    do something

Rather than 

if x:
    do something

--John

-- 
John M. Zelle, Ph.D.             Wartburg College
Professor of Computer Science    Waverly, IA     
john.zelle at wartburg.edu          (319) 352-8360  


More information about the Edu-sig mailing list