Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 21 Online
OpenStudy (anonymous):

Is anyone else here using python 2.7.2 for windows?

OpenStudy (anonymous):

yea i do.

OpenStudy (anonymous):

did you have any problems with defining functions in lecture 4?

OpenStudy (anonymous):

nope i did it!

OpenStudy (anonymous):

I'm using code swiped from the pdf, but I keep getting NameError: name 'sqrt' not defined. I can't figure out what I've not done.

OpenStudy (anonymous):

first "import math"

OpenStudy (anonymous):

I think that may be my problem! do I do it thru the menu?

OpenStudy (anonymous):

no,just type 'import math' as first line of your program

OpenStudy (anonymous):

could you show me a copy of the code?

OpenStudy (anonymous):

I tried what you said, but it didn't work... :(

OpenStudy (anonymous):

import math x = 16 ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 print 'ans =', ans if ans*ans != x: print x, 'is not a perfect square' else: print ans else: print x, 'is a negative number' def sqrt(x): ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x: print x, 'is not a perfect square' return None else: return ans else: print x, 'is a negative number' return None

OpenStudy (anonymous):

thanks for ur help. It's not working out for me. I think I need a small break. Maybe when I get back it will look better.

OpenStudy (anonymous):

Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> sqrt(16) NameError: name 'sqrt' is not defined

OpenStudy (anonymous):

Funny enough, the code works, it's just making the function sqrt(x) that doesn't work. oh well.

OpenStudy (anonymous):

my bad,i didn't checked the code just copy paste :(

OpenStudy (anonymous):

sqrt() is a function/method of the math module - it is in the math 'namespace' to access methods of an imported module you have to use module.method read 9.1 and 9.2 of the Tutorial - I had to refer to it many times on and off as i learned more stuff. The documentation should also be installed on your computer - i find that version easier to use (F1 from within Idle). http://docs.python.org/tutorial/classes.html#a-word-about-names-and-objects

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!