Python Turtle Spirograph
The toy you may remember: a small circle rolling inside a big one, the pen drawing loops. Change three numbers for a completely different pattern.

The full code (23 lines)
import turtle
import math
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.pensize(2)
# a spirograph: a small circle (radius r) rolls inside a big one (radius R), the pen d from its centre
R = 150
r = 52
d = 90
colors = ["#ff595e", "#ffca3a", "#8ac926", "#1982c4", "#6a4c93"]
t.penup()
for i in range(0, 3601):
a = math.radians(i * 2)
x = (R - r) * math.cos(a) + d * math.cos((R - r) / r * a)
y = (R - r) * math.sin(a) - d * math.sin((R - r) / r * a)
t.pencolor(colors[i // 120 % len(colors)])
t.goto(x, y)
t.pendown()How it is drawn
The curve is a hypotrochoid: the small circle's centre goes round the big circle, (R - r) * cos(a), and the pen goes round that centre the other way, d * cos((R - r) / r * a); their sum is the pen.
for i in range(0, 3601) takes the angle from 0 to 7,200 degrees (2 a step): enough turns for the curve to close.
The color changes every 120 points: colors[i // 120 % len(colors)] (// divides and drops the remainder).
The pen is up for the first point and down after it, so no line comes from the centre.
Questions
Why do some numbers leave a gap?
The more awkward the ratio of R to r, the more turns it takes to come back to the start. Click Edit and make 3601 bigger.
What if d equals r?
The pen is on the small circle's edge and the curve gets sharp points. Smaller d gives smooth petals, bigger d little loops.
Try another
Rainbow spiralChange one angle, get a new picture
SunflowerSeeds in golden-angle spirals
Sierpinski triangleA triangle full of holes
SnowflakeThe Koch curve, folded finer and finerIn the tutorial: Circles and arcs →All turtle examples →Python playground →