[Tutor] Python root.
Dave Angel
davea at ieee.org
Sun Apr 18 23:08:25 CEST 2010
Aidas wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hello.
> In here
> http://mail.python.org/pipermail/tutor/2001-February/003385.html You
> had written how to ger root in python. The way is: "from math import
> sqrtprint sqrt( 49 )".
>
> I noticed that if I write just "print sqrt(49)" I get nothing.
I don't get "nothing," I get an error message. In particular I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
> So why I need to write "from math import sqrt" instead of write just
> "print sqrt( 49 )"?
>
> P.S. Sorry about english-I'm lithuanian. :)
>
As the message says, "sqrt" is not defined in the language. It's
included in one of the library modules. Whenever you need code from an
external module, whether that module is part of the standard Python
library or something you wrote, or even a third-party library, you have
to import it before you can use it. The default method of importing is:
import math
print math.sqrt(49)
Where the prefix qualifer on sqrt means to run the sqrt() specifically
from the math module.
When a single function from a particular library module is needed many
times, it's frequently useful to use the alternate import form:
from math import sqrt
which does two things:
import math
sqrt = math.sqrt
The second line basically gives you an alias, or short name, for the
function from that module.
HTH
DaveA
More information about the Tutor
mailing list