A tree that grows by itself (recursion)
Section 13: Pro drawing and chartsLesson 13.2 · ⏱ 14 min
🎯 Project goal
A whole tree with its branches and green leaves, from one function that calls itself.

The idea: a tree is a trunk, and at its end are two smaller trees, left and right. So the tree function draws the trunk, then calls itself twice with a shorter length. The level goes down each time, and when it reaches zero it stops, otherwise it would never end.
import turtle
t = turtle.Turtle()
t.speed(0)
t.left(90)
t.penup()
t.goto(0, -150)
t.pendown()
t.color("sienna")
def tree(length, level):
if level == 0:
return
if level <= 2:
t.color("green")
t.forward(length)
t.left(25)
tree(length * 0.7, level - 1)
t.right(50)
tree(length * 0.7, level - 1)
t.left(25)
t.color("sienna")
t.backward(length)
tree(90, 7)
t.hideturtle()
🐍 Open the code in Robo Python ↗backward(length)takes the turtle back to the start of the branch, so it draws the next branch from the right place.- The last branches (level 2 and 1) are green like leaves.
- Change the angle 25 to 15, then to 40. How does the tree change?
- Try level = 9. Why is the drawing slow? (the number of branches doubles at each level)
📌 Another example: a tree with three branches
Three smaller branches come out of every branch.
import turtle
t = turtle.Turtle()
t.speed(0)
t.left(90)
t.penup()
t.goto(0, -150)
t.pendown()
t.color("brown")
def tree(size):
if size < 12:
return
t.forward(size)
for angle in (-30, 0, 30):
t.right(angle)
tree(size * 0.55)
t.left(angle)
t.backward(size)
tree(110)
🐍 Open the code in Robo Python ↗
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A function that counts down with recursion.
👀 Show the solution🙈 Hide the solution
def countdown(n):
if n == 0:
print("Go!")
return
print(n)
countdown(n - 1)
countdown(5)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗5 4 3 2 1 Go!
Result: 5 4 3 2 1 Go!
Medium
The factorial: 5! = 5 × 4 × 3 × 2 × 1 with recursion.
👀 Show the solution🙈 Hide the solution
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(5))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗120
Result: 120
Hard
A tree with green leaves (the small branches in another colour).
👀 Show the solution🙈 Hide the solution
import turtle
t = turtle.Turtle()
t.speed(0)
t.left(90)
t.penup()
t.goto(0, -150)
t.pendown()
def tree(size):
if size < 10:
return
t.color("green" if size < 30 else "brown")
t.pensize(max(1, size // 15))
t.forward(size)
t.right(25)
tree(size * 0.7)
t.left(50)
tree(size * 0.7)
t.right(25)
t.color("green" if size < 30 else "brown")
t.backward(size)
tree(90)
🐍 Open the code in Robo Python ↗
Result: a tree with green leaves.

