First Steps: Drawing with Turtle
Turtle is a simple way of programming. Schools use it to teach children how to make their first simple programs. You tell a turtle to move and to turn, and it draws a line wherever it goes. Every instruction shows on the screen as it happens, which is why so many people write their first program this way.
Who this is for
Anyone writing a first program: a child with a parent or a teacher, a class in its first term of Python, or an adult starting out. You need to be able to type, and nothing else.
What you need
- Circuitry in a web browser, in the desktop app, or on an iPad or a phone.
- Nothing to install.
turtleis ready on every device.
Your first program
- From the new-document menu, choose Code, then Python. Give the file a name, such as
square.py. - The file opens with the code on the left and an empty preview on the right that says Run to draw here.
- Type this in, or paste it:
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.color("green")
t.pensize(3)
for side in range(4):
t.forward(150)
t.left(90)
turtle.done()
- Press Run in the footer.
What you should see
The preview turns white, and a small green turtle starts in the middle. It walks to the right, turns left, and does that four times, drawing one side of a square each time. It ends where it began.
Read the program again with the picture beside it:
t.forward(150)walks 150 steps and draws a line.t.left(90)turns a quarter of the way round.for side in range(4):does the two lines under it four times.
Three things to try
Change one thing, press Run, and see what is different.
- A triangle. Change
range(4)torange(3)andt.left(90)tot.left(120). Three sides, and a bigger turn. - A different pen. Change
"green"to"red"or"blue", andt.pensize(3)tot.pensize(10). - A star. Change
range(4)torange(5)andt.left(90)tot.right(144).
If you type a name wrongly, the message under the preview gives the nearest one: t.fowrard(10) says Did you mean forward?
A second program: a spiral of colours
import turtle
colours = ["red", "orange", "yellow", "green", "blue"]
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.speed(10)
t.pensize(2)
for step in range(150):
t.pencolor(colours[step % 5])
t.forward(step * 1.5)
t.left(59)
t.hideturtle()
turtle.done()
t.speed(10) makes the turtle walk fast, so you can still watch each line being drawn; t.speed(0) would draw each line at once instead of walking it. step % 5 goes 0, 1, 2, 3, 4 and round again, which picks the next colour each time. Change the 59 to 91 or 121 and the whole shape changes.
Where to go next
- Turtle: every function, filling shapes, keys and clicks, games, and what is different from Python's turtle on a computer.
- Graphics and games with Pyctures: the next path, for pictures, sprites and faster games.
- How the editor helps you learn: Run, the views and the output.
- Learning to Code: the other paths.