I don't understand computing factorials


#1

I understand the initial instructions of computing a factorial beginning with defining a function first. But once the solution is provided I’m lost… Here it is:

def factorial(x):
total = 1
while x>0:
total *= x
x-=1
return total

Why do we keep adding the total variable when creating a function? I don’t understand. Can you please break this down and explain it to me as simply as possible. Thanks!


#2

lets say we want to calculate the factorial of 6, you get:

6 * 5 * 4 * 3 * 2 * 1

for which we use a loop. To make the loop work, we need a variable which keeps track of the result of all the multiplications (total)

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

we can even implement a print statement see total increasing each time we multiply total with x, and storing that result in total


#3

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