我是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 *
通常不是一个好主意,因为它无法控制地污染全局命名空间并可能带来其他困难.
你犯了一个错误..
你写的时候:
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.log
为log
要么
替换from math import *
为import math
这应该可以解决问题.