Byte by Byte › Book 6: Python, Data and How Computers Work › Chapter 9: Drawing with Python Turtle
Chapter 9: Drawing with Python Turtle
You will learn: how to use Python's turtle module to draw, how to move and turn the turtle, how to use loops to draw regular polygons using exterior angles, how to use the pen, colours, fills and coordinates, and how to combine loops and maths to create patterns such as stars, spirals and rangoli designs.
🌟 The Adventure
The Glow Wall rose above Pearlhaven like a giant black cliff. Long ago, the Old Makers had covered it with a special shimmering coral. When the Engine sent light along it, glowing lines appeared, like drawing with a torch on a dark night.
"The Engine once drew on it with something called the Light Turtle," said Octavia. "A tiny point of light that moved where it was told, leaving a glowing trail behind it."
Kachui's spectacles nearly fell off his nose. "A turtle that draws?"
"A turtle that draws, carrying a pen in its tail," said Octavia. "It goes forward, it turns, it lifts the pen, it puts it down. But it only understands Python, and I never learned how to make it draw anything more than a wobbly line."
The Festival of Tides was nine days away. Thousands of fish would gather in the square. They had not seen a single picture on the Glow Wall for thirty years. Memoon looked up at the vast dark surface and felt very small.
Then she remembered her first ever program in Scratch, years ago, when she had made a sprite walk in a square. "Forward, turn, forward, turn," she said slowly. "Kachui. I think I've done this before."
💡 Learn With Memoon
The turtle module. Python comes with a module called turtle . It opens a drawing window with a small arrow or turtle shape in the middle. You give the turtle commands, and as it moves, it draws a line with its pen. It is one of the oldest ideas in teaching programming: an educational robot turtle drew on paper in the 1960s and 1970s, in a language called Logo, and Python's turtle copies it.
Your first drawing.
import turtle
t = turtle.Turtle() # make a turtle called t
t.shape("turtle") # make it look like a turtle
t.forward(100) # move forward 100 steps, drawing a line
t.left(90) # turn left 90 degrees
t.forward(100)
turtle.done() # keep the window open
Save this as first_drawing.py and press F5. A window opens and the turtle draws two sides of a square.
Important: never save your own file as turtle.py . If you do, Python will import your file instead of the real turtle module, and nothing will work.
Turtle commands.
| Command | What it does |
|---|---|
t.forward(100) | Move forward 100 steps (pixels) |
t.backward(50) | Move backward 50 steps |
t.left(90) | Turn left (anticlockwise) by 90 degrees |
t.right(45) | Turn right (clockwise) by 45 degrees |
t.penup() | Lift the pen: move without drawing |
t.pendown() | Put the pen down: draw again |
t.goto(x, y) | Move straight to the point (x, y) |
t.setheading(90) | Point in a direction: 0 is right (east), 90 up, 180 left, 270 down |
t.circle(50) | Draw a circle with radius 50 |
t.color("red") | Set the pen colour |
t.pensize(5) | Set the line thickness |
t.fillcolor("yellow") | Set the colour used for filling shapes |
t.begin_fill() and Fill in the shape drawn between them
t.end_fill()
t.speed(0) | Set the speed: 1 is slow, 10 is fast, 0 is fastest |
t.hideturtle() | Hide the turtle shape |
The t. before each command means "tell the turtle called t to do this", just like random. meant "use the random module". You can make several turtles with different names and control each one separately.
The screen. The drawing window is the screen. You can control it too:
screen = turtle.Screen()
screen.bgcolor("black") # background colour
screen.title("Glow Wall") # window title
Coordinates. The turtle window uses x and y coordinates exactly like the Scratch stage: (0,
- is the centre, x increases to the right and y increases upwards. Negative x is left of centre;
negative y is below it. The turtle starts at (0, 0) facing right.
Loops make shapes. Drawing a square by repeating forward, left four times is the perfect job for a for loop:
for side in range(4):
t.forward(100)
t.left(90)
The polygon rule. Why 90 degrees? When the turtle walks all the way round any closed shape and ends up facing the way it started, it has turned through exactly 360 degrees in total. A square has 4 corners, so each turn is 360 ÷ 4 = 90 degrees. That turn is the shape's exterior angle. For any regular polygon (all sides and angles equal) with n sides:
exterior angle = 360 ÷ n
| Shape | Sides | Turn (exterior angle) | Interior angle (180 − turn) |
|---|---|---|---|
| Equilateral triangle | 3 | 120° | 60° |
| Square | 4 | 90° | 90° |
| Regular pentagon | 5 | 72° | 108° |
| Regular hexagon | 6 | 60° | 120° |
| Regular octagon | 8 | 45° | 135° |
A common mistake is to turn by the interior angle. If you turn 60 degrees to draw a triangle, you get half a hexagon instead. The turtle turns by the exterior angle: the angle between the direction it was going and the direction it goes next.
Now you can write one program for every regular polygon:
import turtle
t = turtle.Turtle()
sides = int(input("How many sides? "))
length = int(input("How long is each side? "))
angle = 360 / sides
for side in range(sides):
t.forward(length)
t.left(angle)
turtle.done()
Type 100 sides of length 5, and the polygon looks just like a circle. That is how a computer draws a circle: as a polygon with very many very short sides.
Stars. A five-pointed star is drawn by turning 144 degrees at each point, five times. The turtle turns 5 × 144 = 720 degrees in total, which is two full turns: it goes round the centre twice.
t.color("gold")
t.fillcolor("yellow")
t.begin_fill()
for point in range(5):
t.forward(150)
t.right(144)
t.end_fill()
Colours. You can name colours, such as "red" , "orange" , "deep sky blue" or "gold" , or use the hex colour codes from Chapter 4, such as "#FF8000" for orange. For random colours, switch the screen to RGB numbers from 0 to 255:
import random screen.colormode(255) t.color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
Moving without drawing. To draw shapes in different places, lift the pen, move, and put it down again:
t.penup() t.goto(-150, 100) t.pendown() t.circle(40)
Forgetting penup() leaves a line across your picture from the old position to the new one. Every turtle artist has done this.
Patterns: loops plus a twist. Some of the most beautiful patterns come from repeating a shape while turning a little each time. This is how a rangoli or kolam pattern grows from a simple repeated motif:
import turtle
t = turtle.Turtle()
t.speed(0)
screen = turtle.Screen()
screen.bgcolor("black")
for petal in range(36):
if petal % 3 == 0:
t.color("magenta")
elif petal % 3 == 1:
t.color("gold")
else:
t.color("cyan")
t.circle(100)
t.left(10)
t.hideturtle() turtle.done()
36 circles, each turned 10 degrees from the last: 36 × 10 = 360, a complete flower. The % operator from Chapter 7 cycles through three colours: petals 0, 3, 6 and so on are magenta; 1, 4, 7 are gold; 2, 5, 8 are cyan. The pattern has rotational symmetry, a topic from your maths book.
Spirals. If the distance grows each time round the loop, you get a spiral:
for step in range(150):
t.forward(step * 2)
t.left(91)
With a turn of exactly 90 degrees you would get a square spiral. Turning 91 degrees makes each square slightly twisted, and the spiral seems to rotate. Change 91 to 121, 61 or 145 and see what happens.
💡 Memoon’s tip: Plan a turtle drawing on squared paper first. Mark (0, 0) in the middle, then write down the coordinates of every corner. Drawing becomes a list of goto() commands, and you will not get lost.

✍️ Try It Yourself
Activity 1: First shapes. Using a for loop each time, draw an equilateral triangle, a square, a pentagon and a hexagon, all with sides of 100. Use penup() and goto() so they do not overlap.
Activity 2: The polygon machine. Type the polygon program from this chapter. Try 3, 6, 10, 20 and 100 sides. At how many sides does it start to look like a circle? (You may need to make the side length smaller as the number of sides grows.)
Activity 3: A house. Draw a house: a filled square for the walls, a filled triangle for the roof (turn 120 degrees at each corner), a rectangle for the door and two small squares for windows. Plan the coordinates on squared paper first.
Activity 4: Starry sky. Make the background dark blue. Use a for loop that repeats 20 times. Each time, lift the pen, go to a random position with random.randint(-300, 300) and random.randint(-250, 250) , put the pen down, and draw a small filled yellow star.
Activity 5: Your own rangoli. Change the rangoli program: try squares or hexagons instead of circles, change the number of repeats and the turn (they must multiply to 360 for a complete pattern), and choose your own colours. Give your design a name.
Activity 6: Spiral explorer. Run the spiral program with different turn angles. Write down the angle and draw a quick sketch of what each produces. Which angles give five arms? Which give a smooth curve?
Unplugged: Be the turtle. Mark a starting point on the floor with chalk or tape and face a wall. A partner reads out turtle commands such as forward 4 (steps) and left 90 . Walk them out. Can you walk a perfect square? Now try a triangle. Did you remember to turn 120, not 60?
🎉 Memoon Solves It
They spent eight days practising. Kachui insisted on testing every program with a real turtle first: himself. He walked forward and turned on the sand while Memoon read out the commands, and when he walked half a hexagon instead of a triangle, they found the bug at once. (She had used the interior angle.)
Noodles discovered that if Memoon forgot penup() , he got long glowing lines across the wall to chase. He was disappointed when she stopped forgetting.
On the night of the Festival, the whole of Pearlhaven filled the square. Memoon ran her program. A tiny point of light appeared at the centre of the Glow Wall. It drew a golden circle, turned ten degrees, and drew another, and another, until a vast magenta, gold and cyan flower bloomed across the wall. Then came stars, hexagons, a spiral that seemed to twist forever, and finally, in glowing letters made from careful goto() lines, the word PEARLHAVEN.
The square erupted. Thousands of fish swirled in a cheering spiral of their own. Octavia wiped one eye with the tip of an arm.
Afterwards, the mayor of Pearlhaven, a stately old grouper, swam up to them. "Magnificent," he said. "But such a pity that only the fish could see it. For thirty years the rest of Memunic has forgotten we exist. I wish we could show everyone."
Memoon thought about the Light Bridges, carrying messages to every village. In Book 3 she had learned what a website was. She had never built one.
"Maybe we can," she said.
❓ Check Your Knowledge
- What must be at the top of every turtle program?
- What do
t.penup()andt.pendown()do? Why would you need them? - Write a
forloop that draws a square with sides of 80. - A turtle draws a regular polygon. What is the exterior angle for (a) 3 sides (b) 8 sides (c) 10 sides?
- A student wants to draw an equilateral triangle and turns 60 degrees each time. What will they get, and why?
- In turtle coordinates, where is the point (0, 0)? Which way does the y value increase?
- Which direction is the turtle facing after
t.setheading(180)? - What do
t.begin_fill()andt.end_fill()do? - Why must you never call your own program
turtle.py? - In the rangoli program, 36 circles are drawn with a turn of 10 degrees. If you wanted 24 circles in a complete pattern, what turn would you need?
- Predict the shape drawn by this code:
for i in range(6):
t.forward(100)
t.right(60)
- Challenge: Write a program that asks the user for a number of points and draws a star with that many points. (Hint: for an odd number of points n, try turning
180 - 180 / ndegrees each time. Test it with 5, 7 and 9.)
📚 Word Bank
- Turtle graphics: drawing by giving movement commands to an on-screen turtle carrying a pen.
- turtle module: the Python module for turtle graphics.
- Screen: the turtle drawing window.
- Heading: the direction the turtle is facing, in degrees.
- Regular polygon: a shape whose sides are all equal and whose angles are all equal.
- Exterior angle: the angle the turtle turns at each corner; for a regular polygon it is 360 ÷ number of sides.
- Interior angle: the angle inside a shape at a corner.
- Fill: colouring in the inside of a closed shape.
- Rotational symmetry: a pattern that looks the same after being turned by a certain angle.
- Rangoli (kolam): a traditional Indian pattern made from repeated, symmetrical shapes.
Keep learning with Byte by Byte
Explore Book 6: Python, Data and How Computers Work. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment