[Tutor] if n == 0 vs if not n

Kent Johnson kent37 at tds.net
Thu Oct 8 20:29:43 CEST 2009

```On Mon, Oct 5, 2009 at 9:13 PM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:

> Actually, I just realized that "not" has higher precedence than "==" so this
> is really checking if (not n) is equal to 0, not if (n == 0) is (not) True.

No, "not" is lower precedence than "==". See
http://docs.python.org/reference/expressions.html#summary

> Anyone have some counter-examples to n != 0 being the same as "not n == 0"?

Well, you can create a pathological class where they are different:

In : class funky(object):
....:     def __eq__(self, other):
....:         return True
....:     def __ne__(self, other):
....:         return True

In : f = funky()

In : f != 0
Out: True

In : f == 0
Out: True

In : not f == 0
Out: False

For a less contrived example, if n is a numpy array, n==0 is also a
numpy array but (not n != 0) gives an error:

In : from numpy import *

In : a = array( [ 0, 10, 20, 30, 40 ] )

In : a== 0
Out: array([ True, False, False, False, False], dtype=bool)

In : not a!= 0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

C:\Project\MangoLib\<ipython console> in <module>()

ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

Kent
```