我这周才开始学Python。(我将在一个月内成为一名计算机科学新生!)
我写了一个函数来计算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
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.')
但当我保存它并在Python shell中键入sqrt(16)时,会收到一条错误消息。NameError: name 'sqrt' is not defined
我正在使用Python3.1.1。
我的代码有问题吗?
任何帮助都将不胜感激。
谢谢
更新
好吧,多亏了你们,我才意识到我没有导入这个函数。
当我试图导入它时,我得到了一个错误,因为我把它保存在一个通用的文档文件中,而不是C:\ Python31。因此,在将脚本保存为C:\Python31\squareroot.py之后,我输入了shell(重新启动了它):import squareroot
又犯了个新错误!>>> import squareroot
Traceback (most recent call last):
File "", line 1, in
import squareroot
File "C:\Python31\squareroot.py", line 13
return ans
SyntaxError: 'return' outside function
意思是我的原始代码中有个错误!我现在要看看下面建议的一些更正。如果你发现了什么,说。谢谢:)
更新2-成功了!!!!!!!!!!
我就是这么做的。
首先,我使用了一个由iamcuckb友好发布的清理过的代码版本。我用它制作了一个新脚本(将函数名从sqrt更改为sqrt a以区分):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
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.')
而且,重要的是,将其保存为C:\ Python31\squareroota.py(同样,在末尾添加了一个“a”,以区分这一文件和另一个失败的文件)
然后我重新打开Python shell并执行了以下操作:>>> import squareroota
没发生什么,没有错误,太好了!然后我做了这个:>>> squareroota.sqrta(16)
得到这个!16 is a perfect square.
4
哇哦。我知道这看起来像是在学校玩ABC积木游戏,但它真的让我大吃一惊。非常感谢大家!