【发布时间】:2012-08-31 17:18:13
【问题描述】:
我这周刚开始学习 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 <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.')
但是当我保存它并在 Python shell 中键入 sqrt(16) 时,我收到一条错误消息。
NameError: name 'sqrt' is not defined
我使用的是 Python 3.1.1。 我的代码有问题吗? 任何帮助,将不胜感激。 谢谢
更新 好的,感谢你们,我意识到我没有导入该功能。 当我尝试导入它时,我收到了一个错误,因为我将它保存在一个通用的 My Documents 文件而不是 C:\Python31 中。所以在将脚本保存为 C:\Python31\squareroot.py 后,我在 shell 中输入了(重新启动它):
导入平方根
又出现一个新错误!
>>> 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
意思是我的原始代码中有一个错误!我现在要看看下面的一些建议的更正。如果您发现了其他任何东西,请说。谢谢:)
更新 2 - 成功了!!!!!!!!!!
这就是我所做的。 首先,我使用了 IamChuckB 友好发布的代码的清理版本。我在其中制作了一个新脚本(将函数名称从 sqrt 更改为 sqrta 以区分):
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.')
重要的是,将其保存为 C:\Python31\squareroota.py(同样,在末尾添加了一个“a”以区分另一个失败的文件。)
然后我重新打开 Python shell 并这样做:
>>> import squareroota
什么都没有发生,没有错误,太棒了!然后我这样做了:
>>> squareroota.sqrta(16)
得到了这个!
16 is a perfect square.
4
哇。我知道这看起来像是在学校里玩 ABC 积木,但它真的让我大吃一惊。非常感谢大家!
【问题讨论】:
-
你可以使用
ans ** 0.5,你知道的。 -
您必须描述您的工作流程。你所说的 Python shell 是什么意思,你如何运行 shell,你在将它保存到文件和在 shell 中尝试之间做了什么,你做了什么使
sqrt在 shell 中可用,等等。 -
您是否将此代码保存在文件中?你在python shell中导入了这个吗? (抱歉问这些问题)
-
缩进在 Python 中很重要,因此请确保您提供的代码与相关代码的格式完全一致。
-
在
def sqrt(x):行之后缩进所有内容。
标签: python function debugging square-root