Editor

Square Spiral in Python Turtle

Beginner · Patterns and spirals · 20 lines · draws in about 9 seconds

Each line is 4 steps longer than the one before and the turtle turns 90 degrees after every line, so the path winds outward in a square spiral.

Square Spiral in Python Turtle: the finished drawing
import turtle
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Square spiral")
t = turtle.Turtle()
t.speed(10)
t.pensize(3)
colors = ["red", "gold", "lime", "deepskyblue"]
# Each line is a little longer than the one before, with a right angle between
for i in range(1, 100):
t.pencolor(colors[i % 4])
t.forward(i * 4)
t.right(90)
t.hideturtle()
turtle.done()

How the code works

Four colours in a list

The list holds the four pen colours, one for each side of a square. That is why each side of the spiral keeps its own colour all the way out.

colors = ["red", "gold", "lime", "deepskyblue"]

A line that grows every time

i counts from 1 to 99, so forward(i * 4) draws lines of 4, 8, 12 steps and so on. colors[i % 4] picks the next colour and goes back to the first after the fourth, and right(90) makes the corner.

# Each line is a little longer than the one before, with a right angle between
for i in range(1, 100):
    t.pencolor(colors[i % 4])
    t.forward(i * 4)
    t.right(90)

Make it yours

Change the code above and press Run. Some ideas:

  • Change t.right(90) to t.right(91) and the spiral twists as it grows.
  • Change i * 4 to i * 2 for a smaller spiral with the lines packed closer together.
  • Add "violet" to the list and change i % 4 to i % 5 so the colours wind around the spiral instead of keeping to one side each.

What it uses

Every turtle command the site supports is listed on Python turtle online.