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:\Python27\mit ocw\pset1a.py", line 28, in <module> x=math.log(d) NameError: name 'math' is not defined
The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.
You can fix this by doing global new at the start of the function in which you define it. This statement puts it in the global scope, meaning that it is defined at the module level. Therefore, you can access it anywhere in the program and you will not get that error.
In mathematics, the term undefined is often used to refer to an expression which is not assigned an interpretation or a value (such as an indeterminate form, which has the propensity of assuming different values). The term can take on several different meanings depending on the context.
This is because when you declare a variable or a function, Python stores the value with the exact name you have declared. If there is a typo anywhere that you try to reference that variable, an error will be returned.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With