Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : name 'math' is not defined Error?

Tags:

python

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 
like image 677
dannysood Avatar asked Nov 30 '11 16:11

dannysood


People also ask

How do I fix name not defined error in Python?

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.

How do you resolve a name error in Python?

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.

What does math is not defined mean?

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.

Why is Python saying my variable isn't defined?

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.


2 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.

like image 142
NPE Avatar answered Sep 22 '22 19:09

NPE


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.

like image 38
Yugal Jindle Avatar answered Sep 22 '22 19:09

Yugal Jindle