Python : name 'math' is not defined Error?
Question:
I am a beginner in python and cant understand why this is happening:
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
Running it in Python and inputing a non prime gives the error
Traceback (most recent call last):
File "C:Python27mit ocwpset1a.py", line 28, in <module>
x=math.log(d)
NameError: name 'math' is not defined
Answers:
Change
from math import *
to
import math
Using from X import *
is generally not a good idea as it uncontrollably pollutes the global namespace and could present other difficulties.
You need to import math
rather than from math import *
.
You did a mistake..
When you wrote :
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
So, When you try using math.log
It gives you error, so :
replace math.log
with log
Or
replace from math import *
with import math
This should solve the problem.
How about (when you need only math.pi
):
from math import pi as PI
and then use it like PI
symbol?
I am a beginner in python and cant understand why this is happening:
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
Running it in Python and inputing a non prime gives the error
Traceback (most recent call last):
File "C:Python27mit ocwpset1a.py", line 28, in <module>
x=math.log(d)
NameError: name 'math' is not defined
Change
from math import *
to
import math
Using from X import *
is generally not a good idea as it uncontrollably pollutes the global namespace and could present other difficulties.
You need to import math
rather than from math import *
.
You did a mistake..
When you wrote :
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
So, When you try using math.log
It gives you error, so :
replace math.log
with log
Or
replace from math import *
with import math
This should solve the problem.
How about (when you need only math.pi
):
from math import pi as PI
and then use it like PI
symbol?