问题
Whenever I try to use any of the built-in functions of Python's exponentiation and logarithms module, I get an error like this:
NameError: name 'sqrt' is not defined
I have tried using math.sqrt(4)
,sqrt(4)
and sqrt(4.0)
, but none of them work. The exception is pow
, which works as it's supposed to. This is really strange and I'm not sure what's wrong.
回答1:
pow
is built into the language(not part of the math library). The problem is that you haven't imported math.
Try this:
import math
math.sqrt(4)
回答2:
You can also import as
from math import *
Then you can use any mathematical function without prefixing math. e.g.
sqrt(4)
回答3:
add:
import math
at beginning. and then use:
math.sqrt(num) # or any other function you seem neccessary
回答4:
You need to say math.sqrt
when you use it. Or, do from math import sqrt
.
Hmm, I just read your question more thoroughly.... How are you importing math
? I just tried import math
and then math.sqrt
which worked perfectly. Are you doing something like import math as m
? If so, then you have to prefix the function with m
(or whatever name you used after as
).
pow
is working because there are two versions: an always available version in __builtin__
, and another version in math
.
回答5:
import math #imports math module
import math as m
print(m.sqrt(25))
from math import sqrt #imports a method from math module
print(sqrt(25))
from math import sqrt as s
print(s(25))
from math import *
print(sqrt(25))
回答6:
In
from math import sqrt
Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".
回答7:
import math as m a=int(input("Enter the no")) print(m.sqrt(a))
from math import sqrt print(sqrt(25))
from math import sqrt as s print(s(25))
from math import * print(sqrt(25))
All works.
来源:https://stackoverflow.com/questions/8783261/python-math-module