6.4.2 Tracing the Recursive Call Stack

Unit: Unit 6: Functions • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Trace stack winding and unwinding with diagnostic indentation
def trace_depth(depth, max_depth):
    indent = "  " * depth
    print(f"{indent}-> Entering level {depth}")

    if depth == max_depth:
        print(f"{indent}** Base case reached at level {depth}! **")
    else:
        trace_depth(depth + 1, max_depth)

    print(f"{indent}<- Exiting level {depth}")

trace_depth(1, 3)
Open in Live Interactive Python Sandbox →