Looking for explanation

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?”

Is the entire course based on videos with solutions? You might find it’s more effective for learning by solving these problems without so much instruction. Finding yourself with a solution you don’t understand is likely to be an issue because those little gaps in your knowledge will hold you back as you continue. Just take a little time and work out if this is actually an effective learning route for you.

As for x, assignment to a name is part of the for loop syntax-

Return does what it always does, stops execution of the function and passes the value back to the caller-

Yes, the entire course is video based with minor reading in between, but so far every single “reading assessment” has been an exact copy of the notes I took during the video, practically word for word. I’m definitely finding it hard to follow on and some of their practice questions include topics that haven’t even been discussed/taught yet. I wanted to try and power through because the course is paid for and the result is a Certification from Google, but I agree with your assessment entirely that the gaps in my knowledge are making it very frustrating to try and follow along. The course was supposed to be designed as a “intro to your very first programming language,” and yet it’s filled with cringe jokes and as I stated there’s frequently a question involving something they haven’t shown yet.

Thanks for the links, I’ll check them out now.