Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 完美的平方函数,不';不归_Python_Loops_If Statement - Fatal编程技术网

Python 完美的平方函数,不';不归

Python 完美的平方函数,不';不归,python,loops,if-statement,Python,Loops,If Statement,我是Python的初学者,我被赋予了这个任务:编写一个函数,返回小于或等于其参数(正整数)的最高完美平方 def perfsq(n): x=0 xy=x*x 如果n>=0: 当xy

我是Python的初学者,我被赋予了这个任务:编写一个函数,返回小于或等于其参数(正整数)的最高完美平方

def perfsq(n):
x=0
xy=x*x
如果n>=0:
当xy

当我运行代码执行函数时,它不会输出任何内容。我承认,我正在努力,如果你能给我一些关于如何解决这个问题的建议,我将不胜感激。

就像Patrick Haugh所说的,尝试检查while循环何时退出。在整个方法中放置print()语句可以帮助您了解方法的执行方式。为了确定循环何时退出,请查看while循环的退出条件:xy 记住,变量只有在更新后才会更新

def perfsq(n):
    x = 0
    xy = x * x
    print("xy: {}".format(xy))
    if n >= 0:
        while xy < n:
            x += 1
            print("xy in loop: {}".format(xy))

        if xy != n:
            print (("%s is not a perfect square.") % (n))
            x -= 1
            print (("%s is the next highest perfect square.") % (xy))
        else:
            return(print(("%s is a perfect square of %s.") % (n, x)))
def perfsq(n):
x=0
xy=x*x
打印(“xy:{}”。格式(xy))
如果n>=0:
当xy
我明白你的错误,这是一个容易犯的错误。当你定义

xy = x*x
计算机计算
x*x
,并将该数字指定为
xy
的值。因此,当您向
x
添加一个时,它不会更改
xy
的值。每次您都必须告诉计算机重新计算
xy

while xy < n:
    x += 1
    xy = x*x
而xy
def perfsq(n):
x=0
xy=x*x
如果n>=0:
当xyxy=x*x您的循环条件

while xy < n:

为什么在
xy
的情况下总是
true
,因为在循环运行时,您已经指定了xy
0
,并且从未将其修改为任何其他值。请检查条件,它将始终得到
true

查看您的
while
循环。什么时候它会停止循环?你能发布一些输出吗?一个与代码无关的提示:所有的完美平方都是连续奇数整数的和
返回(打印(…
没有什么意义。不要混淆函数的返回和打印。
xy=x*x
在循环外执行一次不会导致
xy
在循环内始终等于
x*x
。Python变量不像电子表格单元格,当其他值更改时会自动更新。这样说可能更准确一些“我看到了你的一个错误。”即使他们修复了一个bug,生成的代码仍然无法满足功能规范。
def perfsq(n):

    x = 0
    xy = x * x
    if n >= 0:
        while xy < n:
            x += 1
            xy = x*x <-- Here

        if xy != n:
            print (("%s is not a perfect square.") % (n))
            x -= 1
            xy = x*x  <--Here
            print (("%s is the next highest perfect square.") % (xy))
        else:
            print(("%s is a perfect square of %s.") % (n, x)) <--And here
while xy < n:
for n > 0