Marambo - 1 year ago 227
Python Question

python bad operand type for unary -: 'NoneType'

I send you a question because I have a problem on python and I don't understand why.
I created a function "mut1" to change the number inside a list (with a probability to 1/2) either in adding 1 or subtracting 1, except for 0 and 9:

``````def mut1 (m):
i=np.random.randint(1,3)
j=np.random.randint(1,3)
if i==1:
if 0<m<9:
if j==1:
m=m+1
elif j==2:
m=m-1
elif m==0:
if j==1:
m=1
if j==2:
m=9
elif m==9:
if j==1:
m=0
if j==2:
m=8
print m
``````

mut1 function well, for example, if I create a list P1:

``````>>>p1=np.array(range(8),int).reshape((4, 2))
``````

After that, I apply "mut1" at a number (here 3) in the list p1

``````>>>mut1(p1[1,1])
``````

Hovewer if I write:

``````>>> p1[1,1]=mut1(p1[1,1])
``````

I have a message error:

Traceback (most recent call last): File "<stdin>", line 1, in
<module> TypeError: long() argument must be a string or a number, not
'NoneType'

That happens because you have to make your `mut1` return an `numpy.int64` type of result. So I tried with the following modified code of yours and worked.

``````>>> import numpy as np
>>> import random
>>>
>>> def mut1 (m):
...     i=np.random.randint(1,3)
...     j=np.random.randint(1,3)
...     if i==1:
...         if 0<m<9:
...             if j==1:
...                 m=m+1
...             elif j==2:
...                 m=m-1
...         elif m==0:
...             if j==1:
...                 m=1
...             if j==2:
...                 m=9
...         elif m==9:
...             if j==1:
...                 m=0
...             if j==2:
...                 m=8
...     return np.int64(m)
...
>>> p1=np.array(range(8),int).reshape((4, 2))
>>> mut1(p1[1,1])
2
>>> p1[1,1]=mut1(p1[1,1])
>>>
``````

So the only thing you need to change is to replace `print m` with `return np.int64(m)` and then should work!

You will easily understand why this happened with the following kind of debugging code:

``````>>> type(p1[1,1])
<type 'numpy.int64'>
>>> type(mut1(p1[1,1]))
<type 'NoneType'>
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download