def bunnies(n,months,quantity):
    print(quantity)
    if n == months:
        return quantity
    else:
        quantity=quantity+quantity
        bunnies(n+1,months,quantity)



months=int(input("How many months ?"))
quantity=1
n=0
bunnies_total=bunnies(n,months,quantity)
print(bunnies_total)


由于某种原因,我的函数返回了None,我无法弄清楚。

最佳答案

您的else分支不会返回任何内容,这意味着在python中,它只会返回None。在对return的呼叫上打一个bunnies,您应该可以:

def bunnies(n,months,quantity):
    if n == months:
        return quantity
    else:
        quantity=quantity+quantity
        return bunnies(n+1,months,quantity) # Here

关于python - Python递归函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37159286/

10-13 05:00