Python:名称'math'未定义错误?

Dan*_*nny 27 python

我是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   
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 51

更改

from math import *
Run Code Online (Sandbox Code Playgroud)

import math
Run Code Online (Sandbox Code Playgroud)

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


Yug*_*dle 8

你犯了一个错误..

你写的时候:

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
Run Code Online (Sandbox Code Playgroud)

所以,当你尝试使用时 math.log

它会给你错误,所以:

替换math.loglog

要么

替换from math import *import math

这应该可以解决问题.


Sam*_*lan 7

你需要import math而不是from math import *.