Python Turtle Basics

Introduction

Python’s turtle graphics pay homage to Seymour Papert’s Turtle Robot and Logo. He and two other colleagues

developed Logo in 1967 to use to teach students programming concepts. Papert added turtle graphics to Logo in

the late 1960s to support his turtle robot, which was a simple robot that could carry out drawing functions using

a retractable pen. Logo’s turtle graphics worked on screen and used either a triangle or turtle shape as the

‘turtle’. Unlike cartesian coordinates, turtle graphics was primarily vector-based, meaning they used relative

direction and distance from the starting point. In this lesson, we will explore vector-based commands, as well as

coordinate-based commands.

Importing Libraries

Most programming languages use libraries. Think about how you use the library at school or the public library,

you go there to get books you are interested in because there is no way you could hold that many books in your

house or your room, and some books, you may only need for one project and then you don’t have use for it

afterward. This is like a library in programming. Libraries are collections of prewritten code that programmers

can use for specific tasks. In this case, Python Turtle. It is not built directly into the core Python code but is easily

accessible. Once a library has been imported into your program, you can access all its features. With Python,

importing a library can be done in a few different ways. Sometimes, you do not need the entire library and don’t

want to slow the program by importing the entire library, other times you do want the entire library. To keep

things simple and meet our needs, we will import the entire Turtle library. Use the code shown below at the

beginning of your program. Do not include the greater than symbols in any of these examples. They are

simulating the Python Shell environment and are used here to differentiate between code and regular text.


>>> Import turtle

Setting Up the Screen

Once you have imported the Turtle library, you can access its features. Initially, you will want to set up the

screen. While there are many options for this, we will explore the code that we will use. You can easily find

Python Turtle documentation online that lists everything the library is capable of. Below are commands for

making a screen, sizing the screen, adding a title to the screen, and setting the background color. As you use

these commands, bear in mind that Python is case-sensitive. If a code is shown with all lowercase characters,

adding an uppercase character to your code will result in an error. The same goes for adding all lowercase

characters when a command should be capitalized.


Making the Screen

When making the screen, there is a specific syntax that must be used, otherwise, you will get an error and the

screen will not work. The syntax is shown below. The first word, ‘screen’ could be named anything. The rest of

the code must be entered exactly as shown.


>>> screen = turtle.Screen()


Sizing the Screen

When setting the size of your screen, you must start with the name you gave the screen. In the example above,

the screen was named “screen”. Often, you see programmers use “wn” as an abbreviation for window. The

syntax is as shown below. Remember, ‘screen’ would be whatever you named your screen. The values are the

width and height of the screen in pixels.


>>> screen.setup(400,400)


Naming the Screen

When you run your program, you can add a name to the top of the screen. You see this on all sorts of programs.

The syntax for this would be exactly as shown. The only thing that would change is the actual title. It must be

inside quotation marks to work because text is a string, which we will examine further later in the course.


>>> turtle.title(“My First Program”)


Background Color

Once you have made a screen and sized it, you can add a background color to the entire screen if you wish. The

default color is white. There are various ways to add colors but again, we will look at a simple method that adds

color by name. There are reference files that can be easily accessed online that show colors and color names

that Python recognizes. The syntax can be seen below. “screen” would be changed if you named your screen

something different and the color would be whatever color you wish, it must be inside quotation marks because

Python expects a string. Strings are always inside quotation marks – either single (‘) or double (“).


>>> screen.bgcolor(“yellow”)

Making a Turtle

When you create your turtle, you get to name it! You will type this name many times, so a short name is ideal. In

this example, the turtle will be named Ben. This is an arbitrary choice. This name will be used in the remaining

examples in this document but remember that you would add the name you used in place of “Ben”. To make

your turtle, use the syntax shown below. To point out, you can have multiple turtles, however, we will stick to

one in these examples.


>>> ben = turtle.Turtle()

Adjusting the Turtle's SHape

While this does not impact the function of the turtle, it is fun to adjust the shape of the turtle. It can be set to be

an actual turtle shape, a dot, a triangle, as well as a few other shapes. One time that this can impact your code is

using the stamp command. We will not be getting into that here, but it is a command that exists in the Turtle

library. The options are as follows: square, arrow, circle, turtle, triangle, and classic. These options could be used

in place of “turtle” in the example below. Remember to use the name of your turtle.


>>> ben.shape(“turtle”)

Moving the Turtle

There are a few different ways to move the turtle in Python. You can use a vector-based movement system,

which includes a direction and magnitude, or a raster-based system that uses coordinates to place the turtle. We

will explore both. There can be benefits and drawbacks to each method.


Vector-Based Movement

There are basic commands that are commonly used when moving the turtle as a vector. These include forward,

backward, left, and right. They must be accompanied by a value (magnitude). When using forward and

backward, the number represents the distance you want to move the turtle. When using left and right, the

number represents the angle at which you want to turn the turtle. Right refers to a clockwise rotation and left to

a counterclockwise rotation. See the example below.


>>> ben.forward(100)

>>> ben.backward(100)

>>> ben.right(90)

>>> ben.left(90)


One drawback to this method of movement can be seen when trying to draw circles. When the circle command

is used, the turtle always draws the circle to its left. If you have the turtle where you want the bottom of the

circle to be and it is facing north, the circle will not be placed as you desire. There is a simple solution to this

issue, though. The Turtle library includes a “setheading” command that will set the turtle to face east, west,

north, or south, relative to the screen. The code can be seen below. East (right) = 0, north (up) = 90,

west (left) = 180, and south (down) = 270.


>>> ben.setheading(90)


Raster-Based Movement

Raster-based movement involves X and Y coordinates, where the center of your screen is the origin or (0,0). The

outer extent of your screen would be based on what size you set the window to. This method can be great for

drawing squares and rectangles or for placing circles because the heading of the turtle never changes. A

drawback would be evident with more complex shapes. You would have to map out all the coordinates needed

to make the shape. In instances like these, vector commands can be much easier. The example below shows the

syntax for this type of movement. The coordinates are (X, Y).


>>> ben.goto(20,25)


Speed of Movement

The speed of the turtle can be set, ranging from very slow to fast enough that you do not see the turtle at all.

The syntax is shown below. The value in the script ranges from 1 to 0, where 1 is the slowest, 9 is very fast, and 0

is the fastest.


>>> ben.speed(7)

Lines, Fills, and Shapes


Line Commands

When the turtle moves across the screen, it can draw lines. The library includes a pen tool, which can be up (not

drawing) or down (drawing). The thickness and color of the pen can also be adjusted. Color works in the same

manner as mentioned in the section about background color. There are multiple methods to add color, but the

example here will call a color by name, which is a string and must be inside quotation marks. The pen size must

be a positive integer (whole number) greater than zero. The smaller the number, the thinner the line, larger

numbers result in thicker lines. The pen color and size will remain the same unless changed, so there is no need

to add these commands more than once unless you want to change the size or color. See the syntax below.


>>> ben.penup()

>>> ben.pendown()

>>> ben.pencolor(“red”)

>>> ben.pensize(3)


Fill Commands

Fill commands will fill in a shape with a specified color. They look best when the turtle starts and ends at the

same location. If the turtle ends somewhere other than the starting point, the fill will encompass the area the

turtle has been in and end with a straight line between the starting and ending locations. Like line color, fill color

will remain the same once set unless a script is added to change it elsewhere in the code. Furthermore, the fill

will not occur without using begin_fill before the shape is drawn and end_fill after the shape has been drawn.

The color must be set before the begin_fill command. See examples of the syntax below.


>>> ben.fillcolor(“red”)

>>> ben.begin_fill()

>>> ben.end_fill()


Shape Commands

Aside from using lines, there are a few shapes that can be drawn by name. Other shapes can be drawn line-by-

line or by making a custom function. A function is a set of steps that you define and can call on as needed. That

is one for another time, as it is beyond the basics.


Shapes that can be drawn by name are ‘dot’ and ‘circle’. Dots are just that, dots. Circles can be used for whole

circles or arcs. See the syntax for each below. With the dot, the value is the diameter of the dot, and the color is

optional. With circles, the value is the radius. If a second value is added, it is the angle that is drawn.


>>> ben.dot(100, ”orange”)

>>> ben.circle(150)

>>> ben.circle(150, 180)

Visibility

When you create a drawing, you may not want to see the turtle any longer or maybe you have the turtle hidden

and you want to see it to see where a bug is occurring in your code. The library includes show and hide

commands. See the examples of the syntax below.


>>> ben.hideturtle()

>>> ben.showturtle()

Writing

The Turtle library includes commands to add text to a program. The syntax for this includes the actual text,

known as the argument, whether the turtle moves with the text (True or False), alignment of the text (left,

center, right), and the font, including the font name, size, and font type (normal, italic, bold, underline). The

program can access fonts that are available on the computer running the program. As you have seen

throughout, the syntax must be correct, or you will receive an error message. Items in the examples below must

have the same syntax, including case and quotation marks. As you can see, the only requirement is the

argument. The other fields are optional.

If you find the need to use single or double quotes in a string enclosed in the same type, you must use what is

called an escape character. In Python, this is a backslash (\). It is placed in front of the quotation mark(s) in the

text and prevents errors by telling Python that it is not ending the string or beginning a new one and does not

appear in the output. The first example below shows the syntax for this.


>>> ben.write(“Jessica said, \“Hello, Friends\””)

>>> ben.write(“Hey!”, move=False, font=(“Arial”, 12, “normal”))

Loops

Loops are a way to simplify code. If you want to draw a dodecahedron, it will be far simpler to use a loop than it

would be to write the same commands 12 times in a row. There are two types of loops, for loops and while

loops. Each has its advantages and disadvantages. Which to choose depends on what you are trying to achieve.


For Loops

For loops can repeat commands based on items in a list or using the desired range. Examples of the syntax for

both will be shown below. There are distinct differences between the two types, though. First, let us look at a

loop that uses a range. Look at the code below. What do you think will happen?


>>> for i in range(4):

. . . ben.forward(100)

. . . ben.right(90)


If you guessed that the code would repeat four times, you are correct. You also may have figured out that this

code would result in a square. The letter ‘i’ is not the only letter that can be used here. Certain letters have carried on from earlier programming languages. The letters ‘i’, ‘j’, and ‘k’ are often used. The range is the

number of times the code is to be repeated.


Another thing you probably noticed is the second and third lines are indented. This is necessary or you will get

an error message. The first line must end with a colon (:) and lines that are in the loop must each be indented.

Some IDEs require two spaces, while others require four. The easiest way is to just use the tab key for the

indented code.


The ‘i’ in the code is worth looking at closer. It acts as a counter. It always starts at zero and counts from there. It

is possible to set the starting point and the value it increases with each step, but that is not worth getting into in

the basics.


Now, let us look at a ‘for loop’ that uses a list. To start, a list in Python is information contained within

parentheses, with each list item being separated with a comma. A list is attached to a variable. In the example

below, the list name will be “colors” and will contain different colors. Look at the code and speculate what the

result will be.


>>> colors = (“red”, “blue”, “green”, “yellow”)

>>> for hue in colors:

. . . ben.pencolor(hue)

. . . ben.forward(100)

. . . ben.right(90)


If you guessed that the code would result in another square, you are correct. If you figured out that each line

would be a different color, you are also correct. In this example, the color value in ‘pencolor’ is not set to a

specific color, nor is the value in quotations. This is because ‘hue’ is a variable and corresponds to the colors in

the list. If another color were added to the list, for the shape to not overlap itself, the angle that the turtle turns

by would need to be adjusted. In this case, adding one more value would make five colors, so we would want to

create a pentagon, which uses an angle of 72 degrees (360 ÷ 5).


A list can also contain numbers. What do you think would happen if the following code were run?


>>> lengths = (200, 100, 200, 100)

>>> for distance in lengths:

. . . ben.forward(distance)

. . . ben.right(90)


If you guessed that the program would draw a rectangle, you are correct! Notice the lengths in the list are not in

quotes. This is because they are numbers and not strings. A number can be a string, but that limits it to being

viewed as text and not a number that can be used in mathematical operations.


While Loops

While loops are like for loops and can be used in the same way but have some unique differences. A while loop

is used to repeat a task until a condition has been satisfied. The example below would make increasingly large

circles until the condition (n = 50) has been met. In this example, ‘n’ has been initialized or initially set to 10.


>>> n=10

>>> while n <= 50:

. . . ben.circle(n)

. . . n = n+10


In this code, the line ‘n = n + 10’ increments or adds 10 to the value of ‘n’ each time the code is looped.

Let us look at another example that takes this a step further. This example contains a few things that have not

been explored yet. A description of what is taking place will be included below and the example goes beyond the

basics, but it is worth showing. Examine the code and see what you think will happen.


>>> color = ('yellow', 'orange', 'red', 'darkred', 'blue')

>>> hue = 0

>>> n = 50

>>> while n >=10:

. . . ben.fillcolor(color[hue])

. . . ben.begin_fill()

. . . ben.circle(n)

. . . ben.end_fill()

. . . n = n-10

. . . hue = hue+1

>>> ben.hideturtle()


Do you think you figured it out? This code created a series of five circles. Each one is filled with one of the colors

from the list, starting with the first value (yellow(0)) and continuing through the fifth (blue(4)). The reason for ‘n’

decrementing is to prevent smaller circles from being covered by larger ones. The ‘hue’ increments so it will

start at the left of the list and continue to the right. This could be changed to reverse the color pattern if ‘hue’

were initialized as four.

Comments

Comments are a crucial part of programming. Python will ignore comments in program code. They are used to

explain what is being done in each section of code. They can be used to leave yourself messages as you work on

a program, for others to quickly find different sections of code, to explain what is happening, or to temporarily

ignore certain lines of code when debugging or during initial testing – which should happen throughout the

coding process. It is poor judgment to write an entire program before testing it. Each section should be tested as

it is written. This will greatly decrease the number of bugs in the final product.


There are two types of comments in Python. One is a single-line comment and the other is a multiline comment.

Typically, Python programmers prefer single-line comments and will use them on multiple lines if needed, but

multiline comments do exist. The syntax for both is below.


>>> # This is a single-line comment

>>> # The octothorpe symbol identifies this as a comment

>>> “““This is a multiline comment.

. . . It uses three consecutive quotation marks to

. . . begin and end the comment.”””

>>> ‘‘‘This is also a multiline

. . . comment. Double and single quotes are

. . . interchangeable in Python.’’’

Try it Out

Open a Python editor or IDE (Integrated Development Environment) that you have available to you. At school,

your teacher may have you use the Mu or IDLE IDEs or online editors like Codehs.com, Replit.com, Trinket.io, or

Pythonandturtle.com. At home, trinket.io or pythonandturtle.com/turtle may be the most accessible. Trinket is

more powerful and can be saved.


Try importing the turtle library, making a screen, and drawing something using the commands within this

document. These commands will be used in class to get started with Python. Later, these concepts will be built

upon. Happy coding!


* If you choose to use Trinket editor, naming the window is not supported and must be left out of your code.

** If you use Python and Turtle editor, there are several things that are not supported and must be left out. The

following steps should be followed to ensure the code functions as intended:

1. Do not import the turtle library

2. Do not include any screen setup code

3. The maximum screen size is 250 x 250

4. The last line of code must be - turtle.done()