Trace a smaller call

Lesson 16 of 20 · Functional Python: values, behavior, and choices

A recursive function calls itself. It needs a base case that returns without another recursive call and a step that moves toward that case. This example repeats a beat a non-negative number of times; the input contract is an integer, checked explicitly here.

def beats(count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a non-negative integer")
    if count == 0:
        return ""
    return "tap " + beats(count - 1)

print(repr(beats(3)))
print(repr(beats(0)))
'tap tap tap '
''

Each call has its own local count. The waiting calls resume after the smaller result returns. repr displays the quotes and trailing spaces; the strings themselves do not contain those quote marks.

beats(3) → "tap " + beats(2) → "tap " + "tap " + beats(1)
         → "tap " + "tap " + "tap " + beats(0)
         → "tap tap tap "

The step subtracts one until zero for the accepted domain. A base case does not help when a step moves away from it. The exact type check also excludes Boolean values, which are a subclass of int in Python. For simple repetition, "tap " * count is clearer; recursion helps us reason about structures defined in smaller pieces.

Chapter index