Kodewick
Start learning →

Python Turtle Pythagoras Tree

A right triangle on top of a square, a smaller square on each of its short sides, and so on: a tree.

Python Turtle Pythagoras Tree
The full code (42 lines)
import turtle

screen = turtle.Screen()
screen.bgcolor("#f7f7f2")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.penup()
colors = ["#5b3a29", "#6f4e37", "#7c6a3c", "#6a8d3a", "#4f9d4f", "#3fae6a", "#5cc58a", "#8ddba8"]


def tree(size, level):
    # a square; on its top edge a right triangle, and a smaller tree on each of its two short sides
    if level == 0:
        return
    t.color(colors[min(len(colors) - 1, depth - level)])
    t.begin_fill()
    for i in range(4):
        t.forward(size)
        t.left(90)
    t.end_fill()
    small = size * 0.7071
    # to the top left corner, 45 degrees up: the left tree
    t.left(90)
    t.forward(size)
    t.right(45)
    tree(small, level - 1)
    # to the top of the triangle, 45 degrees down: the right tree
    t.forward(small)
    t.right(90)
    tree(small, level - 1)
    # back to this square's bottom left corner, facing the way it started
    t.left(90)
    t.backward(small)
    t.left(45)
    t.backward(size)
    t.right(90)


depth = 10
t.goto(-50, -230)
tree(100, depth)

How it is drawn

tree(size, level) fills a square, goes to its top left corner and turns 45 degrees to grow the left tree, then to the top of the triangle and turns 90 to grow the right one.

A small square's side is size * 0.7071 (√2 / 2): in a right isosceles triangle the short sides are √2 / 2 of the long one — Pythagoras' theorem.

After both small trees the turtle walks back to the square's bottom left corner, facing the way it started, so the level above can carry on. Get these steps wrong and the tree grows crooked.

The color comes from the level: greener further out. Each level doubles the squares; depth 12 is 4,095.

Questions

Why is the pen always up?

Only fills, no outlines, so there are no lines between squares. begin_fill and end_fill fill without the pen down.

Why does my tree lean?

Both sides are mirror images; if you change only the 45 degrees or the 0.7071, the two sides no longer match.

Try another