How does this for loop work?

Screen Link:
https://app.dataquest.io/m/380/permutations-and-combinations/4/permutations

My Code:

def factorial(n):
    final_product = 1
    for i in range(n, 0, -1):
        final_product *= i
    return final_product

Hi. I was asked to write a function to calculate the factorial for any input. My function worked fine. However, when viewing the example answer, I was confused how their for loop worked. Specifically, I did not understand what range(n, 0, -1) was doing. Any explanations would be helpful.

Thanks.

Hi @mjs139, the range () function takes 3 arguments: start, stop, and step. Essentially, it returns a sequence of numbers starting at a specified number (i.e., start argument), increment by a specified number(i.e., step argument), and stops before a specified number (i.e., stop argument).

So as applied to the factorial () function, it means that, for any n passed to range(), create a sequence of numbers starting from n, increment by -1 before you reach 0. Loop through the sequenence of numbers produced and multiply each number by the value of final_product at every looping. See here for more on the range() function.

Hopefully, this helps!

That clears it up. Thanks.

With respect to the following explanation. This is how the loop would iterate.

fgfgfgfgfgfg

Hope this solves your query. :smile:

1 Like

@mjs139 glad you are clear now!. Could you then please mark the post as solved? If needed see How do I mark a post as solved?.

Always good to add illustrations to enhance explanations. Thanks!

So true buddy. :smile: