Kodewick
Start learning →

Python Turtle Cherry Blossom Tree

A tree grown by recursion, different every time you open the page. Click the numbers below and watch it change.

Python Turtle Cherry Blossom Tree
The full code (44 lines)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("#fff7f2")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)

# grow up from the ground
t.left(90)
t.penup()
t.goto(0, -220)
t.pendown()


def branch(length, level):
    if level <= 1:
        # blossoms at the ends of the branches
        t.dot(random.randint(12, 18), random.choice(["pink", "lightpink", "hotpink", "mistyrose"]))
    if level == 0:
        return
    t.pensize(level * 1.8)
    t.pencolor("#6b3e26")
    t.forward(length)
    angle = random.randint(18, 32)
    t.left(angle)
    branch(length * random.uniform(0.66, 0.8), level - 1)
    t.right(angle * 2)
    branch(length * random.uniform(0.66, 0.8), level - 1)
    t.left(angle)
    # back to where this branch started
    t.penup()
    t.backward(length)
    t.pendown()


branch(110, 9)

# petals the wind blew down
t.penup()
for i in range(60):
    t.goto(random.randint(-280, 280), random.randint(-250, -200))
    t.dot(random.randint(5, 9), random.choice(["pink", "lightpink"]))

How it is drawn

The tree is drawn by recursion: branch(length, level) draws one branch, then grows a shorter branch to the left and one to the right — each drawn by branch itself, one level lower. At level 0 it stops splitting.

The angle of each split, random.randint(18, 32), and how much shorter a branch gets, random.uniform(0.66, 0.8), are random, so no two trees are alike.

The last two levels blossom: t.dot(size, color) puts a dot at the end of a branch, in one of a few pinks.

After a branch the turtle goes back to where it started (t.backward(length)), or the next branch would start in the wrong place — the step people most often miss.

Questions

Does this code run on my own computer?

Yes. With Python 3 installed, save it as tree.py and run python tree.py: a window opens and draws it (turtle comes with Python). This page draws exactly what real Python draws, stroke for stroke.

Why is it slow with more levels?

Each level doubles the branches: 9 levels is about 500 branches, 11 levels over 2,000. Try a smaller number first.

What does RecursionError mean?

The recursion never stops. branch lowers the level by one each time and stops at 0; if the level does not go down, it calls itself forever.

How do I get the same tree every time?

Add random.seed(1) right after import random: the random numbers are then the same on every run.

Try another