I couldn't use the sign funcion inside of another function

Emile van Sebille emile at fenx.com
Mon Apr 23 16:27:14 EDT 2012


On 4/23/2012 11:39 AM Chris Rebert said...
> On Mon, Apr 23, 2012 at 11:29 AM, Julio Sergio<juliosergio at gmail.com>  wrote:
>> I want to use the sign function. When I use it in in-line mode works pretty
>> well:
>>
>>    : sign(-20)
>>    : -1
>>
>> However, I wrote the following code in a file, say, pp.py
>>
>> def tst(x):
>>     s = sign(x)
>>     return(s)
>>
>> Then I tried to import into my session:
>>
>>   : from pp import *
>>
>> When I try to use tst, this is what I get:
>>
>>   ------------------------
>>   Traceback (most recent call last):
>>     File "<ipython console>", line 1, in<module>
>>     File "pp.py", line 9, in tst
>>       s = sign(x)
>>   NameError: global name 'sign' is not defined
>>
>>
>> Do you have any idea why is this happening?
>
> There is no built-in sign() function in Python. It must be coming from
> some library that you imported. You need to add that import to pp.py
> so that Python knows that your module depends on that library.
>
There is math.copysign you could use:

 >>> import math

 >>> help(math.copysign)
Help on built-in function copysign in modul

copysign(...)
     copysign(x, y)

     Return x with the sign of y.

 >>> math.copysign(1,-1)
-1.0
 >>> math.copysign(1,1)
1.0

 >>>
 >>> def sign(y):
...     return int(math.copysign(1,y))
...
 >>> sign(1)
1
 >>> sign(0)
1
 >>> sign(-1)
-1

Emile




More information about the Python-list mailing list