【发布时间】:2022-05-10 22:08:08
【问题描述】:
### Run the code below and understand the error messages
### Fix the code to sum integers from 1 up to k
###
def f(k):
return f(k-1) + k
print(f(10))
我对如何在使用递归时修复此代码感到困惑,我不断收到错误消息
[上一行重复了 995 次以上]
RecursionError: 超出最大递归深度
有没有一种简单的方法可以在不使用任何 while 循环或创建多个变量的情况下解决此问题?
【问题讨论】:
-
这个函数总是调用自己,导致无限递归。在某些时候,应该返回一个实际值。在这种情况下,需要一些 if-then-else 魔法。 ;)
标签: python-3.x recursion