Python Turtle Graphics

With turtle graphics you can make drawings in a window, using a special set of commands.  Your page should start with the line:

from turtle import *

The * means “everything”.   You’re importing all the turtle functions into your code, so you can use them to draw.

The idea is that there is a turtle on the screen that you can give commands.  This little program draws a triangle.

from turtle import *
fd(100)
lt(120)
fd(100)
lt(120)
fd(100)
lt(120)

fd means “go forward”, and the number is the distance.
lt means “left turn”, and the number is the angle in degrees.

Here are some more commands:

rt(100) -> Right Turn

circle(50)

pd() -> Pen Down

pu() -> Pen Up

color("red")

pensize(5)

There are lots more!  You can learn more about Python Turtle Graphics here.

Loops

Loops in python are a way to do something over and over.  Try the following code in your turtle program:

for i in range(4):
    fd(100)
    lt(90)

You should see a square.

Try making a hexagon (6 sides). How big should the angle in the lt be?

If you use an angle that doesn’t go evenly into 360, you can make some crazy patterns.  Try this:

for i in range(200):
    fd(100)
    lt(92)

Make your own pattern!

Filling

You can fill in parts of your drawing with the two commands begin_fill() and end_fill().  Try the following:

color("red", "blue")
penwidth(5)
begin_fill()
for i in range(4):
    fd(100)
    lt(90)
end_fill()

What happens when you give the turtle 2 colors like this?  Which one is the fill color?

Try using begin_fill() and end_fill() with a fancier drawing.  See what you can make!

Colors