← Python lessons

Recursion: code after the recursive call

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

In a recursive function, the lines after the recursive call run once that call has finished. They run on the way back, last call first.

Read Recursion in Python: a function that calls itself first.

Lines after the call run on the way back

there_and_back prints before it calls itself and again after:

def there_and_back(n):    if n > 0:        print("out", n)        there_and_back(n - 1)        print("back", n)there_and_back(3)

It printed out 3, out 2, out 1, then back 1, back 2, back 3. there_and_back(3) prints out 3, then waits while there_and_back(2) does all its work. Only then does it print back 3.

Each call keeps its own n. The call with n as 1 finishes first, so back 1 comes first and back 3 comes last.

Out and back with the turtle

The same idea brings a turtle home. Each call steps forward, lets the next call do the rest, then steps back:

import turtledef out_and_back(t, steps):    if steps > 0:        t.forward(20)        out_and_back(t, steps - 1)        t.backward(20)t = turtle.Turtle()t.speed(0)out_and_back(t, 5)print(t.position())

The turtle goes out 5 steps of 20. Then each call, as it finishes, goes back its own step. It printed (0.00,0.00): the turtle ends where it started.

See also: Recursion in Python: a function that calls itself, Turtle backward(): going back to the start.

Your turn

count_up prints nothing yet. Add one line after the recursive call that prints n, so count_up(3) counts up.

🎯 Goal — make it print exactly:
1
2
3
def count_up(n):    if n > 0:        count_up(n - 1)        # add one line: print ncount_up(3)