Recursion inside a for loop
Recursion inside a for loop means a function calls itself in the body
of a for loop. The call runs once on every pass of the loop.
So one call can start two, three or more smaller calls.
Read The base case: recursion with an order first.
One section with a loop
Start with the loop on its own, with no recursion yet. This loop draws three lines out from one spot. Each pass goes out, comes back and turns:
import turtlet = turtle.Turtle()t.speed(0)for i in range(3): t.forward(100) t.backward(100) t.left(120)print(t.position())print(t.heading())It drew three lines of 100, 120 degrees apart. Three turns of 120 make a
full turn of 360, so it printed (0.00,0.00) and 0.0. The turtle ends
where it started, facing the way it started. That matters once the loop
sits inside a recursive function: each call must leave the turtle where it
found it.
A recursive call in the loop body
Here the loop body prints, then calls repeat with depth - 1. The
if depth > 0: line is the base case: depth 0 does nothing.
def repeat(depth): if depth > 0: for i in range(2): print(depth) repeat(depth - 1)repeat(2)It printed 2, 1, 1, 2, 1, 1. On the first pass, repeat(1)
does all its work before the loop's second pass starts. Then the second
pass prints 2 and calls repeat(1) again.
How many calls?
Each call runs its loop, so each call makes as many calls as the loop has
passes. With range(3), depth 2 makes 3 calls, and each of those makes 3
more:
def spread(depth): if depth > 0: for i in range(3): print("depth", depth) spread(depth - 1)spread(2)It printed 12 lines: 3 at depth 2 and 9 at depth 1. One more depth
would add 27 lines, because every level has 3 times as many calls as the
level before.
See also: Branching recursion: a function that calls itself twice, For Loops.
Your turn
fan prints its depth. Add a for loop over range(2) that calls fan
with depth - 1, so fan(2) prints three lines.
fan 2 fan 1 fan 1
def fan(depth): if depth > 0: print("fan", depth) # add two lines: a for loop over range(2) that calls fan with depth - 1fan(2)