5.factorial


#1

The code that i wrote keeps giving me a wrong result, but I dont understand wher is my mistake

def factorial(x):
    while x > 1:
        result = x* (x-1)
        x = x-1
        return result
    else:
        return 1

Factorial - was my approach too simple?
#2

This return is inside the loop block so returns after only one iteration.

This is going to be 2 every time. Only the last computation is stored in result.

Consider:

def factorial(x):
    result = 1
    while x > 1:
        result *= x    # notice that this is cummulative
        x -= 1
    return result

#3

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