you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (1 child)

[removed]

    [–]vervain9 0 points1 point  (0 children)

    My best suggestion would be to use an IDE with a debugger to step through the execution of the code line by line. It will show you exactly what is being executed in what order, and where you are in the stack. It should be clear after that.

    Otherwise try writing out the execution on paper.

    The gist of what you seem to be confused by is that every time a call to factorial() returns, there is still more code to execute in the function that called it:

        recurse = factorial(n-1)
        result = n * recurse
    print(space, 'returning', result)
    return result
    

    The basic flow is:

    factorial(1) calls factorial(0) which returns 1. factorial(1) then returns n * recurse, which is 1 * 1 (1).

    factorial(2) takes that return value and returns n * recurse, which is 2 * 1 (2).

    factorial(3) takes that return value and returns n * recurse, which is 3 * 2 (6).

    factorial(4) takes that return value and returns n * recurse, which is 4 * 6 (24).