I literally just started learning Python this week. (I will be a computer science fresher in a month!)
Here's a function I wrote to compute the square root of x.
#square root function
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
But when I save it and type sqrt(16) into the Python shell, I get an error message.
NameError: name 'sqrt' is not defined
I'm using Python 3.1.1. Is there something wrong with my code? Any help would be appreciated. Thanks
UPDATE Okay, thanks to you guys I realized I hadn't imported the function. And when I tried to import it, I got an error because I saved it in a generic My Documents file instead of C:\Python31. So after saving the script as C:\Python31\squareroot.py, I typed into the shell (having restarted it):
import squareroot
And got a NEW error!
>>> import squareroot
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import squareroot
File "C:\Python31\squareroot.py", line 13
return ans
SyntaxError: 'return' outside function
Meaning there WAS a bug in my original code! I'm going to look at some of the suggested corrections below right now. If you've spotted anything else, say. Thanks :)
UPDATE 2 - IT WORKED!!!!!!!!!!
Here's what I did. First, I used a cleaned up version of code kindly posted by IamChuckB. I made a new script with this in it (changed the function name from sqrt to sqrta to differentiate):
def sqrta(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
And, importantly, saved it as C:\Python31\squareroota.py (Again, added an "a" at the end to differentiate between this the other, failed, file.)
Then I reopened Python shell and did this:
>>> import squareroota
Nothing happened, no error, great! Then I did this:
>>> squareroota.sqrta(16)
And got this!
16 is a perfect square.
4
Wow. I know this might seem like playing with ABC blocks in school but it honestly blew my mind. Thank you very much everyone!