Python:name 'math' is not defined错误?

43

我是Python的初学者,无法理解为什么会发生这种情况:

from math import *
print "enter the number"
n=int(raw_input())
d=2
s=0
while d<n :
    if n%d==0:
       x=math.log(d)
       s=s+x
       print d
    d=d+1
print s,n,float(n)/s   

在Python中运行并输入非质数会出现错误

Traceback (most recent call last):
  File "C:\Python27\mit ocw\pset1a.py", line 28, in <module>
    x=math.log(d)
NameError: name 'math' is not defined

1
关于模块:http://docs.python.org/tutorial/modules.html#importing-from-a-package - César
4个回答

72

改变

from math import *
import math

使用 from X import * 通常不是一个好的做法,因为它会无法控制地污染全局命名空间,并可能带来其他困难。


哦,我实际上是在使用MIT OCW进行学习,在他们的问题集中写着要使用from math import *。 - dannysood
1
@Danny:我不知道他们为什么选择以那种方式编写它,但我建议不要使用“from X import *”。 - NPE
1
@Danny:在某些情况下,使用 * 导入是合理的,但正如 @aix 所说,它“通常不是一个好主意”。因此,对于您不需要扩展的简单脚本,您可能不关心,但对于更复杂的脚本,您应该关心。 - Tadeck
其他的困难有哪些? - Matt Fenwick
@MattFenwick: 主要是无法重新加载以这种方式导入的内容。 - NPE

10

你犯了一个错误...

当你写下:

from math import *
# This imports all the functions and the classes from math
# log method is also imported.
# But there is nothing defined with name math

因此,当您尝试使用math.log时,会出现错误,所以:

log替换math.log

或者

import math替换from math import *

这应该可以解决问题。


8
您需要使用import math而不是from math import *

1
如何使用(仅需要 math.pi):
from math import pi as PI

然后像使用 PI 符号一样使用它吗?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接