American Flag in Python Turtle
Intermediate · Flags · 83 lines · draws in about 20 seconds
This program draws the flag of the United States with 13 stripes and 50 stars at the official proportions, using a nested loop that staggers rows of six and five stars.

How the code works
Sizes from the official flag
Every size is a fraction of the height, taken from the official specification: the flag is 1.9 times as wide as it is high, the blue union covers 7 stripes, and each star is 0.0616 of the height across.
HEIGHT = 300 WIDTH = HEIGHT * 1.9 STRIPE = HEIGHT / 13 UNION_WIDTH = HEIGHT * 0.76 UNION_HEIGHT = STRIPE * 7 # Star spacing and size, also from the official specification GAP_X = HEIGHT * 0.063 GAP_Y = HEIGHT * 0.054 STAR_RADIUS = HEIGHT * 0.0616 / 2
A star from ten short lines
The turtle starts at the top point and turns left 72 degrees at each inner corner and right 144 degrees at each tip, five times over. Tracing the outline, instead of crossing lines, lets begin_fill() fill the whole star.
def star(x, y, radius, color): """Draw a filled five-pointed star centred at (x, y).""" edge = radius * 0.7265 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(edge) t.left(72) t.forward(edge) t.right(144) t.end_fill()
Thirteen stripes in a loop
stripe % 2 == 0 is true for stripes 0, 2, 4 and so on, so red and white take turns and the first and last stripes are red.
for stripe in range(13): if stripe % 2 == 0: color = RED else: color = "white" rectangle(left, top - stripe * STRIPE, WIDTH, STRIPE, color)
Nine rows of stars
Rows of six sit in the odd columns and rows of five in the even columns between them. The inner loop draws one row, and the outer loop moves down one gap at a time.
for row in range(9): y = top - (row + 1) * GAP_Y if row % 2 == 0: columns = range(1, 12, 2) else: columns = range(2, 11, 2) for column in columns: star(left + column * GAP_X, y, STAR_RADIUS, "white")
Make it yours
Change the code above and press Run. Some ideas:
- Change
t.speed(10)tot.speed(0)to see the finished flag at once. - Change
"white"in the laststar(...)call to"gold"for golden stars. - Change
HEIGHT = 300toHEIGHT = 200for a smaller flag: every stripe, star and gap shrinks with it.
What it uses
- nested for loops
- functions with parameters
- the % operator
- begin_fill and end_fill
Every turtle command the site supports is listed on Python turtle online.