Factorial


#1


https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096

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)
        num=num*(i+1)
        print(num)
    return num
print(factorial(6))


#2

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

here:

num=num*(i+1)

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


#3

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


#4

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


#5

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.


#6

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
"""


#7

Very helpful. Thanks Wchiment!


#8

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


#9

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