Prove Progress in Recursive Functions
Core idea
Recursion solves a problem by calling the same function on a smaller instance. A base case returns directly; recursive cases must approach it. For nonnegative n, decreasing n by one reaches zero after n steps. Python keeps active calls on the stack and imposes a recursion limit, so deep linear recursion may be better written as a loop.
def sum_to(n): if n < 0: raise ValueError("negative input") if n == 0: return 0 return n + sum_to(n-1)print(sum_to(4))print(sum_to(0))The calls reduce n until zero; results combine while returning.
Reject input outside the proof
def sum_to(n): if n < 0: raise ValueError("negative input") if n == 0: return 0 return n + sum_to(n-1)try: sum_to(-1)except ValueError: print("invalid")A negative argument would move farther from zero if repeatedly decreased.
Common mistake
A base case is not enough if recursive calls do not move toward it. Do not raise the recursion limit merely to make unbounded recursion work. The example uses O(n) active call frames.
Practice
Write and trace a recursive product for small nonnegative n, including zero; compare with a loop and describe stack use.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Recursive termination
Check your understanding of recursion and base cases.
What is printed?
def sum_to(n): if n < 0: raise ValueError("negative input") if n == 0: return 0 return n + sum_to(n-1)print(sum_to(3))What is printed?
def sum_to(n): if n < 0: raise ValueError("negative input") if n == 0: return 0 return n + sum_to(n-1)print(sum_to(0))What is the progress measure for sum_to(n)?
Why prefer a loop for very large linear recursion?