Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Python recursion not stopping

+6 votes
asked Feb 18 by gta6isnotfree (430 points)
I’m super new to Python and trying to make a factorial function using recursion. But it just keeps crashing with some RecursionError.   

Here’s my code:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n)
        
print(factorial(5))

I thought “if n == 0” would stop it, but nope.  

Can someone explain why it’s not stopping and how I can fix it so factorial(5) gives 120?

3 Answers

+3 votes
answered Feb 18 by Filip Necula (280 points)
look at your "else" wing, instead of factorial(n-1)  you wrote factorial(n) so in other words your program was calculating "n*n*n*n*......." infinetly and that's why you get a recusion error
0 votes
answered Apr 9 by 240840131045 (140 points)
def factorial(n):

    for i in range (n+1):

        if n == 0:
            return 1
        else:
            return n * factorial(n)
        
print(factorial(5))
commented Apr 10 by Peter Minarik (101,340 points)
You have the same problem as the original poster: infinite recursion.
0 votes
answered Apr 19 by Vipul Kumar (280 points)
just a small correction
you should write

return n*factorial(n-1)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...