Python Fundamentals · Functions

Recursion: Functions That Call Themselves

factorial(4) calls factorial(3), which calls factorial(2)… Watch the frames stack up until the base case, then unwind with the answers.

recursion.py

def factorial(n):
    if n <= 1:              # the base case stops the recursion
        return 1
    return n * factorial(n - 1)

result = factorial(4)
print(result)

Step by step

  1. Python defines the function factorial(). Its body does not run yet: it runs each time the function is called.
  2. Start: factorial(4).
  3. n = 4: not the base case.
  4. factorial(4) needs factorial(3), so it pauses and calls itself. A new frame appears in Memory.
  5. Line runs: if n <= 1: # the base case stops the recursion.
  6. n changes from 3 to 2.
  7. Line runs: if n <= 1: # the base case stops the recursion.
  8. n changes from 2 to 1.
  9. n = 1: the base case.
  10. Return 1: the first answer, and the stack starts unwinding.
  11. factorial(2) gets 1 back: 2 × 1 = 2.
  12. factorial(3): 3 × 2 = 6.
  13. factorial(4): 4 × 6 = 24.
  14. Start: factorial(4).
  15. 24. The calls stacked up to the base case, then each frame finished with the answer from the one above it.