Search code examples
pythonrecursionfactorial

Problem while doing simple python Recursion


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!


Solution

  • 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))