I don't understand how it works


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#
No problems
I don't understand how this works, I just followed the instructions.
how does the factorial thing work?

def factorial(x):
    if x == 1:
        return 1
    return x * factorial(x - 1)

#2

may be your error is factorial 0, test is i just change == to <=

def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1)

#3

Pencil through it with a small number to see it played out...

Let x = 7.

x <= 1                    # base case (also input validation)
    return 1
return 7 * factorial(6)   # 5040   -> return value
return 6 * factorial(5)   # 720    ^
return 5 * factorial(4)   # 120    ^
return 4 * factorial(3)   # 24     ^
return 3 * factorial(2)   # 6      ^
return 2 * factorial(1)   # 2      ^

The recursion builds a call stack of all the return expressions, but not their values (since they cannot be determined, just yet). When the base case is reached, recursion is terminated and the call stack is popped off, this time as a value. That value is used in the next return, which is then popped off, and so on all the way up the stack. Once the last return is reached, its value is returned to the caller.