Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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方法返回None_Python_Return - Fatal编程技术网

Python方法返回None

Python方法返回None,python,return,Python,Return,我有一个很奇怪的问题。我写了一个方法,当给定一组数字时,确定描述一组数字的公式的阶数。该方法相当简单,我添加了几行代码用于调试: def getdeg(numlist, cnt): #get the degree of the equation describing numlist count = cnt #initial run should be with cnt as 0 templist = [] for i in range(len(numlist) - 1):

我有一个很奇怪的问题。我写了一个方法,当给定一组数字时,确定描述一组数字的公式的阶数。该方法相当简单,我添加了几行代码用于调试:

def getdeg(numlist, cnt): #get the degree of the equation describing numlist
    count = cnt #initial run should be with cnt as 0
    templist = []
    for i in range(len(numlist) - 1): #exclude the last item (which doesn't have an item after it)
        templist.append(numlist[i+1] - numlist[i]) #append the val of index i+1 minus index i
    count += 1
    print(templist)
    if not allEqual(templist):
        print("Not all equal, iterating again")
        getdeg(templist, count)
    else:
        print(count)
        return count

def allEqual(numlist):
    if len(numlist) == 1:
        return True
    for i in range(len(numlist) -1):
        if not (numlist[i] == numlist[i+1]):
            return False

    return True
现在,我在一组数字上运行,我知道这些数字可以用三次方程来描述,如下所示:

x = getdeg([2, 8, 9, 11, 20], 0)
print(x)
相当简单,是吗?除非运行此操作,否则它会打印出以下内容:

[6, 1, 2, 9]
Not all equal, iterating again
[-5, 1, 7]
Not all equal, iterating again
[6, 6]
3
None
一切看起来都很好,直到那一刻。它在那里干什么?我假设else条件没有被执行,但是它打印出的3很好,所以它显然是。这也意味着程序知道count的值是多少,但它没有正确地返回它。有人能告诉我到底发生了什么事吗

if not allEqual(templist):
    print("Not all equal, iterating again")
    getdeg(templist, count)
请记住,当一个方法递归地调用自身时,如果希望返回值,仍然需要显式返回该值

if not allEqual(templist):
    print("Not all equal, iterating again")
    return getdeg(templist, count)
请记住,当一个方法递归地调用自身时,如果希望返回值,仍然需要显式返回该值

if not allEqual(templist):
    print("Not all equal, iterating again")
    return getdeg(templist, count)

您还需要在if子句中返回一个值

return getdeg(templist, count)

您还需要在if子句中返回一个值

return getdeg(templist, count)

啊,上帝。递归****让我再一次陷入困境。谢谢啊,上帝。递归****让我再一次陷入困境。谢谢