(In Easy Steps) Max Wainewright - Coding With Python - Create Amazing Graphics - The QuestKids Do Coding-In Easy Steps Limited (2022)
(In Easy Steps) Max Wainewright - Coding With Python - Create Amazing Graphics - The QuestKids Do Coding-In Easy Steps Limited (2022)
Cover
Title
Copyright
Contents
Getting Started
Saying Hello
Giant Circles
Simple Squares
Square Patterns
Multi Patterns
Spinning Circles
A Bit Random
Random Dots
Random Colours
Random Lines
Random Sizes
Random Line Burst
Random Colour Spin
Random Hoops
Mixing Colours
Blended Square
Blended Circle
Shaded Sphere
Colour Mix Points
Spiral Blend
Colour List Spiral
Drawing Pictures
Flower
Donut
Pizza
Emojis
Dog
Functions
Square Function
Flower Function
Recursive Spiral
Recursive Squares
Recursive Tree
Extra Challenges
Python Commands
Glossary
Back Cover
To create the games in this book you will
need:
a computer or laptop with a proper keyboard – an iPad or any
other tablet will not work so well.
Copyright © 2022 by In Easy Steps Limited. All rights reserved. No part of this book may be reproduced or
transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any
information storage or retrieval system, without prior written permission from the publisher.
Trademarks
All trademarks are acknowledged as belonging to their respective companies.
Printed and bound in the United Kingdom
Notice of Liability
Every effort has been made to ensure that
this book contains accurate and current information. However, In Easy Steps Limited and the authors shall not be liable
for any loss or damage suffered by readers as a result of any information contained herein.
Contributors:
Author: Max Wainewright
Creative Designer: Jo Cowan
Cover & character illustrations: Marcelo (The Bright Agency)
Acknowledgements
The publisher would like to thank iStock for the use of their background illustrations.
Contents
Getting Started
Saying Hello
4
5
Giant Circles
Simple Squares
Square Patterns
Multi Patterns
Spinning Circles
6
10
12
14
16
A BIT RANDOM
Random Dots
Random Colours
Random Lines
Random Sizes
Random Line Burst
Random Colour Spin
Random Hoops
18
20
22
24
26
28
30
32
MIXING COLOURS
Blended Square
Blended Circle
Shaded Sphere
Colour Mix Points
Spiral Blend
Colour List Spiral
34
36
38
40
42
44
46
DRAWING PICTURES
Flower
Donut
Pizza
Emojis
Dog
48
50
52
54
56
58
FUNCTIONS
Square Function
Flower Function
Recursive Spiral
Recursive Squares
Recursive Tree
62
64
66
68
70
72
Extra Challenges
Python Commands
Glossary
75
79
80
Getting Started
In this book you will learn how to create some amazing graphics
using Python. You will also become a great Python coder!
Keep looking up and down your code to look for patterns. IDLE (the Python editor) changes
the colour of some code to make it easier for you to find errors.
Can you find the errors in each of these? Only one has no errors!
See below
for the answers!
Answers: A) Missing quote mark before blue. B) No errors! C) Missing left bracket after color.
D) Import is spelt incorrectly.
8
Another circle
Find the IDLE window with your code in. Add the lines of code
marked in green (lines 7 to 12).
Don’t change
this part.
Pick yellow.
Draw a medium circle.
Choose red.
Draw a smaller circle.
Pick purple.
Draw a small circle.
Save again
Click File > Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The turtle graphics window should appear with an image like
this:
Check for errors
Check your code carefully if it doesn’t work properly. Make
sure your follow the pattern of changing colour then drawing
a dot on the next line.
After that, save and run your code again.
Challenges
Experiment with your code and make your own designs!
To make the code simpler we will use a loop to repeat some code
four times.
HOW THE CODE WORKS
The turtle moves forward 200 steps then turns right
90 degrees.
The loop makes the turtle move forward and turn again.
The loop repeats again and the square is almost complete.
The square is now completed and the code stops.
We’ll use
these commands to draw the square.
This is what coders call a loop. It makes some lines of code repeat four times. The lines that
we want to repeat are indented – moved in from the edge, like the start of a paragraph. The
variable
n is used to count to 4.
This command tells the turtle to move forward 200 pixels. It will draw the side of the square.
10
Make a new Python file
Start up IDLE or click File > New File.
Switch on the line numbers
Click Options > Show Line Numbers.
Start coding!
Type in this code to make a square:
Import the graphics commands.
Leave a gap in your code.
Set the thickness of the lines drawn.
Choose the colour of the square.
Repeat the following code four times:
Move forward 200 steps.
Turn right 90 degrees.
Press Enter twice to leave a gap.
Save your file
Click File > Save.
Type in square as the file name.
Browse to your Documents folder.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
Another window will start and show
the results of your code.
It should contain a red square, like this:
Not working?
Go back and look through your code carefully.
Check you have typed the code exactly as above. Make sure
the correct lines are indented.
Click File > Save and run your code.
Challenges
Change the number 20 in line 3. What happens?
Edit line 7 and use a larger number. How does it change the
square?
What happens if you change the number in line 6?
Try using different colours, and experiment.
Wow!
11
Square Patterns
Python is a great coding
language for creating patterns. By drawing lots of squares
we
can make various different designs. Once you have got
the hang of this, you can play with the code and
experiment, making different-sized and different-coloured
pieces of art.
HOW THE CODE WORKS
Our project will use two loops. One loop will draw a square, using the code from the previous
project.
The other loop will repeat the first loop, making lots of squares. Each square will be rotated
10 degrees to the right to make the pattern above.
When one loop
is inside another loop it is called
a nested loop.
Make a new Python file
Start up IDLE or click File > New File.
Switch on the line numbers
Click Options >
Show Line Numbers.
12
Start coding!
Import the graphics commands.
Leave a gap.
Set the width of the line to 3 pixels.
Tell the turtle to draw in blue.
Leave a gap.
Repeat the following lines 36 times:
Rotate the turtle 10 degrees to the right.
Repeat the lines below four times:
Move forward 100 pixels.
Turn right 90 degrees.
I wish I were
a turtle…
Save your file
Click File > Save.
Type in squares as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
Another window will start and show the output from your code.
A pattern like this should start to be drawn:
Having problems?
Check your code carefully.
Make sure you have typed the code exactly as above. Are all
the lines indented the right amount?
Click File > Save and run your code again.
Challenges
Experiment with colours and line width.
Python tries to guess when you want to indent some code, but you will have to make some
changes yourself. You can always add or delete spaces at the start of a line. Just move your
cursor to the start of a line and press the Backspace key or the Space bar.
13
Type in the code below to create a pattern:
Multi Patterns
In this project, the code from the previous activity is used
multiple times. This allows us
to build up a more complex and interesting pattern. Each block
of code draws a square of a different size and colour.
Nice!
14
Start coding!
Import the graphics module.
Set the turtle’s speed to fast.
Set the line width to 4 pixels.
Choose the colour red to draw with.
Repeat the following lines 36 times:
Rotate the turtle 10 degrees to the right.
Repeat the lines below four times:
Move forward 200 pixels.
Turn right 90 degrees.
Keep the line width at 4 pixels.
Now, draw in orange.
Repeat the following lines 36 times:
Rotate the turtle 10 degrees to the right.
Repeat the lines below four times:
Move forward 160 pixels.
Turn right 90 degrees.
Make sure
all your code is indented correctly.
Save your file
Click File > Save.
Type in multi as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The graphics window will appear and show the first two parts
of the pattern.
Having problems?
Go through your code carefully.
Check you have entered the code exactly as above. Are all the
lines indented the right amount?
Once you have
the first two patterns working, try to add the third one yourself!
Challenges
Try to make some of these patterns:
15
Type in the code below to create a pattern:
Spinning Circles
We can make a filled circle
in Python by using the dot command. To make an unfilled circle,
we need to adapt the code we used to make a square. Instead of
drawing a shape
with four sides, we will draw one with 36 sides – which will look
like a circle. By drawing lots of rotated circles, we can create an
amazing pattern!
A square has four sides. The turtle turns 90 degrees at each corner.
To make our “circle” we will just turn 10 degrees after each line.
HOW THE CODE WORKS
36 x 10 = 360
Although this looks like a circle, it is
in fact drawn with straight lines.
If we zoom in enough we can see it is really a polygon shape. It has 36 sides.
Our pattern is created by drawing a “circle” then rotating the turtle 6 degrees and drawing
another circle.
Gradually, the pattern is built up as more
and more “circles”
are drawn.
Make a new Python file
Start up IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
16
Start coding!
Type in this code to make a square:
Import the graphics module.
Set the speed of the turtle to fast.
Colour the background in black.
Draw in red.
Repeat the following code 60 times:
Repeat the next two lines 36 times:
Move forward 25 pixels.
Turn right 10 degrees.
Turn right 6 degrees.
Now, draw in gold.
Repeat the following code 30 times:
Repeat the next two lines 36 times:
Move forward 20 pixels.
Turn right 10 degrees.
Turn right 12 degrees.
Take care with the indentation of each line so that Python knows which parts to repeat.
Save your file
Click File > Save.
Type in circles as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
See the circles!
A new window will pop up and show the results of your code.
It should look like this:
Not working?
Carefully look through all your code.
Does the code exactly match Step 3? Check the lines are
indented the correct amount – line 7 should line up with line
10; line 14 should match line 17.
Click File > Save and run your code.
Challenges
Experiment with colours and how far the turtle moves forward.
Can you make these patterns?
17
A BIT RANDOM
All the patterns in this next section of the book are made by
using a loop to draw something over and over again.
We can use this approach
to draw hundreds or even thousands of dots or lines.
But to make this interesting,
we will need to make each dot or line different. To do this, we
will need some new code – the random module.
Using the random module
To use any of the commands in the random module we need to
load it first.
This tells Python to import (load) all the commands to do with making things random.
We have already used import to load the turtle module.
A module (or
library) is a group
of commands that do related things
Picking a random number
Throwing a dice gives us a random number between 1 and 6.
We can do this with code using the randint command.
The smallest number to pick.
The largest number to pick.
randint is
short for random integer. An integer is a whole number.
18
Drawing a random-sized dot
To draw a random-sized circle we can use some code, like this:
Pick a random number between 80 and 400. Store it in a variable called size.
Draw a dot as big as the value stored in the size variable.
Storing the random number in a variable makes it easier to read our code.
Choosing a random colour
We can easily pick a random colour by making a list.
Create a list called paint with three items.
Set the turtle colour to one of the items in the list.
Later on in the book
we will find how to make random colours in up to 16 million shades!
Moving to a random place
We can easily send the turtle to a random position on the
screen.
Choose a random number between 0 and 100. Store it in a variable called x.
Do the same for y.
Move the turtle to the coordinates (x,y).
Making a random decimal
The randint command makes integers (whole numbers). If you
want to make a decimal you need to use the uniform command.
The smallest value to pick.
The largest value to pick.
19
Random Dots
This project will draw a simple pattern made up of randomly-
placed dots on the screen.
A loop will repeat 10 times, drawing each of the dots. Two
variables, x and y, will be used to set the coordinates of each
dot. These variables will be given random values whenever the
loop runs.
Make a new Python file
Start up IDLE or click File > New File.
Switch on the line numbers
Click Options >
Show Line Numbers.
Start coding!
Type in this code:
Import the graphics commands.
Import the random library.
Repeat the code below 10 times:
Make a variable called x. Give it a random value between 0 and 100.
Create another variable called y, with a random value from 0 to 100.
Move the turtle to the coordinates (x,y).
Draw a dot 20 pixels wide.
This project
uses the random module to pick numbers…
…and the turtle module to turn the numbers into dots on the screen.
20
Save your file
Click File > Save.
Type random dots as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The graphics
window will start and will show the output from your code.
A series of dots should be drawn in the top-right part of the
window.
Check for errors
If this doesn’t work then go back and look through your code
carefully.
Make sure you have typed
the code just as it is written in Step 3. Check that lines 5 to 8
are indented, and you typed the colon : at the end of line 4.
Click File > Save and run your code.
Challenges
Edit line 4 to increase the number of dots drawn by your code.
Change the size of the dot to make it bigger or smaller.
In line 5, change the range of the random values to 0 to 200.
Try changing the range of y values in line 6.
Make the dots fill the screen by using negative (minus numbers)
in the range. For example, change line 5 to say (-200,200)
instead of (0,100).
31
Random Hoops
The first project in this book used code to draw a series of
dots, creating a coloured target. The code here will automate
and randomise that idea. We will use a loop to draw multiple
circles, starting with a large circle then another, gradually
decreasing in size. The control variable from the loop will set
the size of the circle. Colours will be picked at random.
HOW THE CODE WORKS
A for loop controls this code, using a variable called size. This variable starts at
400 and changes its value by -10 each time the loop runs. This makes each dot that it draws
get smaller and smaller. A random colour is picked for each of the dots.
size = 400
size = 390
size = 380
size = 250
size = 10
This looks
similar to the Giant Circles activity on page 8.
But this code
uses a loop and random values.
Make a new Python file
Launch IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
32
Start coding!
Type in this code:
Import the turtle graphics library.
Import the random library.
Set the turtle to move quickly.
Create a list of colours called paint.
Make a loop that runs down from 400 to 0
in steps of negative 10 (-10).
Pick a random colour from the list.
Draw a dot the width of the size variable.
Save your file
Click File > Save.
Type random hoops as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The graphics window will appear and display the output of
your code.
A series of coloured circles should be drawn, getting smaller
and smaller.
Check for errors
If the code doesn’t work properly, go back and look through
each line of your code.
Check you have typed the code just as it is written in Step 3.
Make sure you typed -10 (minus 10) in line 7.
Click File > Save and run your code.
Challenges
Try to make some of these patterns:
33
MIXING COLOURS
The projects in the next
part of this book explore how colours can be chosen using
numbers. Instead of being limited to blue, light blue or dark
blue, we can use numbers to specify the shade of blue we want.
By combining this idea with some loops and variables, we will
build some amazing patterns using thousands of different
shades!
Red, green and blue light
When you are using real paint, mixing red and blue makes
purple. Mixing blue and yellow paint makes green.
On a computer we mix light instead of paint. Mixing red and
blue light makes purple, but mixing red and green light makes
yellow.
By varying the amount of red, blue and green light, we can
make any colour.
This is called the RGB colour system (named after the colours it uses).
RGB colour modes
We mix a particular colour by specifying the amount of red,
green and blue to use.
There are two different ways to say how much of each colour
we want:
The amount of each colour is given as a decimal between
0 and 1.0.
The amount of each colour is given as a number between
0 and 255.
34
In this book we will use this mode.
Setting colours
Colours can be set by using the turtle.color command,
but instead of words we use RGB values.
This sets a colour with
maximum red, no green and no blue = Red.
No red, maximum green and no blue = Green.
35
Blended Square
We will start off by drawing a simple square. A series of lines
will be drawn by the turtle, each one a slightly different colour.
The control variable in the loop will be used to set part of the
RGB colour value so that the colours gently blend together as
the square is drawn.
HOW THE CODE WORKS
A for loop controls this code, using a variable called x. As x grows from 0 to 200, it draws the
square one line at a time. The value of x is used to mix the line’s colour, so each line is a
slightly different colour.
x=0
x=50
x=100
x=150
x=200
The first line is drawn. The turtle colour (255,128,0) is orange.
More lines have been drawn. The turtle colour (255,128,50) is bright orange.
Half the square is now drawn and the colour (255,128,100) is an orange-pink mix.
The square is nearly finished and the colour (255,128,150) is pink.
The square is complete. The turtle colour (255,128,200) is bright pink.
Make a new Python file
Launch IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
36
Start coding!
Type the code below into the Python editor:
Import the graphics library.
Tell the turtle to move quickly.
Set the turtle to use colour values from 0 to 255.
Repeat the code below 200 times:
Set the colour based on the current value of x.
Gradually move the turtle sideways along the graphics window.
Draw a line up 200 pixels.
Save your file
Click File > Save.
Type blended square as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The graphics window will show and display the output of your
code.
A square like this will be drawn in the top-right part of the
window:
Check for errors
If the code doesn’t work properly, go back and look through
each line of your code.
Check your code matches Step 3. Make sure the brackets and
the values are all correct.
Click File > Save and run your code.
Challenges
In line 7, try changing 255 to 0 and see what happens.
Change 128 to 0 and run your code to see the effect.
Keep experimenting and try to create some of these squares:
Nice effect!
37
Remember to
set the turtle’s speed or your code will take a long time!
Blended Circle
This project shows another way to create a pattern by mixing
colours using the RGB system. Multiple lines are drawn from the
centre of the graphics window. Each line is a slightly different
colour, creating a circular pattern as the code runs.
HOW THE CODE WORKS
Each line is drawn in a slightly different colour. This is because of the control variable that
counts how many times the loop is run. It also gets used to set the colour of the line. So, each
time a new line is drawn, a different value is used to set the colour.
a=150
After the loop has drawn
150 lines, the circle is
almost complete. The turtle
colour will be (255,150,0) – orange.
a=75
By the time this line is drawn, the colour will be (255,75,0) – a mix of red and orange.
a=0
When the line starts, the colour of the turtle will be (255,0,0), which is red.
Make a new Python file
Launch IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
38
Start coding!
Start typing in this code:
Import the graphics library.
Tell the turtle to use colour values from 0 to 255.
Set the speed to fast.
Pick the line width.
Repeat this code 180 times:
Move the turtle to the centre of the window.
Set the colour of the turtle using the variable a.
Rotate slightly to the right (clockwise).
Draw a line 300 pixels long, facing in the current direction.
Turn back to page 34 for a reminder of how RGB colour mixing works.
Save your file
Click File > Save.
Type blended circle as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The output from your code will be shown in the graphics
window.
A circle should be drawn in the centre of the window.
Check for errors
If the code doesn’t work properly, go back and look through
each line of your code.
Check your code against Step 3, making sure all the
commands and values are correct.
Click File > Save and run your code.
Challenges
Use a larger number in line 5 to set the line thickness.
Try rotating by 1 degree instead of 2 in line 10.
Change the amount moved forward from 300 in line 11. What
happens to the circle?
41
Colour Mix Points
This project will draw
hundreds of small dots on
the screen. Each one will be positioned in a random place, but
they will also be a slightly different colour. A loop will keep the
code running. The control variable from the loop will be used to
help set the colour, using RGB values.
Make a new file
Start up IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
Start coding!
Start typing this code into the Python editor:
Import the turtle graphics commands.
Import the random library.
Stop the turtle drawing lines between each dot.
Set the speed of the turtle to fast.
Use colour values between 0 and 255.
Repeat the code below 255 times:
Give the x and y variables a random value between -200 and 200.
Move the turtle to the coordinates (x,y).
Set the colour using the variable c.
Draw a small dot on the screen.
42
Save your file
Click File > Save.
Type points as the file name.
Click Save.
Run
Click Run > Run Module.
(or press F5)
View your work
The graphics window should show hundreds of coloured dots
on the screen.
Check for errors
If it doesn’t work, go back and check each line of code. Click
File > Save and run your code again.
More code, more dots
Edit your code to look like this:
Click at the end of line 8 and press Enter to make space
for a new line of code.
This second loop will repeat all the code below five times.
Click at the start of line 10 and press the Tab key. Make sure all lines from
10 to 14 are indented more than line 9.
Remember –
the indents are an important part of the code.
Save again
Click File > Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The graphics window should now show a lot more dots!
Check for errors
Make sure that lines 1 to 8 are not indented. Line 9 should be
indented and lines 10 to 14 should be double-indented.
Challenges
Try to make some of these patterns:
43
Spiral Blend
The code in this project will draw a spiral on the screen. Each
line in the pattern will be slightly longer and a slightly
different colour. We’ll start by drawing a spiral based on a
square shape, with 90-degree corners. Once this code is working
we can adapt it, creating some amazing effects!
Make a new Python file
Launch IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
Start coding!
Start by typing in this code:
Import the turtle graphics library.
Set the turtle speed to fast.
Use colour values between 0 and 255. Choose the line width to draw with.
Repeat the code below 255 times:
Set the turtle colour based on the n variable.
Move forward by double the value of n.
Turn right 90 degrees.
44
Save your file
Click File > Save.
Type spiral blend as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
A coloured spiral pattern will appear in the graphics window.
One degree more
Edit line 10 of your code to make the turtle turn 91 degrees at
each corner instead of 90.
Turn right 91 degrees.
This change adds a little magic!
Check for errors
If it doesn’t work, go back and check each line of code. Click
File > Save and run your code again.
Save and run
Save the changes and run your new code.
Click File > Save.
Click Run > Run Module or press F5.
See the changes
A new pattern will be drawn in the graphics window.
Challenges
In line 10, try turning by 92 or 93 degrees.
What happens if you use n*3 in line 9?
Try making some of these patterns.
45
Colour List Spiral
Instead of gradually changing the colour shade, this project uses
a different method to choose colours. A spiral is drawn using
similar code to the previous activity. Colours are picked in turn
from a list of six. Because the spiral being drawn is hexagonal,
an interesting colour effect is created.
HOW THE CODE WORKS
A list of colours called col is created.
A for loop makes the variable n increase from 0 up to 254.
A special function works out the remainder when n is divided by 6. This function is called
mod and is represented by the % symbol.
This value, n%6, is used to pick a colour from the list, so each colour is used in turn.
A hexagonal spiral is drawn using the colour. Because there are six sides and six colours, this
gives us the pattern shown above.
The code makes this sequence of colours keep on repeating!
Make a new Python file
Launch IDLE or click File > New File.
Switch on the line numbers
Click Options >
Show Line Numbers.
46
Start coding!
Type in this code:
Import the turtle graphics commands.
Set the background colour.
Tell the turtle to move quickly.
Set the line width to 1.
Create a list of colours.
Repeat these lines 255 times:
Pick the colour for the turtle.
Move forward n steps.
Turn right 61 degrees.
360 ÷ 6 = 60
By turning 61 degrees, the spiral is almost hexagonal.
Save your file
Click File > Save.
Type spiral list as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
A graphics window will
start up. The hexagonal pattern should be slowly drawn in the
window.
Check for errors
If it doesn’t work, check each line carefully.
Make sure you typed in line 6 correctly, using the quote mark,
commas and square brackets.
Check you typed the correct symbol to calculate the colour in
line 9.
Click File > Save then run your code.
Challenges
Try using a different set of colours in line 6.
Experiment with the angle the turtle turns by in line 11.
47
DRAWING PICTURES
The next section in this book shows you how to draw pictures
using Python. We will use some coding techniques that we’ve
used in the previous projects, such as loops and variables.
A light blue circle will cut a hole out of the middle of the donut.
Don’t forget to add sprinkles to the donut!
48
Using coordinates
With some pictures, you will need to move the turtle to
particular places on the screen.
The ear is too far up and too far to the left. We need to make the x value bigger and the y
value smaller.
Now, the ear is too far to the right! We need to try a value in between the two x values. The y
value looks okay.
That looks perfect! We have corrected our code using “trial and error”.
Phew!
Squared paper
Sometimes, it’s much easier if you plan out your picture on
some squared paper.
Start by drawing the x and y axes on the paper.
Add numbers to the x and y axes.
This will also really impress your maths teacher!
Then, you can start planning the code. This will draw a yellow face:
And this will add the right eye:
49
Flower
Our first project in this section is a simple picture of a flower.
We will combine together some lines and a dot to make the
design. By setting a very wide line width, we will create petals
for the flower. A loop will be used to draw five petals in total.
HOW THE CODE WORKS
Point down then draw a green line to be the stem of the flower.
Use a loop to draw
a thick orange line
for each petal of the
flower.
The loop turns
72 degrees each
time to make five
petals in total.
A red dot in the centre completes the flower.
Make a new Python file
Launch IDLE or click File > New File.
Switch on the line numbers
Click Options >
Show Line Numbers.
50
Enter this code
Import the turtle graphics library.
Set the width to 10 pixels.
Point the turtle upwards.
Choose the green colour.
Draw a line to be the stem of the flower.
Repeat the code below five times:
Set the width to 50 pixels.
Turn right 72 degrees.
Set the colour to orange.
Move forward to draw the petal.
Move back to the centre.
Pick a red colour.
Draw the centre of the flower.
Save your file
Click File > Save.
Type flower as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your code
The Turtle Graphics window will appear and your flower will be
drawn.
Check for errors
If this doesn’t work then go back and look through your code
carefully.
Check your code is exactly as shown above. Make sure lines 9
to 13 are noindented.
Click File > Save and run your code.
Challenges
Experiment with different colours for different parts of the
flower.
Try making the flower bigger or smaller.
Change the amount the turtle turns in line 10 from 72 to 36. How
many times will you need to make the loop repeat in line 8 to
complete the flower?
Set the background colour to green.
Later on in
this book we will
learn how to make
a command to draw a flower.
51
Donut
Yum!
The basic shape of our donut
will be made by drawing a
series of circles. We will use
RGB colour values to pick the correct shade for the dough.
The sprinkles will be created
by using a loop. This will work
in a similar way to the project on pages 30-31, spreading out the
sprinkles around the donut. Each sprinkle will have a
random colour and direction.
HOW THE CODE WORKS
A light blue background is set.
The donut is
drawn using RGB values to set the light brown colour.
A pink dot adds the glaze (or icing).
The centre of the donut is removed by drawing a light blue dot over the centre.
A for loop draws 60 random sprinkles around the donut.
Make a new Python file
Start up IDLE or click File > New File.
Show the line numbers
Click Options >
Show Line Numbers.
52
Enter this code
Import the graphics commands.
Import the random command library.
Make the turtle move quickly.
This lets us pick values from 0 to 255 for colours.
Set the background colour.
Mix a light brown donut colour.
Draw the donut.
Pick pink.
Draw on the icing.
Select the background colour again.
Make a hole in the donut by drawing on top of it.
Make a list of colours for the sprinkles.
Set the width of the sprinkles.
Repeat the code below 60 times.
Spread the sprinkles out every 6 degrees.
Stop drawing.
Move the turtle to the centre.
Move forward a random distance.
Face a random direction.
Pick a colour from the sprinkles list.
Get ready to draw.
Draw a sprinkle.
Save your file
Click File > Save.
Type donut as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
A donut!
Check for errors
Go back and look through your code carefully.
Check each line of code.
Challenges
Change the icing glaze to chocolate.
Add more sprinkles. Add more colours!
Challenges
Draw green olives instead of black ones.
Change the number of slices.
Add some other toppings to the pizza.
55
Emojis
It doesn’t take a lot of code to draw a simple happy
emoji – but everything
needs to be in the correct place! We will start by drawing a big
yellow circle for the head, then add
eyes and a big circle for
the mouth. A second yellow circle will be drawn over the top of
the mouth, changing
it into a smile.
HOW THE CODE WORKS
Draw a big yellow dot to be the face.
Position the
turtle using the goto command and draw a small black dot.
Draw another small black dot to make the other eye.
Draw a medium-sized black dot to make the mouth.
Draw another yellow dot over the top of the mouth to create a smile.
Make a new Python file
Start up IDLE or click File > New File.
Turn on the line numbers
Click Options >
Show Line Numbers.
56
Enter this code
Import the turtle graphics library.
Edit the code to make an angry red emoji face. Which other
emojis can you code?
57
Dog
My fav!
We will start this project by drawing a dog’s head. Circles
will make its face, eyes and
nose. The ears will be drawn
with thick lines. Extra code
will give it a body, legs and a tail – all made out of lines of
various thicknesses. Because
this is a long project, we will add comments that will show up in
red. This will make the code easier for you to follow.
HOW THE CODE WORKS
Start by setting the background to light blue.
Draw a brown dot to make the dog’s head.
Draw a white dot and a smaller black dot to be the left eye.
Move the turtle to the right and draw the right eye.
Set light brown,
move down and add a dot to be the muzzle.
Move up a little and add a small black dot to be the nose.
Move left and draw a dark brown line to show the left ear.
Finally, move to the right and draw the right ear.
Click the Options menu and show the line numbers.
Make a new file
Start up IDLE or click File > New File.
58
Enter this code
Import the turtle graphics library.
Stop the turtle drawing lines.
Set the colour mode to use values from 0 to 255.
Add a comment in the code to show where the head is drawn.
Set the colour for the dog.
Start by drawing the head.
Add a comment to show where the left eye is drawn in the code.
Pick white.
Move up a little and to the left.
Draw the outer part of the eye.
Choose black.
Draw the pupil (the centre of the eye).
Show where the right eye is drawn in the code.
Pick white.
Move up a little and to the right.
Draw the outer part of the eye.
Choose black.
Draw the pupil.
Make a comment that the code draws the muzzle next:
Move to the centre and down a little.
Set a light brown colour.
Draw the dog’s muzzle.
The nose is drawn next.
Move just below the centre.
Pick the black colour.
Draw the nose.
Now, draw the left ear.
Set the line width to 40 pixels.
Position the turtle to draw the left ear.
Set the colour to dark brown.
Get ready to draw.
Point the turtle downwards.
Draw a line to make the left ear.
Stop drawing again.
Make a comment to say the right ear is drawn next.
Set the line width to 40 pixels.
Position the turtle to draw the right ear.
Set the colour to dark brown.
Get ready to draw again.
Point the turtle down.
Draw a line to make the right ear.
The hash symbol is used to
write comments on a line.
The hash
sign lets us make comments or notes in our code.
Comments make code much easier to read, fix or change.
59
Save your file
Click File > Save.
Type dog as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your work
The Turtle Graphics window should appear with an image of a
dog, like this:
Check for errors
If it doesn’t work properly, check your code carefully. If things
aren’t in the correct
place, check you haven’t left out any minus signs.
Then, save and run your code again.
If the head looks okay then you can try to give the dog a body, legs and a tail.
About time!
Start by drawing a thick line to be the body.
Draw the first leg down to the right.
Add the second back leg.
Make a thinner line to be the dog’s tail.
Move the turtle to
the front of the body and draw one leg.
Then, finish with the final leg.
We need to
draw the body before we draw the head.
Make some space
Click the cursor at the end of line 1. Press Enter a few times to
make some space.
Press Enter.
This will give
us room to type in the code for the body.
60
Add legs
Import the turtle graphics library.
Set the colour mode to use values from 0 to 255.
Stop the turtle drawing.
Set the colour for the dog’s body (slightly darker).
Make the line very wide.
Move to just below where the head would be in the middle.
Get the turtle ready to draw.
Draw the body across to the right.
Make the line thinner for the legs.
Move down to draw the first back leg.
Move back up to the body.
Draw the other back leg.
Set the thickness for the tail.
Move the turtle to where the tail will start on the dog’s body.
Draw the tail.
Stop the turtle drawing.
Set the thickness for the legs.
Move to the front of the body.
Make the turtle ready to draw.
Draw the first leg.
Move back up to the body.
Draw the other front leg.
Stop the turtle drawing.
Move the turtle back to where the head will be added.
Save and run
Save the changes and run your new code.
Click File > Save.
Click Run > Run Module or press F5.
View your dog
The graphics window should appear again. The dog should
now have a body, legs and a tail!
Challenges
Make some changes to how the dog looks. Change its colour or
how long its legs are.
Change where dog is looking by moving the pupils (black circles)
to one side.
Give the dog some spots! Can you draw any other animals?
61
FUNCTIONS
In this section we will look
at how we can create our own commands in Python. This is called
creating a function or procedure.
This makes life much simpler. If you want to draw a flower, you
can just type flower and one
will appear. The catch is, you have to teach Python how to
draw a flower first…
Why not just copy and paste?
If you wanted to draw lots of different-sized squares, you could
just copy and paste your code over and over again.
But if you wanted to draw a pattern with 20 different squares,
your code could easily be hundreds
of lines long!
It’s really hard
to find a bug in a long piece of code like this one!
Functions use less code
If you made a function to draw a square, your code would be
much shorter.
Functions also make your code much easier to read and fix.
Functions are more flexible
You can make functions do different things, by giving them
parameters.
Parameters are a bit like variables.
62
Defining a function
Before we use a new command, we need to define it.
Start defining the square.
Repeat the following commands four times:
Move forward 200 steps.
Turn left 90 degrees.
def is short for define.
Python will use
the definition to draw a square.
Using the function
Just type square() to run the new function.
Run the function and draw a square.
This is known
as “calling” the function.
Adding a parameter
We can adapt the function so that we can draw a square that is
any size!
The size parameter is introduced here… …and used here.
To use the function, type a number between the brackets.
300 gets used instead of “size” when the function is used.
RECURSION
Sometimes, functions call themselves. This makes the function run over and over again until
something happens, such as one of the parameters getting too small. This is called recursion.
On pages
68-69 you will learn how to make a spiral by using recursion.
FUNCTION OR COMMAND
The things you type in Python to make something happen are called commands. We make
our own commands by creating functions.
Some coders call functions procedures, and commands can be called statements!
Try coding the
projects on the next
few pages – it will
make more sense!
PARAMETER OR ARGUMENT
A parameter works in a very similar way to a variable.
Strictly speaking, a parameter is called an argument or value when the function runs.
63
Square Function
We can use copy and paste to
reuse code. But this can make
your programs very long! It also means you need to make
multiple changes to each part of your code if you want to change
something.
In this project, you will learn how to create your own code words
to do particular tasks. In coding this is called creating a
function.
Functions are
a great way to keep your code organised and easier to read.
HOW THE CODE WORKS
There is no command in Python to draw a square – so we will create our own!
Every time we type square, the turtle will draw a square. We will give it some information
about the size, position and colour of the square.
This value will tell the turtle the x position of the square.
This value will set the square’s
y position.
This sets how big the square will be.
The colour of the square is set here.
Python will look through your code for an explanation of how to draw
a square.
We will use the command def to define a square.
Each time the square command is used, Python will look at this part of the code to work out
how to draw the square.
Make a new Python file
Start up IDLE or click File > New File.
Switch on the line numbers
Click Options >
Show Line Numbers.
64
Define a square
Type in this code to define a square:
Import the turtle graphics commands.
The following lines define the square function:
Set the colour of the square.
Stop the pen drawing.
Move the turtle to the coordinates (x,y).
Get the pen ready to start drawing.
Tell the turtle to fill in the next shape drawn.
Repeat the following lines four times:
Move the turtle forward, according to the size value.
Turn the turtle left 90 degrees.
Fill in the shape that has been drawn.
Save your file
Click File > Save.
Type squares as the file name.
Click Save.
Our code has taught Python how to draw
a square.
But nothing will happen if we run the code, as we haven’t used our new square command yet.
Use the square command
Now, add these lines to your code:
Leave a blank line to make it easier to read.
Draw a large red square.
Draw a medium-sized purple square.
Draw a very big yellow square to the left of the others.
Change this part
of the code to make your own pattern
or picture using squares.
Save again
Click File > Save.
Run the code
Click Run > Run Module.
(or press F5)
Check for errors
If the code doesn’t work, go back and check through your
code.
Check all lines are indented by the correct amount. Save and
run your code again.
Challenges
Try to make some of these patterns:
65
Flower Function
On pages 50-51 we made a simple program to draw one flower. In
this project, we will extend this idea and create
a function to draw a flower. We will give the funcEach time we
tion parameters so that we can
set each flower’s position
and colour. Finally, we will
add a loop that will use the function to quickly draw 20
randomly-positioned and coloured flowers.
HOW THE CODE WORKS
We will start by making a command to draw a flower.
Each time we type flower, the turtle will draw a flower.
These values will set the x and y position of the flower.
This value will set the colour of the petals.
1
Python will look through your code for an explanation of how to draw
a flower.
The command def will define a flower.
Every time the flower command is used, Python will use this part of the code to draw the
flower.
A loop will keep drawing flowers. Each one will have a random x and y value
to place it in a random place, and be given a random colour from a list.
Make a new file
Start up IDLE or click File > New File.
Show line numbers
Click Options >
Show Line Numbers.
66
Start coding!
Type in this code:
Import the turtle graphics library.
Import the random commands.
Define the flower command.
Lift the turtle up so that it stops drawing.
Move to the coordinates (x,y).
Put the turtle down, ready to draw.
Set the line width to 5.
Point towards the top of the screen.
Choose green to draw the stem.
Draw a line to be the flower’s stem.
Make a loop that runs five times.
Set the line width to 25.
Turn right 72 degrees.
Set the petal colour using pCol.
Draw one petal.
Move back to the centre of the flower.
Pick the black colour.
Draw the centre of the flower.
Set the turtle’s speed to fast.
Draw a light green background.
Make a list of colours for the petals.
Repeat these lines 20 times:
Pick a random x and y value between -300 and 300.
Draw a random flower.
The indentation
at the start of each line is very important in this project.
Turn 72 degrees
for each of the
five petals, because 72 x 5 makes
360 degrees.
Save your file
Click File > Save.
Type flowers as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
Flowers!
Your screen should start
to fill up with random flowers!
Check for errors
Go back and look through your code carefully.
Pay close attention to the indentation of each line.
Challenges
Change line 26 to draw more flowers.
It draws a line
115 steps long
then turns
45 degrees. It calls drawSpiral(110).
drawSpiral(110)
This draws a line 110 steps long then turns right 45 degrees.
The function keeps recurring until…
drawSpiral(10)
…a short 10-step line is drawn. The side length is not greater than 10 so the function stops.
Make a new file
Start up IDLE or click File > New File.
Show line numbers
Click Options >
Show Line Numbers.
68
Start coding!
Type in this code:
Import the graphics library.
Define the drawSpiral function
Draw a line, as long as the value of the side variable.
Turn right 45 degrees.
If the value of the side variable is greater than 10 then:
Run the function again, with a shorter side length.
Pick the orange colour.
Set the width of the line drawn.
Draw a spiral, starting with a side length of 120.
Keep an eye on
the indentation in this code. It needs to be perfect!
Save your file
Click File > Save.
Type spiral as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your code
The Turtle Graphics window will appear and your flower will be
drawn.
Check for errors
Not working? Go back and look through your code.
Make sure lines 4, 5 and 6 are indented, and that line 7 is
double-indented. All other lines should not be indented.
Click File > Save and run your code.
Challenges
Change line 12 to draw different-sized spirals. Change their
colour and line thickness.
What happens if you turn by a different angle in line 5 or use a
bigger number in line 7?
69
Recursive Squares
The pattern in this project
is created by drawing a
number of different coloured squares. A recursive function is
used to make each square slightly smaller than the previous one
and to position it correctly. The function also swaps the colour
each time
a square is drawn. Once the square gets small, fewer than 20
steps, the function stops.
HOW THE CODE WORKS
Let’s see what happens if we start our pattern with a blue square,
80 pixels wide.
drawSquare(0,0,80,'blue')
Change where the next square gets drawn by editing line 17.
71
Recursive Tree
Recursive patterns can be found in nature. This project uses
recursion to draw a tree. We will define a function that draws a
branch of a tree. At the end of the branch, the function will
call itself again. Each time the function gets called, it will tell
Python to make a smaller branch in a different direction. We
will use random numbers to make
the tree look more realistic.
HOW THE CODE WORKS
How long it will be in pixels.
Our drawBranch function will use these values.
Where to start drawing the branch.
The angle it will be pointing (in degrees).
The function starts by drawing the tree trunk (actually, a branch going up).
After the trunk is drawn, the function calls itself to draw two more slightly smaller branches
at the end of the trunk.
Two more branches are drawn at the end of each of the first two. The random command
makes each branch slightly different.
Another two branches get added at the
end of each branch. Because they have
got quite small, the function stops.
Make a new file
Start up IDLE or click File > New File.
Show line numbers
Click Options >
Show Line Numbers.
72
Start coding!
Type in this code to draw the tree:
Import the turtle graphics commands.
Import the random commands.
Define the function to draw a branch.
Stop the turtle drawing as it moves.
Move the turtle to the coordinates (x,y).
Point it in the direction stored in the deg parameter.
Get the turtle ready to draw.
Move forward the number of steps set in size.
Find the current x value and store it in x1.
Get the current y value and store it in y1.
If the size of the branch is bigger than 5, then:
Pick a random angle for a branch going left.
Pick a random value for a branch going right.
Choose a random size for the left branch.
Pick a random size for the right branch.
Call the function to draw the left branch.
Call the function to draw the right branch.
Set the turtle to draw quickly.
Start drawing the tree with a branch 100 pixels long, pointing up.
The values given to
a function (inside the brackets) are called its parameters.
Save your file
Click File > Save.
Type tree as the file name.
Click Save.
Run the code
Click Run > Run Module.
(or press F5)
View your code
The Turtle Graphics window will start up.
Your tree will
be drawn, one branch at a time.
Not working?
Check all the lines are indented correctly. Any mistakes here
will stop your code working.
Make sure all the calculations in lines 13 to 16 are typed
correctly.
Experiment with
the code so far. Can you change the height of the tree?
73
Edit your tree code
Now, add a
loop to draw a whole forest
of trees!
Add some more trees by editing the end of your code so that it
looks like this:
Make the turtle work fast.
Repeat the code below five times.
Set the position of the next tree in a variable called x.
Start the next tree by drawing a trunk.
Save and run
Click File > Save.
Click F5.
View your code
Your forest will start growing
in the Turtle Graphics window.
Add colour and thickness
Click at the beginning of line 8 and press Enter twice. Add
these extra lines of code:
Set the thickness of each branch.
Set the colour of the tree branch.
This will make
the branches
thinner as they
get shorter.
Add leaves
Click at the end of line 20 and press Enter. Add these extra
lines of code:
Else if the size is 5 or smaller, then:
Set the colour mode.
Pick a random shade of green.
Draw a leaf.
Save and run
Click File > Save.
Click F5.
View your code
The trees will now be redrawn with leaves.
Make sure the else command is indented in line with the if command in line 12.
Challenges
Add more trees.
3. Instead of drawing a black dot, change your code so it draws three different-
coloured dots. Each dot needs to get smaller – a bit like a small version of the
code on page 6.
Experiment with
the colour and size of the dots.
Hexagon pattern
1. Type in the code for the square pattern on pages 12-13.
3. Change the loop on line 8 so that it repeats six times – as there are six sides
on a hexagon.
2. Make a list called col that contains all the colours you want to use.
3. Create a loop that will draw 100 squares. Give each one a random x and y
value and a random size and colour. See
Step 3 on page 65 for help
with that.
If you complete this challenge, try doing it with another shape – maybe hexagons?
RGB hoops
1. Find the code on page 33 that draws random coloured hoops.
It uses a list of four colours to make the pattern. Adapt the code so that it
picks a random colour using the RGB system.
3. Use the code at the bottom of page 35 to pick random numbers for R, G and B.
Use these values
to set the colour.
3. Delete the pu (penup) command. You may need to add it in later somewhere
else.
Combined picture
I’m seeing stars!
1. Combine together the code from several projects to make a picture.
2. Start by setting a background colour, then bring in some trees from the
project on pages 72-74.
3. Add a square function (from page 64) and draw a large green square very low
down to make the grass. It can overlap the bottom of the trees.
4. Add the code to draw some flowers from page 67. You will need to change the
code to make the flowers smaller.
for n in range(4):
def
if
else
x=5
col=['red','blue']
Load the code in the turtle graphics module.
Define a function.
turtle.begin_fill()
turtle.bgcolor('red')
turtle.color('red')
turtle.color(255,0,0)
turtle.colormode(255)
turtle.dot(50)
turtle.end_fill()
turtle.goto(50,30)
turtle.speed(0)
turtle.width(20)
Move the turtle back 30 pixels.
random.uniform(0.5,1.5)
random.choice(col)
Pick a random integer (whole number) between 1 and 6.
79
Glossary
Algorithm A set of rules or steps to make a game or
program work.