A recursive function solves a problem by calling itself with a smaller problem. Build a function that counts how many one-step reductions separate a nonnegative integer from zero. The answer is familiar; the purpose is to make the calls and returns correct.
Every recursive algorithm needs a base case with a direct answer and a recursive case that moves toward it. Here zero needs zero reductions. A positive value needs one reduction, followed by however many reductions the smaller value needs. The smaller argument must be n - 1, not n, or the function would keep repeating the same problem.
For an input of three, the pending questions are "one plus the answer for two," "one plus the answer for one," and "one plus the answer for zero." Zero returns directly. The waiting additions then finish in reverse order. Each function call has its own local n; changing an argument for a new call does not overwrite the caller's local variable.
def describe_base(value: int) -> str:
if value == 0:
return "stop here"
return "a smaller problem is needed"
print(describe_base(0)) # stop here
The illustrative count calls follow the same reduction as steps_to_zero: the zero base answer lets each waiting addition finish.
Complete steps_to_zero(n) using a recursive call, rather than simply returning n or using a loop. The supplied _check_n helper accepts integers from zero through 100, raises TypeError for other types, and raises ValueError outside that range. Call it before choosing a case. This deliberate bound keeps the exercise well below typical stack limits; it is not a mathematical restriction on counting.
There are n + 1 calls, including the base case. Runtime is O(n) and the call stack uses O(n) space even though each call has only a small amount of local state. Python does not guarantee tail-call elimination, so recursive calls are not free jumps. Keep the examples small and do not change the recursion limit. The next lesson will make entry and return order visible.
The base-case branch is already placed before the recursive case. Each task changes one part of the function: validation, the direct base answer, then the smaller recursive call and its combination.
_check_n(n) before doing any work.Edit main.py, then press Run to inspect the supplied probe. Press Submit to check the operation on additional inputs. You do not need to copy code from another lesson.