Recursion in Python: a function that calls itself
Recursion is when a function calls itself. Each call gets a smaller value,
and an if stops the calls when there is nothing left to do.
Read Defining Functions and Parameters & Return first.
A function that calls itself
Inside its own body, countdown calls countdown again, with a smaller
number:
def countdown(n): if n > 0: print(n) countdown(n - 1)countdown(3)countdown(3) prints 3, then calls countdown(2). That prints 2 and
calls countdown(1), which prints 1 and calls countdown(0). Each call
passes n - 1, a number one smaller than its own.
Stopping the recursion: the base case
The base case is the call that does nothing and calls nothing. Here it is
countdown(0): n > 0 is false, so the indented lines are skipped.
def countdown(n): if n > 0: print(n) countdown(n - 1)countdown(0)print("Liftoff!")countdown(0) prints nothing, so only Liftoff! appears. A negative number
skips the if too. Every call takes 1 off, so the calls always reach the base
case and stop.
Without the if, nothing stops the calls. Python gives up after about 1000
of them with a RecursionError:
def countdown(n):
print(n)
countdown(n - 1) # no base case: this raises RecursionError
countdown(3)
Recursion with the turtle
A recursive function can draw. Pass the turtle in as a parameter, and every call draws with the same turtle:
import turtledef stairs(t, steps): if steps > 0: t.forward(30) t.left(90) t.forward(30) t.right(90) stairs(t, steps - 1)t = turtle.Turtle()t.speed(0)stairs(t, 4)Each call draws one step, then asks stairs to draw the rest with
steps - 1. stairs(t, 0) is the base case: it draws nothing.
t.speed(0) makes the turtle draw as fast as it can.
See also: Defining Functions, Drawing shapes with turtle loops.
Your turn
Finish blastoff so it counts down in twos: inside the if, print n, then
call blastoff with n - 2.
7 5 3 1
def blastoff(n): if n > 0: # add two lines: print n, then call blastoff with n - 2 passblastoff(7)