Factorial: Infinite Loop Starting


def factorial(x):
    if x==0:
        return 0
        while x!=0:
    return f

What is happening wrong here? Can't figure out! Any type of help will be highly appreciated


Your code causes an infinite loop because x will never become 0. Your code keeps running the while loop because x != 0 all the time. If it was, your code returns 0.

This is the code I used:

def factorial(x):
    result = 1
    for integer in range(1,x+1):
        result *= integer
    return result


Plus, you got some recursion going on in the while loop. I suggest either just doing a loop or a recursion but not both (due to optimisation purposes). Even if the recursion finishes, your while loop still runs because x will never become 0 if x != 0 as an input.


I have factorial calling itself, then return the factorial of the number, factorial (x - 1), while multiplying the returning the integer (x) with it.

@casz146 and @datfatcat explained what's going on in your code. I think if you took out the f=1 and put the 1 in your if statement, you can go from there and simplify your code to where I got mine.

This is what I had that passed.

def factorial(x):
    if x == 1:
        return 1
        return x * factorial(x - 1)


Oh yes, the recursion approach :+1:


Thanks man!
I think one more condition on if should have been added perhaps? That is when x==0?
Thanks for helping out!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.