递归函数返回 None 但打印正确的结果 [英] Recursive function returns None but prints correct result
问题描述
我正在研究填充列表的递归函数.我遇到了一个问题,当我尝试返回列表本身时,我收到 None
参数.但是,如果我打印相同的参数,我会得到正确的列表.知道为什么我会看到这种行为吗?
I am working on recursive function that fills a list. I encountered a problem that when I try to return the list itself I recieve None
argument. However, if I print the same argument I got the correct list back. Any idea why I see such behavour?
示例:
def Price(tau, price):
price[tau] = (tau**2 - tau) + price[tau+1] - price[tau+2]
if tau == 0:
return price
else:
tau = tau - 1
Price(tau, price)
print(Price(tau = 3,
price = 6*[0]))
> None
但是只是打印价格,给出了正确的结果:
However just prining the price, gives correct result:
def Price(tau, price):
price[tau] = (tau**2 - tau) + price[tau+1] - price[tau+2]
if tau == 0:
print(price)
else:
tau = tau - 1
Price(tau, price)
Price(tau = 3,
price = 6*[0])
> [-6, 2, 8, 6, 0, 0]
推荐答案
在你的函数中,当你进入你的 if
语句时,你只会返回 Price
的结果.如果你点击你的 else
语句,你确实在递归循环中更深入了一步,但你永远不会返回那个结果.试试这个:
Inside your function, you are only returning the result of Price
when you go into your if
statement. If you hit your else
statement, you do indeed go one step deeper into the recursive loop, but you never return that result. Try this instead:
if tau == 0:
return price
else:
tau = tau - 1
return Price(tau, price)
这篇关于递归函数返回 None 但打印正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!