python中求平方根函数_Python中的平方根函数有什么问题?

我这周才开始学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积木游戏,但它真的让我大吃一惊。非常感谢大家!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值