Codes works but I was hoping someone could walk me through.

When I do it on paper the factors are not multiplied together.

def factorial(x):
    num = 1
    for i in range(x): #range is 0 thru x (this case 5)does not include x (x-1)
    return num


why not? You added a print statement, so you it happening



you store the current value of num multipied by i+1 into num, this will cause num to increase each run of the loop


what are the values in the first iteration for num=num*(i+1)?

I thought I understood, but now I'm just confused.

x sets the range
what is the first i value?
please show me


range() produces a list, i will contain the values of the list produced by range

The first value in the list is 0, so for the first run of the loop i will be zero, you can verify this by adding print i


I got it. On paper, I was incrementing num instead of plugging the previous value of num from the prior iteration. If that makes sense. Thank you.


Made some notes and thought this might help someone else.

range is 0 -5. one less than value of range or x
num starts at 1
num = num * (i+1)

1 = 1 * (0 + 1) range or i starts at 0 and increments at each iteration
1 = 1 * (1 + 1) range incremented and result stored in num for next iteration
2 = 2 * (2 + 1) result stored in num
6 = 6 * (3 + 1) result stored in num
24 = 24 * (4 + 1) result stored in num
120 = 120 * (5 + 1) result stored in num
breaks loop because hits range of 5
value stored in num is returned as 720


Very helpful. Thanks Wchiment!


You're welcome! I'm glad I get to actually help someone else for a change!


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