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.

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.