Kodewick
Start learning →

Python Turtle Sierpinski Triangle

A triangle becomes three half-size ones (the middle one left out), and each of those the same — the classic recursive fractal.

Python Turtle Sierpinski Triangle
The full code (36 lines)
import turtle

screen = turtle.Screen()
screen.bgcolor("white")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
colors = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51", "#8338ec"]


def triangle(x, y, size, color):
    # a filled equilateral triangle, its bottom left corner at (x, y)
    t.penup()
    t.goto(x, y)
    t.setheading(0)
    t.color(color)
    t.begin_fill()
    for i in range(3):
        t.forward(size)
        t.left(120)
    t.end_fill()


def sierpinski(x, y, size, level):
    # a triangle becomes three half-size ones (the middle left out), and each of those the same
    if level == 0:
        triangle(x, y, size, colors[(int(x + y) // 7) % len(colors)])
        return
    half = size / 2
    sierpinski(x, y, half, level - 1)
    sierpinski(x + half, y, half, level - 1)
    sierpinski(x + half / 2, y + half * 0.866, half, level - 1)


level = 5
sierpinski(-250, -210, 500, level)

How it is drawn

sierpinski(x, y, size, level): at level 0 it draws one filled triangle; otherwise it splits into bottom left, bottom right and top halves, each drawn by sierpinski one level lower.

The upside-down middle triangle is never drawn, so it stays empty — those are the fractal's holes.

The top triangle's corner is at (x + half / 2, y + half * 0.866): 0.866 is √3 / 2, an equilateral triangle's height over its side.

Each level triples the triangles: level 5 is 243, level 7 is 2,187.

Questions

Where do the colors come from?

A number worked out from the triangle's position (x + y) picks a color from the list, so colors are scattered over the triangle.

Why not a higher level?

There are 3 to the power of the level triangles: level 8 is 6,561, slow to draw. This page goes up to 7.

Try another