5 Factorial question - why does this code work?


#1

I'm trying to figure out why this code works, specifically the math portion in the function's range. It goes as follows:

def factorial(x):
    total = 1
    for t in range(1, x+1):
        total = total * t
    return total
    print total

print factorial(4)

Why is it that when the function is executed, specifically the following section:

   for t in range(1, x+1):
        total = total * t

the function executes (4*3*2*1) instead of ((1*4)+(1*3)+(1*2)+(1*1))? In other words, could you walk me through the math that's taking place?


#2

the best way to figure out why something is working is adding print statements:

def factorial(x):
    total = 1
    for t in range(1, x+1):
        print t
        total = total * t
        print total
    return total
    print total # this line is useless, 
#functions end the moment a return keyword is reached

print factorial(4)

t will hold the numbers (1,2,3,4) and multiply them with total (total gets constantly updated


#3

Well, total = total * t doesn't have any + symbol in it so it won't be adding anything. You're basically accumulating total. So let's say t is 1. Total is 1 as well so 1 * 1 = 1. Total is still 1.
Next, t becomes 2 while total is still 1. 2 * 1 = 2. Total is now 2. Repeat this until the function reaches x.

Print statements and tracing it will help you understand it better.


#5

2 posts were split to a new topic: 5. factorial


#6

Thanks for the help!


#7

aha! that makes sense! domo arigato