簡體   English   中英

Python方法未返回

[英]Python Method Returning None

我有一個很奇怪的問題。 我編寫了一種確定給定數字集的公式的程度的方法。 該方法非常簡單,我在調試中添加了幾行:

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)

請記住,當方法遞歸調用自身時,如果要return值,則仍然需要顯式return值。

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

您還需要在if子句中返回一個值。

return getdeg(templist, count)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM