logical statements (in Python and Numeric)

Chris Barker Chris.Barker at noaa.gov
Thu Jun 20 15:27:11 EDT 2002


Fernando Pérez wrote:
> > it has to do with a using an and statement...

> > y = y + (x >= -2. and x < 0.) * (x + 6.)

> I agree that the above failure is bloody counterintuitive, to the point where
> I'd call it a bug. It's easy to illustrate with:

I don't know if it is a bug or not, but it is annoying. Python 2.1
introduced "rich comparisons", which allowed NumPy to overload >,<,== ,
etc, but you can't overload "and" and "or". I think this is because of
how "and" shortcuts but not evaluating the second operand if the first
is false, etc. In Python, a non-empty sequence is TRUE, so x and y. will
always evaluate to true if x and y are not empty, and the value returned
is teh first one that answers the question, so, for y and y not empty:

x and y #returns y
x or y  #returns x

One solution is to use the bitwise operators instead:
y = y + (x >= -2. & x < 0.) * (x + 6.)

or 
y += ( (x >= -2. & x < 0.) * (x + 6.) ) 

to use +=

This should work fine in this case, and most comon cases.

You might also want to take a look at the where() and putmask() functions:

y = y + where( (x >= -2. & x < 0.), (x + 6.), 0 )

> You may consider posting to the Numeric mailing list about this.

before you do that, look at the archives, it has been discussed a lot.

> The 'and'
> operator should either not work at all or work correctly.

I'm not sure either of these is possible without significant changes to Python.

-Chris

-- 
Christopher Barker, Ph.D.
Oceanographer
                                    		
NOAA/OR&R/HAZMAT         (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the Python-list mailing list