Prologue:
Welcome back! So far, all of our Python programs have just been text. Today we’re getting visual. We’re going to draw pictures with code using Python’s turtle.
The turtle is a little arrow that walks around the screen and draws a line wherever it goes. If you ever used the Pen blocks in Scratch, this will feel super familiar.
IMPORTANT NOTE
This one works best in IDLE from Part 4. If you’ve been using an online editor, it may not be able to show the turtle’s drawing window.
Let’s begin!
Chapter 1: Draw a square!
Create a new file in IDLE and save it as turtle_square.py. Then type this in:
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.right(90)
turtle.done()
Press F5. A new window should pop up, and you’ll watch the turtle draw a square!
Here’s what each line does:
import turtleloads the turtle toolbox, just likeimport randomdid.t = turtle.Turtle()creates your turtle and names itt.t.forward(100)moves the turtle forward 100 steps. That’s themove (100) stepsblock!t.right(90)turns the turtle right 90 degrees. That’s theturn right (90) degreesblock.- The
forloop repeats those two lines 4 times, once for each side of the square. turtle.done()keeps the window open so you can admire your work.
Chapter 2: Draw a star!
Squares are cool, but let’s make something fancier. Make a new file called turtle_star.py:
import turtle
t = turtle.Turtle()
t.color("blue")
t.pensize(3)
for i in range(5):
t.forward(150)
t.right(144)
turtle.done()
Run it and you should see a blue star!
Two new lines here:
t.color("blue")changes the pen color. Try"red","green", or"purple"too.t.pensize(3)makes the line thicker.
So why 144? A star has 5 points, and the turtle has to turn a sharp 144 degrees at each point to make the star shape. If you change it to 72, you’ll get a pentagon instead. Try it and see!
Chapter 3: Future Steps
Awesome work! You just made art with code. In Part 9, we’ll learn about functions, which let you make your own custom commands, just like “My Blocks” in Scratch.
CHALLENGE
Draw a triangle! Hint: a triangle has 3 sides, and the turtle needs to turn 120 degrees at each corner. Bonus: can you draw a hexagon (6 sides)?
If you get stuck or have any questions, feel free to contact me! And leave a comment telling me what shapes you drew!
