【发布时间】:2021-10-28 09:49:37
【问题描述】:
我在 Python 中执行简单的递归程序时遇到此错误。
RecursionError Traceback (most recent call last)
<ipython-input-19-e831d27779c8> in <module>
4 num = 7
5
----> 6 factorial(num)
<ipython-input-19-e831d27779c8> in factorial(n)
1 def factorial(n):
----> 2 return (n * factorial(n-1))
3
4 num = 7
5
... last 1 frames repeated, from the frame below ...
<ipython-input-19-e831d27779c8> in factorial(n)
1 def factorial(n):
----> 2 return (n * factorial(n-1))
3
4 num = 7
5
RecursionError: maximum recursion depth exceeded
我的程序是:
def factorial(n):
return (n * factorial(n-1))
num = 7
factorial(num)
请帮忙。提前致谢!
【问题讨论】:
-
你的递归没有基本情况,即它只是给出答案而不调用自己
-
嗨罗宾,你能详细说明一下吗?
-
程序在无限循环中执行时会出现此错误。在这个程序中,没有条件停止递归。
def factorial(n): if(n>1): return (n * factorial(n-1)) else: return 1=> 尝试像上面提到的那样改变你的功能。它会起作用的。 -
@YabazeCool 不是无限循环。无限递归。甚至不一定是无限递归。如果你点击
1500递归,你会得到错误:stackoverflow.com/a/3323013/2681662 -
当然用递归计算阶乘是个坏主意。
标签: python recursion factorial