WITH PROGRAMMING IN Python, you can create a huge range of things, from games to scientific data analysis programs, and from 3D modelling tools to robot controllers. In Adventure 1, you learned how to use some basic Python code to make a spaceship command console. Now you’re going to try something a bit more visual.
Creating images with Python is a fun and powerful way to learn how to program. What’s great about it is that you can create complex images with programs that use only a few lines of Python code.
In this adventure, you’ll learn how to use numbers and Turtle Graphics to make drawings with Python. Figure 2-1 shows a drawing made with Turtle Graphics.
In this adventure, you’ll use the turtle
module in Python. A module is a set of pre-written and reusable commands that extend what you can do with Python. Recall that you used the time
module in Adventure 1 to make your program wait a number of seconds before proceeding. The turtle
module allows you to create basic shapes and drawings in Python.
When you draw in Turtle Graphics, the cursor on your screen is referred to as a turtle, even though the default icon for the cursor doesn’t look like a turtle! It actually looks like an arrow—but it is still called a turtle. You can imagine a turtle walking across your screen, leaving a trail behind it to create shapes and images. You’ll most often use the turtle
module simply to draw lines. By creating lots of lines, turning the turtle round, changing colours and filling in shapes, you’ll discover that you can generate some really cool and complex images using only a few lines of Python.
Time to get started.
>>>
) at the start of the line.)turtle
module in your program, the first thing you need to do is import it. Type the following command into the shell to import the turtle
module:
import turtle
turtle.forward()
command and include an argument to tell it how many steps to take. In this example, you’ll start by moving the turtle 100 steps. When you put the 100 in between the brackets, you do not need to use speech marks as you’re using numbers, not strings (more on this in a bit):
turtle.forward(100)
turtle.right(90)
Press Enter, and the turtle turns 90 degrees to the right.
turtle.forward(50)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
Et voila! The turtle will have drawn a rectangle. It should now be back where it started, as shown in Figure 2-3.
You can of course change the arguments that you give the right()
and forward()
functions.
You have used integers in this program. Integers are whole numbers (that is, numbers with no decimal place) and can be either positive or negative. For example, 10, 92, 3, -78 and -831,789 are all integers.
The values used for arguments in the turtle functions can be swapped for variables. This next program uses variables for two things: the length of the sides; and the angles. The turtle will draw a zigzag line in this program. You’ll also notice a new command, left()
, which, as you might have guessed, makes the turtle turn left.
turtle
module:
import turtle
length
and another called angle
and set their values to 20 and 45, respectively:
length = 20
angle = 45
turtle.forward(length)
turtle.right(angle)
turtle.forward(length)
turtle.left(angle)
Adventure 2
and save the file in it as zigZag.py
. Now when you run the program it will draw a zigzag as in Figure 2-4, making each length 20 steps and each angle 45 degrees.One of the most useful features of variables is that you can change the value that they store. Here’s an example for you to try, which should demonstrate the power of variables.
zigZag.py
).angle
variable so that it has the value of 90, instead of 45:
angle = 90
When you run the program you should see that the angle of each zigzag is now 90 degrees, as in Figure 2-5. This is because the value of the angle
variable has been changed.
Change the value of the length
variable and run the program to see how this affects the shape of the zigzag.
As you have just seen, you can change the value of a variable to change the result of your program. But there’s a lot more you can do—you can also change the value using addition, subtraction, multiplication and division. You’re now going to use addition to draw a spiral with the turtle.
turtle
module and set the length
and angle
variables with the following code:
import turtle
length = 10
angle = 90
turtle.forward(length)
turtle.left(angle)
length = length + 10
spiral.py
in the Adventure 2
folder and run it with Run⇒Run Module. You should see a spiral like the one shown in Figure 2-6.It’s not a good idea to copy and paste a block of code many times in a program. What happens if you want to change something? If you’ve pasted the code lines in 20 times, you would have to make 20 changes! You might be able to do it quickly if you’ve only got a few commands, but it soon gets very time consuming if there are lots of lines of code, and you may sometimes have hundreds or even thousands of lines. So much repeated code also makes the program harder to read and understand. There is a simpler way to it.
As you learned in Adventure 1, loops are an efficient way to repeat blocks of code. In this next example, you use a loop to create a spiral instead of copying and pasting the lines of code over and over again.
turtle
module and create length
and angle
variables:
import turtle
length = 0
angle = 90
while length < 200:
turtle.forward(length)
turtle.right(angle)
length = length + 10
betterSpiral.py
in the Adventure 2
folder.Notice how your program can draw a lot more than it did in the previous example, while using fewer lines of code.
The while
loop in this code uses a less than comparator. It checks that the length of the line being drawn is less than 200. The body of the loop will repeat only when the length is less than 200. If it is equal to 200 or greater than 200, the loop will stop running. You can change this number to make a bigger or smaller spiral.
There are six types of comparators that you can use in your own programs:
==
): Checks whether two values are the same!=
): Checks whether two values are not the same<
): Compares a value to see if it less than another value<=
): Compares a value to see if it is less than or the same as another value>
): Compares a value to see if it is greater than another value>=
): Compares a value to see if it is greater than or the same as another valueAll of these comparators can be used with if
statements and while
loops.
So far, the programs that you’ve written have only used straight lines. But what about circles? They don’t use straight lines, just a single curved line. How can the turtle program create a curved line?
There’s a simple solution to this: you create a curve simply by using lots and lots of very short straight lines with small turns. If your program creates 360 lines and 360 turns of 1 degree, it will result in a circle. Try it out for yourself:
circle.py
in the Adventure 2
folder.import turtle
repeats = 0
while repeats < 360:
turtle.forward(1)
turtle.right(1)
repeats = repeats + 1
You can create quite an array of shapes by adapting the code from the example you just completed. You could change the program so that it creates a square or a triangle, for example. Can you work out how to do this? This next program uses input so that you can tell it how many sides you want your shape to have. The program uses a prompt that asks that very question.
shapes.py
in the Adventure 2
folder.import turtle
sides = int(raw_input("Enter the number of sides for
your shape: "))
angle = 360.0 / sides
length = 400.0 / sides
for side in range(sides):
turtle.forward(length)
turtle.right(angle)
turtle.done()
In this program, you have used a few things you haven’t seen so far. Look at Step 3. On lines 3 and 4 the numbers have decimal places—in other words, they are not whole numbers, or integers but a different data type called a floating point number, or float. A float is the name for any number in Python that has a decimal place. Because floats and integers are both types of number, you can add, subtract, multiply and divide them.
On line 2 of the program, the raw_input()
function is inside an int()
function. The raw_input()
function returns any data you input as a string—but your program needs to use your input as an integer, not a string. You therefore use the int()
function to convert your input from a string to an integer. Converting one data type to another in this way is known as type conversion.
The code divides the total number of degrees in a circle (360) by the number that was input. This determines the degrees of each angle in the shape. The length of each side is determined by dividing 400 by the number that was input. These variables are then used to make the shape on the last four lines of the program.
You have already come across one type of loop, the while
loop. For loops are another type of loop that repeats a block of code. The for
loop will repeat a number of times, determined by the argument inside the range()
function. The range()
function is very commonly used with for
loops. You can also use for
loops with lists, which you will learn about later. In the code you have just written, the loop will repeat the same number of times as is input for the number of sides. The argument of the range()
function can be changed to another number to make the loop repeat a different number of times. For example, you could change the number of sides to four by using this code:
for sides in range(4):
[etc…]
The last line of the program, turtle.done()
, keeps the window open even after the shape has been drawn. Without it the program would close immediately after the shape has been drawn.
Now you’ve drawn a simple shape, what can you do to liven it up a bit? Add a bit of colour, that’s what. With a simple change to the program, you can get your turtle to fill in the shape with colour. Here’s how.
shapes.py
program, if it isn’t open already.for
loop, add the following lines of code:
turtle.fillcolor("blue")
turtle.begin_fill()
turtle.end_fill()
In the first Python statement you added, turtle.fillcolor("blue")
, you selected the colour you wanted the turtle to use. There are a range of colours that you can use, including red, green, black and orange.
Try using different colours in your shapes; remember that they need to be written as a string. You will return to colours in a later adventure, when you learn more about using them, including how to create colours of your own.
If you are starting to think like a computer programmer, you’ll now be thinking: How can I save time? And how can I make more of my programs reusable? When you used the raw_input()
function in Adventure 1, you learned that functions are one way that code can be made to be reusable. Now you’re going to learn how to create your own functions to reuse code that draws shapes.
In the next example, you will use two functions to create shapes and move the position of the turtle.
turtle
module:
import turtle
sides
and length
arguments. Type this code below the import
command in the file editor:
def drawShape(sides, length):
angle = 360.0 / sides
for side in range(sides):
turtle.forward(length)
turtle.right(angle)
def moveTurtle(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
drawShape(4, 10)
moveTurtle(60, 30)
drawShape(3, 20)
turtle.done()
reusableShapes.py
in the Adventure 2
folder and run the program with Run⇒Run Module. You can see the output in Figure 2-11.You can now draw more shapes by calling the functions as many times as you want, using whatever arguments you like. This code uses the functions you just made to draw a shape with five sides and another shape with 10 sides. Add this code above the turtle.done()
line:
moveTurtle(-100, -60)
drawShape(5, 100)
drawShape(10,100)
Shapes with a predetermined number of sides, like triangles, circles, squares and pentagons, are very common. Instead of having to recreate the shape every time with the drawShape()
function, wouldn’t it be cool to add some code so that the common shapes have their own functions? For example, you could create a drawSquare()
function that would instantly draw a square. Here’s how:
reusableShapes.py
program that you just created. Underneath the moveTurtle()
function add the following code:
def drawSquare(length):
drawShape(4, length)
drawShape()
function and gives the drawShape()
function the value of 4 for the sides
argument. By doing this, the functions are reused so that your program uses fewer lines of code and is easier to read.def drawTriangle(length):
drawShape(3, length)
def drawCircle(length):
drawShape(360, length)
turtle.done()
line in your program:
moveTurtle(-100, 20)
drawSquare(30)
moveTurtle(- 10, 20)
drawCircle(1)
drawCircle(2)
moveTurtle(75, -75)
drawTriangle(60)
Now that your program can reuse functions to create images, this is where things get interesting! You can easily change the code to draw some cool things. You can use the functions to quickly draw complex shapes with only a few lines of Python, or draw pictures by combining the different functions.
The next thing you’re going to do is make your turtle draw completely random shapes all over the screen, a bit like in Figure 2-13.
reusableShapes.py
program and save it as randomShapes.py
in the Adventure 2
folder.import turtle
def drawShape(sides, length):
angle = 360.0 / sides
for side in range(sides):
turtle.forward(length)
turtle.right(angle)
def moveTurtle(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
def drawSquare(length):
drawShape(4, length)
def drawTriangle(length):
drawShape(3, length)
def drawCircle(length):
drawShape(360, length)
In other words, what’s left are all the functions that you created in the program.
random
:
import random
Add the following function to create a random shape at a random location:
def drawRandom():
x = random.randrange(-;200, 200)
y = random.randrange(-;200, 200)
length = random.randrange(75)
shape = random.randrange(1, 4)
moveTurtle(x, y)
if shape == 1:
drawSquare(length)
elif shape == 2:
drawTriangle(length)
elif shape == 3:
length = length % 4
drawCircle(length)
turtle.done()
function:
for shape in range(100):
drawRandom()
turtle.done()
For further adventures with Turtle Graphics, use the commands in the following quick reference table to experiment.
Python Command Quick Reference Table |
|
Command |
Description |
|
This statement imports the |
|
This command moves the turtle forward a number of steps and makes it draw a straight line. |
|
This command turns the turtle a number of degrees to the right. |
|
This command turns the turtle a number of degrees to the left. |
|
Whole numbers in Python use the integer data type; 5, 237 and 21 are all examples of integers. |
|
Integers can be stored in variables. This allows the value of the variable to be reused and changed as the program runs. |
|
The addition operator is used to add two number values together. The result is usually stored in a variable like this: |
|
The < comparator compares two values. If the first value is less than the second, it evaluates to |
|
The |
|
The |
|
Floats are a data type used to represent numbers with decimal places; 6.8, 11.51 and 574.96 are all examples of floats. |
|
The division operator divides one number by another. The result is often stored in a variable like so: |
|
A |
|
These functions are used in the |
|
Functions are created using the |
|
The modulo operator divides one number by the other and returns the remainder of the division. For example, |
|
The |
|
The |
Achievement Unlocked: Creator of splendid shapes using the turtle
module.
18.191.234.150