1

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!

  • 4
    your recursion doesn't have a base case, ie one where it just gives the answer without calling itself – Robin Zigmond Oct 28 '21 at 09:50
  • Hi Robin, Can you please elaborate? – Lalit rathore Oct 28 '21 at 09:53
  • This error will come when your program executed In infinite loop. In this program, there is no condition to stop recursion. ```def factorial(n): if(n>1): return (n * factorial(n-1)) else: return 1 ``` => try to change your function like above mentioned. It will Work. – Yabaze Cool Oct 28 '21 at 09:59
  • 1
    @YabazeCool not an infinite loop. An infinite recursion. And even not necessarily an infinite recursion. If you hit `1500` recursion you'll get the error: https://stackoverflow.com/a/3323013/2681662 – MSH Oct 28 '21 at 10:04
  • 1
    Of course calculating the factorial with recursion is a bad idea anyway. – Matthias Oct 28 '21 at 10:10

2 Answers2

1

A recursive function has a simple rule to follow.

  1. Create an exit condition
  2. 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))
MSH
  • 1,743
  • 2
  • 14
  • 22
0

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.

thibaultbl
  • 886
  • 1
  • 10
  • 20