Moon and Stars in Python Turtle
Intermediate · Nature · 69 lines · draws in about 10 seconds
This program paints a night sky with a crescent moon drawn as two arcs of the same circle size, a soft glow and gold stars.

How the code works
Stars from an outline
The turtle starts at the top point and turns left 72 degrees at each inner corner and right 144 degrees at each tip. Tracing the outline lets begin_fill() fill the whole star.
def star(x, y, radius, color): """A filled five-pointed star centred at (x, y).""" t.penup() t.goto(x, y + radius) t.setheading(288) t.pendown() t.color(color) t.begin_fill() for point in range(5): t.forward(radius * 0.7265) t.left(72) t.forward(radius * 0.7265) t.right(144) t.end_fill()
Tiny stars at random
random.seed(12) makes the random places the same on every run. t.speed(0) before the loop puts all 90 dots down at once.
for twinkle in range(90): t.goto(random.randint(-300, 300), random.randint(-215, 215)) t.dot(random.choice([2, 3, 4]), "white")
A crescent from two arcs
From the middle of the moon's circle the turtle walks out to the top tip and turns to follow the edge. It draws 210 degrees of the circle round the left, turns left 150 degrees at the bottom tip, and draws 150 degrees of a circle of the same size the other way, back up to the top tip.
radius = 150 t.setheading(75) t.forward(radius) t.left(90) t.pendown() t.color(MOON) t.begin_fill() t.circle(radius, 210) # the outside edge, round the left t.left(150) t.circle(-radius, 150) # the inside edge, curving back up t.end_fill()
Make it yours
Change the code above and press Run. Some ideas:
- For a fatter moon, change
75to60,210to240, and both150s in the crescent to120. - Add another bright star with a line such as
star(-200, -150, 16, "gold"). - Change
range(90)torange(200)for a sky full of tiny stars.
What it uses
- circle with extent
- functions with parameters
- random with a seed
- dot
Every turtle command the site supports is listed on Python turtle online.