New coder here, don’t worry I’m not copy pasting my test question begging for the solution. The question is already solved, however I couldn’t explain why it worked when trying to jot it down in my own notes.
The base question was: Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all integers before it. For example, the factorial of five (5!) is equal to 12345=120. Also recall that the factorial of zero (0!) is equal to 1.
As I stated, I have already answered the question, the focus is on my own notes attempting to explain each line. The course is taught with videos where they brush over the topics and give one example and move on, and I’m finding myself not understanding why certain things work when it looks like they shouldn’t. My answer was:
def factorial(n): ## defining function called factorial using variable (n)
result = 1 ## base result is 1
for x in range(1,n): ## for all values of x between 1 and n (where is x defined? why does it allow x out of nowhere?)
result *= x ## new result is (result * x)
return result ## update result exit loop?
for n in range(0,10):
print(n, factorial(n+1))
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
I just wanted a better of understanding of “why does x work here?” and “what exactly is return result doing?”