Python:'math'未定义错误?

43 投票
4 回答
152033 浏览
提问于 2025-04-17 07:24

我刚开始学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

4 个回答

8

你需要用 import math 这种方式来引入数学库,而不是用 from math import * 这种方式。

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 时,

它会给你报错,那么:

math.log 替换成 log

或者

from math import * 替换成 import math

这样应该就能解决问题了。

72

from math import *

改成

import math

使用 from X import * 通常不是个好主意,因为这样会不受控制地污染全局命名空间,还可能带来其他麻烦。

撰写回答