There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform complex mathematical calculations. In this chapter we will introduce a module that allows us to create a data object called a turtle that can be used to draw pictures.
Turtle graphics, as it is known, is based on a very simple metaphor. Imagine that you have a turtle that understands English. You can tell your turtle to do simple commands such as go forward and turn right. As the turtle moves around, if its tail is down touching the ground, it will draw a line (leave a trail behind) as it moves. If you tell your turtle to lift up its tail it can still move around but will not leave a trail. As you will see, you can make some pretty amazing drawings with this simple capability.
Note
The turtles are fun, but the real purpose of the chapter is to teach ourselves a little more Python and to develop our theme of computational thinking, or thinking like a computer scientist. Most of the Python covered here will be explored in more depth later.
Let’s try a couple of lines of Python code to create a new turtle and start drawing a simple figure like a rectangle. We’ll call the variable that refers to our first turtle alex, but you can choose another name if you follow the naming rules from the previous chapter.
The program as shown will only draw the first two sides of the rectangle. After line 3 you will have a straight line going from the center of the canvas below towards the right. After line 6, you will have a canvas with a turtle and a half drawn rectangle. Press the run button to try it and see.
(ch03_1)
Here are a couple of things you’ll need to understand about this program.
The first line tells Python to load a module named turtle. That module brings us two new types that we can use: the Turtle type, and the Screen type. The dot notation turtle.Turtle means “The Turtle type that is defined within the turtle module”. (Remember that Python is case sensitive, so the module name, with a lowercase t, is different from the type Turtle.)
We then create and open what the turtle module calls a screen (we would prefer to call it a window, or in the case of this web version of Python simply a canvas), which we assign to variable wn. Every window contains a canvas, which is the area inside the window on which we can draw.
In line 3 we create a turtle. The variable alex is made to refer to this turtle. These first three lines set us up so that we are ready to do some drawing.
In lines 4-6, we instruct the object alex to move and to turn. We do this by invoking or activating, alex’s methods — these are the instructions that all turtles know how to respond to.
Complete the rectangle ...
An object can have various methods — things it can do — and it can also have attributes — (sometimes called properties). For example, each turtle has a color attribute. The method invocation alex.color(“red”) will make alex red, and the line that it draws will be red too.
The color of the turtle, the width of its pen(tail), the position of the turtle within the window, which way it is facing, and so on are all part of its current state. Similarly, the window object has a background color. These are all part of the state of the window object.
Quite a number of methods exist that allow us to modify the turtle and the window objects. We’ll just show a couple. We’ve only commented those lines that are different from the previous example. Note also that we’ve now called our turtle object tess.
(ch03_2)
The last line plays a very important role. The wn variable refers to the window shown above. When we invoke its exitonclick method, it pauses the execution of the program, and waits for the user to click the mouse somewhere in the window. When this click event occurs, the response is to close the turtle window and exit (stop execution of) the Python program.
Each time we run this program, a new drawing window pops up, and will remain on the screen until we click on it.
Extend this program ...
Just like we can have many different integers in a program, we can have many turtles. Each of them is an independent object and we call each one an instance of the Turtle type (class). Each instance has its own attributes and methods — so alex might draw with a thin black pen and be at some position, while tess might be going in her own direction with a fat pink pen. So here is what happens when alex completes a square and tess completes her triangle:
(ch03_3)
Here are some How to think like a computer scientist observations:
When we drew the square, it was quite tedious. We had to move then turn, move then turn, etc. etc. four times. If we were drawing a hexagon, or an octogon, or a polygon with 42 sides, it would have been a nightmare to duplicate all that code.
A basic building block of all programs is to be able to repeat some code over and over again. In computer science, we refer to this repetitive idea as iteration. In this chapter, we will explore some mechanisms for basic iteration.
In Python, the for statement allows us to write programs that implement iteration. As a simple example, let’s say we have some friends, and we’d like to send them each an email inviting them to our party. We don’t quite know how to send email yet, so for the moment we’ll just print a message for each friend.
(ch03_4)
Take a look at the output produced when you press the run button. There is one line printed for each friend. Here’s how it works:
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program. When humans execute programs, they often use their finger to point to each statement in turn. So you could think of control flow as “Python’s moving finger”.
Control flow until now has been strictly top to bottom, one statement at a time. We call this type of control sequential. Sequential flow of control is always assumed to be the default behavior for a computer program. The for statement changes this.
Flow of control is often easy to visualize and understand if we draw a flowchart. This flowchart shows the exact steps and logic of how the for statement executes.
A codelens demonstration is a good way to help you visualize exactly how the flow of control works with the for loop. Try stepping forward and backward through the program by pressing the buttons. You can see the value of friendName change as the loop iterates thru the list of friends.
|
Source Code
Step ? of ?
|
|
Program output:
|
To draw a square we’d like to do the same thing four times — move the turtle forward some distance and turn 90 degrees. We previously used 8 lines of Python code to have alex draw the four sides of a square. This next program does exactly the same thing but, with the help of the for statement, uses just three lines (not including the setup code). Remember that the for statement will repeat the forward and left four times, one time for each value in the list.
(ch03_for1)
While “saving some lines of code” might be convenient, it is not the big deal here. What is much more important is that we’ve found a “repeating pattern” of statements, and we reorganized our program to repeat the pattern. Finding the chunks and somehow getting our programs arranged around those chunks is a vital skill when learning How to think like a computer scientist.
The values [0,1,2,3] were provided to make the loop body execute 4 times. We could have used any four values. For example, consider the following program.
(ch03_forcolor)
Since there are still four items in the list, the iteration will still occur four times. aColor will take on each color in the list. We can even take this one step further and use the value of aColor as part of the computation.
(colorlist)
In this case, the value of aColor is used to change the color attribute of alex. Each iteration causes aColor to change to the next value in the list.
In our simple example from the last section (shown again below), we used a list of four integers to cause the iteration to happen four times. We said that we could have used any four values. In fact, we even used four colors.
import turtle #set up alex
wn = turtle.Screen()
alex = turtle.Turtle()
for i in [0,1,2,3]: #repeat four times
alex.forward(50)
alex.left(90)
wn.exitonclick()
It turns out that generating lists with a specific number of integers is a very common thing to do, especially when you want to write simple for loop controlled iteration. Even though you can use any four items, or any four integers for that matter, the conventional thing to do is to use a list of integers starting with 0. In fact, these lists are so popular that Python gives us special built-in range objects that can deliver a sequence of values to the for loop. They start at 0, and in the cases shown below do not include the 4 or the 10.
for i in range(4): # Executes the body with i = 0, then 1, then 2, then 3 for x in range(10): # sets x to each of ... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note
Computer scientists like to count from 0!
So to repeat something four times, a good Python programmer would do this:
for i in range(4):
alex.forward(50)
alex.left(90)
The range function is actually a very powerful function when it comes to creating sequences of integers. It can take one, two, or three parameters. We have seen the simplest case of one parameter such as range(4) which creates [0, 1, 2, 3]. But what if we really want to have the sequence [1, 2, 3, 4]? We can do this by using a two parameter version of range where the first parameter is the starting point and the second parameter is the ending point. The evaluation of range(1,5) produces the desired sequence. What happened to the 5? In this case we interpret the parameters of the range function to mean range(start,stop+1).
Note
Why in the world would range not just work like range(start, stop)? Think about it like this. Because computer scientists like to start counting at 0 instead of 1, range(N) produces a sequence of things that is N long, but the consequence of this is that the final number of the sequence is N-1. In the case of start, stop it helps to simply think that the sequence begins with start and continues as long as the number is less than stop.
Here are a two examples for you to run. Add another line below to create a sequence starting at 10 and going up to 20 (including 20).
(ch03_5)
Codelens will help us to further understand the way range works. In this case, the variable i will take on values produced by the range function.
|
Source Code
Step ? of ?
|
|
Program output:
|
Finally, suppose we want to have a sequence of even numbers. How would we do that? Easy, we add another parameter, a step, that tells range what to count by. For even numbers we want to start at 0 and count by 2’s. So if we wanted the first 10 even numbers we would use range(0,19,2). The most general form of the range is range(start, stop, step). You can also create a sequence of numbers that starts big and gets smaller by using a negative value for the step parameter.
(ch03_6)
Try it in codelens.
|
Source Code
Step ? of ?
|
|
Program output:
|
Here are a few more things that you might find useful as you use the turtle.
Turtle methods can use negative angles or distances. So tess.foward(-100) will move tess backwards, and tess.left(-30) turns her to the right. Additionally, because there are 360 degrees in a circle, turning 30 to the left will leave you facing in the same direction as turning 330 to the right! (The on-screen animation will differ, though — you will be able to tell if tess is turning clockwise or counter-clockwise!)
This suggests that we don’t need both a left and a right turn method — we could be minimalists, and just have one method. There is also a backward method. (If you are very nerdy, you might enjoy saying alex.backward(-100) to move alex forward!)
Part of thinking like a scientist is to understand more of the structure and rich relationships in your field. So revising a few basic facts about geometry and number lines, like we’ve done here is a good start if we’re going to play with turtles.
A turtle’s pen can be picked up or put down. This allows us to move a turtle to a different place without drawing a line. The methods are penup and pendown.
alex.penup()
alex.forward(100) # this moves alex, but no line is drawn
alex.pendown()
Every turtle can have its own shape. The ones available “out of the box” are arrow, blank, circle, classic, square, triangle, turtle.
...
alex.shape("turtle")
...
You can speed up or slow down the turtle’s animation speed. (Animation controls how quickly the turtle turns and moves forward). Speed settings can be set between 1 (slowest) to 10 (fastest). But if you set the speed to 0, it has a special meaning — turn off animation and go as fast as possible.
alex.speed(10)
A turtle can “stamp” its footprint onto the canvas, and this will remain after the turtle has moved somewhere else. Stamping works, even when the pen is up.
Let’s do an example that shows off some of these new features.
(ch03_7)
The list of integers shown above is created by printing the range(5,60,2) result. It is only done to show you the distances being used to move the turtle forward. The actual use appears as part of the for loop.
One more thing to be careful about. All except one of the shapes you see on the screen here are footprints created by stamp. But the program still only has one turtle instance — can you figure out which one is the real tess? (Hint: if you’re not sure, write a new line of code after the for loop to change tess’ color, or to put her pen down and draw a line, or to change her shape, etc.)
Lab
| Method | Parameters | Description |
|---|---|---|
| Turtle | None | Creates and returns a new turtle object |
| forward | distance | Moves the turtle forward |
| backward | distance | Moves the turle backward |
| right | angle | Turns the turtle clockwise |
| left | angle | Turns the turtle counter clockwise |
| up | None | Picks up the turtles tail |
| down | None | Puts down the turtles tail |
| color | color name | Changes the color of the turtle’s tail |
| fillcolor | color name | Changes the color of the turtle will use to fill a polygon |
| heading | None | Returns the current heading |
| position | None | Returns the current position |
| goto | x,y | Move the turtle to position x,y |
| begin_fill | None | Remember the starting point for a filled polygon |
| end_fill | None | Close the polygon and fill with the current fill color |
| dot | None | Leave a dot at the current position |
| stamp | None | Leaves an impression of a turtle shape at the current location |
| shape | shapename | Should be ‘arrow’, ‘classic’, ‘turtle’, or ‘circle’ |
Once you are comfortable with the basics of turtle graphics you can read about even more options on the Python Docs Website. Note that we will describe Python Docs in more detail in the next chapter.
Write a program that prints We like Python's turtles! 1000 times.
Give three attributes of your cellphone object. Give three methods of your cellphone.
Assume you have the assignment xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
Use for loops to make a turtle draw these regular polygons (regular means all sides the same lengths, all angles the same):
A drunk pirate makes a random turn and then takes 100 steps forward, makes another random turn, takes another 100 steps, turns another random amount, etc. A social science student records the angle of each turn before the next 100 steps are taken. Her experimental data is [160, -43, 270, -97, -43, 200, -940, 17, -86]. (Positive angles are counter-clockwise.) Use a turtle to draw the path taken by our drunk friend.
Enhance your program above to also tell us what the drunk pirate’s heading is after he has finished stumbling around.
On a piece of scratch paper, trace the following program and show the drawing. When you are done, press run and check your answer.
Write a program to draw a shape like this:
Write a program to draw a face of a clock that looks something like this:
with the turtle methods provided in turtle_methods.
what do you get?
Write a program to draw a Sprite where the number of legs is provided by the user.