A Code Walkthrough for Young Coders
Ages 9–12 • Reading code, not just running it • About 20 minutes
Python has a fun module called turtle. It gives you a tiny turtle that holds a pen. When you tell the turtle to walk, it drags the pen behind it and draws on the screen. This page walks through a real Python program that uses the turtle to draw hexagons and squares, and explains what every part of the code does.
When you run the program, the turtle starts in the middle of the screen and walks around drawing shapes. Here is the finished picture:
Look closely — you can see big hexagons stacked on top of each other (those are drawn three times, so they look extra dark), then medium and small hexagons branching off, and finally two squares. Every line was made by the turtle walking forward and turning.
The turtle only knows two basic moves:
That’s it! Every shape in the picture is just walk — turn — walk — turn — walk … over and over.
To draw any closed shape, you can use this rule:
Total turning to come back to the start = 360°. So if a shape has N equal sides, each turn is 360 ÷ N degrees.
import turtle t = turtle.Turtle()
import turtle tells Python: “I want to use the turtle module.” The next line creates a turtle and gives it a short nickname, t, so we don’t have to type the full word every time.
def draw_hex(side_length): t.pendown() for _ in range(6): t.forward(side_length) t.right(60) t.penup()
A function is a recipe with a name. This recipe is called draw_hex, and it draws a hexagon. The word side_length is a parameter — a blank you fill in when you use the recipe. draw_hex(250) means “draw a hexagon with sides 250 steps long.”
Inside the recipe:
def draw_square(side_length): t.pendown() for _ in range(4): t.forward(side_length) t.right(90) t.penup()
Same idea as the hexagon, but it loops 4 times and turns 90° at each corner. Notice how similar these two functions look — the only differences are the number of sides and the turning angle.
for _ in range(3): draw_hex(250) t.right(90) t.forward(60) draw_hex(100) t.right(90) t.forward(40) draw_hex(120)
This loop runs 3 times. Each time, the turtle:
That’s why you see 3 sets of 3 hexagons in the picture. (The big hexagons happen to land on top of each other!)
t.forward(300) t.right(60) draw_square(270) t.left(30) t.forward(110) t.right(80) draw_square(135) turtle.done()
After all the hexagons, the turtle moves to a new spot, draws a big square, moves again, and draws a smaller square. Finally, turtle.done() tells the program: “We’re finished — please keep the picture window open so we can look at our drawing.”
To run it, save the file and type python3 draw_shapes.py in a terminal. (Make sure Python 3 is installed.)
Tip: don’t name your file turtle.py — Python already has a built-in module with that name, and it will get confused and try to import your file instead of its own.