def calculate_factorial(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
print(calculate_factorial(5))
I had to create a block of code that calculates the factorial of any given number in calculate_factorial(n).
I didn’t understand how to do it so I googled the answer but there was no explanation of what each line meant.
line 1. I understand defining ‘calculate_factorial(n)’ is to define ‘calculate_factorial(n)’ as a variable and to run the block when called upon and given a value, like so at the end of the block.
Not sure:
line 2. factorial holds the value 1. line 3. in for i in range is a loop, ‘(1, n+1)’ because i want values 1 through n since last number isn’t counted.
4. i guess 1 times range? so why wouldnt that give that? For example, I gave (5) so shouldn’t it have looped (1 times 1, 1 times 2, 1 times 3, 1 times 4, 1 times 5)?
5. returns answer to ‘factorial *= i’?
go ahead and roast me, I’m new, but please tell me where I’m wrong after “not sure:”. I can also type what I tried but its embarrassing. I was using while loops and if/break.