I am getting this error while Executing simple Recursion Program in 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
My program is:
def factorial(n):
return (n * factorial(n-1))
num = 7
factorial(num)
Please help. Thanks in advance!
CodePudding user response:
A recursive function has a simple rule to follow.
- Create an exit condition
- Call yourself (the function) somewhere.
Your factorial function only calls itself. And it will not stop in any condition (goes on to negative).
Then you hit maximum recursion depth.
You should stop when you hit a certain point. In your example it's when n==1
. Because 1!=1
def factorial(n):
if n == 1:
return 1
return (n * factorial(n-1))
CodePudding user response:
You have to return another value at some point.
Example below:
def factorial(n):
if n == 1:
return 1
return (n * factorial(n-1))
Else, your recursive loop will not stop and go to - infinity.