
python
Draw USA flag with Python
Draw USA Flag with Python" is a fun and interactive coding project that guides you step-by-step to recreate the iconic American flag using Python programming.
draw-usa-flag-with-python.py
1import turtle
2import time
3
4# --- Setup Official Flag Proportions ---
5# Using variables for precise calculations [cite: 27, 29]
6HOIST = 400
7FLY = 760
8STRIPE_H = HOIST / 13
9CANTON_H = STRIPE_H * 7
10CANTON_W = FLY * 0.4
11STAR_SIZE = 12
12
13screen = turtle.Screen()
14screen.setup(width=900, height=600)
15screen.bgcolor("#121212")
16screen.title("USA Flag")
17turtle.tracer(0) # Disable automatic updates for timing control
18
19t = turtle.Turtle()
20t.hideturtle()
21
22def draw_rectangle(x, y, w, h, color):
23 """Draws a solid colored rectangle using the def keyword."""
24 t.up()
25 t.goto(x, y)
26 t.setheading(0)
27 t.down()
28 t.color(color)
29 t.begin_fill()
30 for _ in range(2): # Standard loop for rectangular geometry
31 t.forward(w)
32 t.right(90)
33 t.forward(h)
34 t.right(90)
35 t.end_fill()
36
37def draw_star(x, y, size, color):
38 """Draws a perfectly symmetrical five-pointed star."""
39 t.up()
40 t.goto(x, y)
41 t.setheading(0)
42 t.forward(size / 2)
43 t.left(162)
44 t.down()
45 t.color(color)
46 t.begin_fill()
47 for _ in range(5):
48 t.forward(size)
49 t.left(72)
50 t.forward(size)
51 t.right(144)
52 t.end_fill()
53
54# --- THE 20-SECOND DRAWING SEQUENCE ---
55
56# 1. THE 13 STRIPES (~7.8 Seconds)
57# Each stripe appears every 0.6 seconds using a loop
58for i in range(13):
59 color = "#B22234" if i % 2 == 0 else "#FFFFFF"
60 draw_rectangle(-380, 200 - (i * STRIPE_H), FLY, STRIPE_H, color)
61 screen.update()
62 time.sleep(0.6) # Controls the flow of the animation
63
64# 2. THE BLUE CANTON (1.0 Second)
65draw_rectangle(-380, 200, CANTON_W, CANTON_H, "#3C3B6E")
66screen.update()
67time.sleep(1.0)
68
69# 3. THE 50 STARS (~11.7 Seconds)
70# Rows appear one by one to simulate a methodical build
71x_start = -380 + (CANTON_W / 12)
72y_start = 200 - (CANTON_H / 10)
73x_gap = CANTON_W / 6
74y_gap = CANTON_H / 10
75
76for row in range(9): # Handles the 9 rows of stars [cite: 33]
77 if row % 2 == 0:
78 for col in range(6):
79 draw_star(x_start + (col * x_gap), y_start - (row * y_gap), STAR_SIZE, "white")
80 else:
81 for col in range(5):
82 draw_star(x_start + (col * x_gap) + (x_gap / 2), y_start - (row * y_gap), STAR_SIZE, "white")
83
84 screen.update()
85 time.sleep(1.3) # Pause after each row to reach the 20-second goal
86
87# --- Final Reveal ---
88t.up()
89t.goto(0, -250)
90t.color("white")
91t.write("THE UNITED STATES of AMERICA", align="center", font=("Arial", 22, "bold"))
92t.up()
93t.goto(0, -270)
94t.color("white")
95t.write("pythonking.io", align="center", font=("Arial", 12, "bold"))
96screen.update()
97
98turtle.done()Ready to Level Up?
Stop guessing what to learn next. Get the structured path that separates senior engineers from everyone else.
Grab Your Free Roadmap