Learning Python : >>> import math doesn't work ?

David Sanders dpsanders at gmail.com
Sun Nov 18 23:21:03 EST 2007


On Nov 18, 8:48 pm, pdlem... at earthlink.net wrote:
> Have carefully installed Python 2.5.1 under XP in dir E:\python25 .
> ran   set path = %path% ; E:\python25
> Python interactive mode works fine for simple arithmetic .
> Then tried >>>  import math
>                 >>>  x = sqrt(100)
>    Get error    Name error : name 'sqrt' is not defined
>         Same thing with sin(x) .
> I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs
> or include directories .
> The Tutorial does not clear this up .
> Please help.    Thanks  Dave     pdlem... at earthlink.net

Hi,

I believe that should be:
    x = math.sqrt(100)

'import math' makes available the functions in the math module, but
they are still inside the math namespace, so still require 'math.'
If you will be using sqrt a lot, you can create a copy of the function
in the local namespace using
    sqrt = math.sqrt
    x = sqrt(100)

[In principle, you can give it any name you want, but of course it is
sensible to use a name that makes sense.
E.g. if you were a Spanish speaker, you could say instead
    raiz = math.sqrt
    x = raiz(100)
]

For more details about how 'import'ing works, check out the Python
tutorial.

Hope that helps.
Best wishes,

David.







More information about the Python-list mailing list