5. factorial


#1




The code that I made creates an infinite loop. I understand why it creates an infinite loop, but I do not know how to stop it from happening. Please help me get out of this infinite loop.


I want it to start working


def factorial(x):
    if x == 0:
        return 1
    elif x == 1:
        return 1
    elif x == 2:
        return 2
    else:
        total = x
        while x >= 2:
            total = total * (x-1)
        return total
    print total


#2

Note that (x-1) does not change the value of x. If for example x is 10 then the loop will keep multiplying total by 9.
You need to actually change x on every run through the loop:

while x >= 2:
    total = total * (x - 1)
    x = x - 1

#3

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