← Python lessons

Recursive functions that return a value

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A recursive function can return a value: each call returns its own part plus what a smaller call returns. The base case returns the starting value, such as 0.

Read Recursion in Python: a function that calls itself and Parameters & Return first.

Return the result of a smaller call

total(n) adds up the numbers from n down to 1. Each call returns its own n plus the total of the numbers below it:

def total(n):    if n > 0:        return n + total(n - 1)    return 0print(total(4))

It printed 10. total(4) returns 4 + total(3). That waits for total(3), which returns 3 + total(2), and so on down to total(0). Then the answers come back up: 0, 1, 3, 6, 10.

The base case returns the starting value

The base case does no work, so it returns the starting value: 0 for a count or a sum, 1 for a product. The return 0 sits after the if, so it runs only when n > 0 is false.

To count calls, add 1 for each one. steps(n) counts how many hops of 2 it takes to get from n down to 0 or below:

def steps(n):    if n > 0:        return 1 + steps(n - 2)    return 0print(steps(5))print(steps(0))

It printed 3 and 0. steps(5) is 1 + steps(3), which is 1 + 1 + steps(1), which is 1 + 1 + 1 + steps(-1). steps(-1) returns 0, so the answer is 3.

Note: Without return 0, the base case returns None. Then 1 + None stops Python with a TypeError.

Keep a running count

A function that calls itself twice gets two answers back. Keep them in a variable: start it at 1 for this call, then add what each smaller call returns.

def count_calls(n):    if n > 0:        count = 1        count = count + count_calls(n - 1)        count = count + count_calls(n - 1)        return count    return 0print(count_calls(3))

It printed 7: one call of 3, two of 2 and four of 1. count = 1 and return count sit inside the if, so only a call that does its work counts itself. count_calls(0) returns 0.

Add up results in a loop

You can call a function that returns a value in a loop, and add up every answer. Start the total at 0 before the loop:

def steps(n):    if n > 0:        return 1 + steps(n - 2)    return 0total = 0for i in range(3):    total = total + steps(5)print(total)

It printed 9. Each pass adds steps(5), which is 3, so the total goes 3, 6, 9.

See also: Branching recursion: a function that calls itself twice, The base case: recursion with an order.

Your turn

product(n) multiplies the numbers from n down to 1. Add the two returns: n times product(n - 1) inside the if, and 1 after it.

🎯 Goal — make it print exactly:
24
def product(n):    if n > 0:        pass  # replace this line: return n times product(n - 1)    # add a line: the base case returns 1print(product(4))