← Python lessons

The base case: recursion with an order

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

The base case of a recursive function does the simple job itself, without calling the function again. An order counts down to 0, the base case.

Each call passes order - 1, so the order goes down by 1 every time.

Read Branching recursion: a function that calls itself twice first.

Count down an order

countdown checks for order 0 first. Every other order prints its number and calls countdown with order - 1:

def countdown(order):    if order == 0:        print("Lift off!")    else:        print(order)        countdown(order - 1)countdown(3)

It printed 3, 2, 1, then Lift off!. The order goes down by 1 each time, so it always reaches 0. The call with order 0 is the base case: it prints Lift off! and makes no more calls.

The base case does the simple job

In a drawing, the base case draws the simplest piece. Here order 0 draws a line with a tick, out 10 and back. Every other order is two rulers of the order below, each half as long:

import turtledef ruler(t, size, order):    if order == 0:        t.forward(size)        t.left(90)        t.forward(10)        t.backward(10)        t.right(90)    else:        ruler(t, size / 2, order - 1)        ruler(t, size / 2, order - 1)t = turtle.Turtle()t.speed(0)ruler(t, 200, 2)print(t.position())

Only order 0 draws anything. The else: part just splits the job into smaller rulers. It drew 4 lines of 50, each with a tick, and printed (200.00,0.00).

Order 0, order 1, order 2

Each order up doubles the pieces, because each call makes two calls. Here the base case prints its size instead of drawing it:

def pieces(size, order):    if order == 0:        print(size)    else:        pieces(size / 2, order - 1)        pieces(size / 2, order - 1)pieces(200, 0)print("---")pieces(200, 1)print("---")pieces(200, 2)

Order 0 printed one piece of 200. Order 1 printed two of 100.0, and order 2 printed four of 50.0. The pieces are always printed by the base case, so the size only splits up.

See also: Recursion in Python: a function that calls itself, Turtle graphics in Python.

Your turn

dots prints dot at order 0. Add two calls to dots with order - 1, so dots(1) prints three lines.

🎯 Goal — make it print exactly:
order 1
dot
dot
def dots(order):    if order == 0:        print("dot")    else:        print("order", order)        # add two lines: call dots with order - 1, twicedots(1)