[英]Python Method Returning None
I'm having a very odd problem. 我有一个很奇怪的问题。 I wrote a method that determines the degree of a formula describing a set of numbers, when given the said set.
我编写了一种确定给定数字集的公式的程度的方法。 The method is fairly simple, I've added in a couple of lines for debugging purposes:
该方法非常简单,我在调试中添加了几行:
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
Now, I'm running this on a set of numbers I KNOW to be described by a 3rd-degree equation, like so: 现在,我在一组我想用三阶方程描述的数字上运行它,如下所示:
x = getdeg([2, 8, 9, 11, 20], 0)
print(x)
Fairly simple, yes? 很简单,是吗? Except when you run this, it prints out the following:
除非您运行此命令,否则它会打印出以下内容:
[6, 1, 2, 9]
Not all equal, iterating again
[-5, 1, 7]
Not all equal, iterating again
[6, 6]
3
None
Everything is looking good, right up until that "None." 一切看起来都很好,直到“无”为止。 What is it doing there?
在那里做什么? I would assume that the
else
conditional isn't being executed, but it's printing out 3 just fine, so it obviously is. 我会假设
else
条件没有被执行,但是它打印出3就很好了,显然是这样。 That also means that the program "knows" what the value of count
is, but it's not returning it right. 这也意味着程序“知道”
count
的值是什么,但是并没有正确返回它。 Could someone enlighten me as to what on earth is going on? 有人能启发我关于地球上正在发生的事情吗?
if not allEqual(templist):
print("Not all equal, iterating again")
getdeg(templist, count)
Remember, when a method recursively calls itself, you still need to explicitly return
the value if you want a value to be returned. 请记住,当方法递归调用自身时,如果要
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.