Editor

Python Turtle Star

Beginner · Shapes · 39 lines · draws in about 11 seconds

The star is ten straight lines, in to an inner corner and out to a point five times, so the whole shape fills with gold.

Python Turtle Star: the finished drawing
import turtle
import random
random.seed(41)
screen = turtle.Screen()
screen.bgcolor("midnightblue")
screen.title("Star")
t = turtle.Turtle()
# Small white dots for a night sky
t.speed(10)
t.penup()
for i in range(30):
x = random.randint(-300, 300)
y = random.randint(-220, 220)
t.goto(x, y)
t.dot(random.randint(3, 7), "white")
# Go to the top point of the big star, facing along its first line
t.goto(0, 199)
t.setheading(-72)
t.pendown()
t.speed(4)
t.pensize(5)
t.color("orange", "gold")
# Each pass goes in to an inner corner, then out to the next tip
t.begin_fill()
for i in range(5):
t.forward(160)
t.left(72)
t.forward(160)
t.right(144)
t.end_fill()
t.hideturtle()
turtle.done()

How the code works

A sky full of dots

With the pen up the turtle moves without drawing. Each time round the loop it goes to a random spot and leaves a white dot() of a random size, and random.seed(41) at the top makes the same sky appear every time.

# Small white dots for a night sky
t.speed(10)
t.penup()
for i in range(30):
    x = random.randint(-300, 300)
    y = random.randint(-220, 220)
    t.goto(x, y)
    t.dot(random.randint(3, 7), "white")

Get ready at the top point

setheading(-72) points the turtle down and to the right, along the first edge of the star. The speed drops to 4 so the star is drawn slowly enough to watch.

# Go to the top point of the big star, facing along its first line
t.goto(0, 199)
t.setheading(-72)
t.pendown()
t.speed(4)
t.pensize(5)
t.color("orange", "gold")

Ten lines make five points

Each pass draws two lines: in to an inner corner, left(72), out to the next point, then right(144). Five passes bring the turtle back to the start, so end_fill() fills a closed outline. A star drawn with five crossing lines would keep an empty middle when filled, which is why this one traces the outline instead.

# Each pass goes in to an inner corner, then out to the next tip
t.begin_fill()
for i in range(5):
    t.forward(160)
    t.left(72)
    t.forward(160)
    t.right(144)
t.end_fill()

Make it yours

Change the code above and press Run. Some ideas:

  • Change range(30) to range(80) for a sky with more stars.
  • Change t.color("orange", "gold") to t.color("deepskyblue", "lightcyan") for an icy blue star.
  • Change random.seed(41) to another number, such as random.seed(5), to scatter the dots in a new pattern.

What it uses

  • for loops
  • begin_fill and end_fill
  • random numbers
  • dot

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