Coding Club Python Basics - Chris Roffey PDF
Coding Club Python Basics - Chris Roffey PDF
Clubng
Python
Basics
cambridge university press
Cambridge, New York, Melbourne, Madrid, Cape Town,
Singapore, São Paulo, Delhi, Mexico City
www.cambridge.org
Information on this title: www.cambridge.org/9781107658554
A catalogue record for this publication is available from the British Library
Chapter 4: Functions 45
Chapter 5: MyEtchASketch 55
Appendix74
Acknowledgements82
Contents 3
Introduction
Why was this book written?
This book is the first in a series of books for anyone with little or no knowledge of computer
programming but who would like to give it a go.
But my wish to produce a series of short books on coding goes back much further than that.
When I grew up, computers were very different from the PCs we use today. To play a game or
use a word-processor, you had to run the program by typing green text into an empty black
screen. But the great thing was, you could also type in your own commands and run them! It
was not long before I had written my first text-based game in a language called BASIC.
Introduction 4
Later on, I wanted to learn a more modern language, and set about teaching myself Java. I
read four or five books and completed the examples, but at the end of each one I was left in
a dreadful situation: I had all sorts of ideas for programs I wished to make, but still no idea
how to start! I could make the exciting projects that were the focus of these books, but not
much else. So with this series of books, I have taken a different approach. I hope it will teach
you the skills you need to write any program you can imagine – eventually – and many
simple programs straight away.
I want you, the reader, to learn not only how to make the programs in this book but also how
to design your own. I want you to be able to write programs well, so that if you take it further
and become the inventor of the next Google you will not have to unlearn bad programming
habits. Unlearning things, I should add, is a lot more difficult than you might imagine.
There are four ways in which this book tries to help you to learn:
1 By copying the code – this is important as it gets you to work through the code a line at a
time (like computers do) and will help you remember the details in the future.
2 Finding and fixing errors – error messages in Python give you some clues as to what has
gone wrong. Solving these problems yourself will help you to be a better programmer.
In the end though, this should not become boring, so if you get stuck the code can be
downloaded from the accompanying website.
3 Experimenting – feel free to experiment with the code we write. See what else you can
make it do. If you try all the challenges, puzzles and ideas, and generally mess with the
code, this will help you learn how to write code like a professional.
4 Finally, this book will not only provide the code to build some cool, short projects but
also teach you how the programs were designed. You can then use the same methods to
design your own applications.
Introduction 6
A word of warning
You may be tempted to simply get the code off the web site instead of typing it yourself. If
you do this you will probably find that you cannot remember how to write code so easily
later. You will only be asked to type small chunks of code at a time – remember that this will
help you understand every detail of your programs.
You will also become a faster typist, which is a very important skill these days!
Introduction 7
Chapter 1
Python, IDLE and your first program
• learn about computer programming and the different languages that you can use
• learn how to use IDLE, which will help organise your programs and allow you to run
them easily
Computers and coding have not been around for a long time but they have sure packed in
some interesting history in a short space of time. The first machine that stored instructions
in a way that future computers could take advantage of was the Jacquard loom that used
holes punched in cards and was invented in 1801. Charles Babbage is often credited with
inventing the first computer which he described in 1837 but was not built until 100 years
later. In 1989 Guido van Rossum started to create the Python programming language which
he named after Monty Python’s Flying Circus, a BBC comedy sketch show.
Programming languages
There are many programming languages currently used by coders around the world. Some
are best in one situation, others in another.
Once you have learned one modern programming language, you can quickly learn others.
You simply have to find out how your new language handles variables, loops, etc. (You will
know what these are by the end of the book.)
Python
Python is a typed computer language. This makes writing short programs very fast and you
can produce almost anything you can imagine.
IDLE
You will start programming in IDLE which comes with Python. IDLE is a special text editor
like Microsoft Word, except it understands Python and helps you get your code right. IDLE is
itself, a Python application.
The code you want to run is typed after the special entry prompt:
To run the code we press the return key. This is how Python runs in IDLE’s interactive mode.
Python can run files as well but to start with, this is all we need.
A great reason for learning Python and using IDLE as our IDE (Integrated Development
Environment) is that it is very similar on all the different types of computers available.
The text before the >>> prompt is unimportant at the moment. However, it is always useful
to know what version of Python you are using.
Hello World!
Since the dawn of programming, when the first cave-coders booted up their cave-computers,
it has been a tradition that your first program when learning a new language is ‘Hello
World’. The aim is to try to make the computer say ‘hello’ to the world. If you can do this
you will have tested whether everything that was set up for you is working properly.
• After the >>> prompt write in the code from Code Box 1.1 and then press your return
key to run the program.
Hello World!
Colons, brackets, speech marks, apostrophes and spelling of Python words have to be just right.
Although we can read imperfect sentences, computers cannot.
Whether or not you got any errors, try this Quick Quiz.
Quick Quiz 1
Which of these lines of code are correct?
1 Print("Hello world!")
2 print("Hello world!")
3 print(Hello world!)
4 print "Hello world!"
Notice how the coloured text helps you spot code that is not going to work. All the code
listings in this book use the same coloured text as in IDLE’s standard display. This should
help you to spot bugs in your code.
Idea 1
1 Write some new code so that a short message is displayed that says thank you to
whoever got everything ready for you.
2 Run your new code to display the message.
3 Now show them your message. This will make them happy.
Idea 2
1 Write some code so that the computer will show the text for a joke.
>>> print("Question: What goes clip?")
Question: What goes clip?
>>> print("Answer: A one legged horse")
Answer: A one legged horse
>>>
Chapter 1: Python, IDLE and your first program 15
Chapter 2
Some text, some maths and going loopy
If you have not pressed your return key yet, to see what happens, do so now.
Backslashes
Are you a bit confused about the last two escape sequences? If so, type in and run the code
from Code Box 2.2.
Try typing in the code from Code Box 2.3 to see how to avoid having to escape speech marks.
This takes advantage of the fact that you can choose whether to surround strings in double
speech marks or single ones. Watch out though, you will get a lot of syntax errors if you do
not do this carefully.
Functions
print()is called a function (these are covered in chapter 4, page 53). What print()
will do, is print anything you throw at it inside the brackets. They must be separated by
a comma, and strings (bits of text) must be put in speech marks. Everything inside the
brackets will be printed out in order. The results from sums can also be output, but you must
not put the calculations in speech marks. What do you think would happen if you left in the
speech marks? Don’t forget you can also add in escape sequences.
Maths
Using Python as a calculator is easy, if you remember two things:
>>> 11/4
2.75
>>> 11//4
2
>>> 11%4
3
>>>
0
Quick Quiz 2
Can you work out what the output from this code will be?
>>> print("11 divided by 4 also equals: ", 11//4, " remainder: ", 11%4)
Imagine you were trying to write some code in a History lesson at school, when you should
be doing History. Your teacher might ask you to write fifty lines. Well no matter, Python can
do that.
Try opening IDLE in interactive mode and then enter the code in Code Box 2.4. You will need
to press return twice at the end.
To start with we create a variable and assign a value to it. A variable is a space in the
computer’s memory where we can store, for example, a string or an integer. We create a
variable by naming it. In Code Box 2.6 we called our variable ‘number’ and with the equals
operator we give it the value ‘1’.
The next line of code >>> while number<101: says ‘while the variable called number is less
than 101 do the following’. All of the code that is indented after the colon is to be repeatedly
performed by the computer. That is, it loops through these two lines of code until number is
no longer less than 101.
The last line of code number = number+1 is in the loop. It keeps adding 1 to number for
number = 1
each passage through the loop. Don’t forget the variable’s value can be changed with the
equals operator at any time. number 1,
Delving Deeper
The equals sign is used differently to the way it is used in maths. In computing, the equals sign means ‘point
this variable name at this piece of data’ (an integer for example). So number=1 means ‘create a variable
called number and point it at the integer 1’. Another way of saying this is ‘assign the value 1 to the variable
number‘. Later we may assign another value to number.
There are several operators you can use in a while loop. Some examples are given in Table
2.3. Note how we now have another version of equals ==. This form is more like the equals
in maths. It is an example of a comparative operator. Therefore, while number==1:
means ‘while the variable called number is equal to 1, do the following’.
Operator Meaning
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Table 2.3 Comparative operators.
We use a double equals sign to compare two values and a single equals sign to assign a
value to a variable.
Puzzle 1
Write some code in IDLE so that the computer counts up to 20 in twos.
Puzzle 2
Write some code so that the computer outputs the 5 times table like this.
1x5=5
2x5=10
3x5=15
Hint: You will need a counter variable which you could call number. Then
you should find out how to write one line, and then make your loop do it 10
times.
>>> number=1
>>> while number < 101:
print(number)
number = number+1
In your new code, you are not allowed to use the less than operator <.
Instead you should use one of these comparative operators in each program:
<= > !=
You are going to build and save a Magic 8 Ball game. If you have not played with one of
these toys before, what you do is, ask the 8 Ball for some advice, shake it and it magically
responds.
print(“Welcome to MyMagic8Ball.”)
print(“shaking ...\n” * 4)
Try typing the code from Code Box 3.1 into your new script mode window. These are the first
lines of the MyMagic8Ball game.
(If you have a British Apple keyboard, you will need to hold alt and click the £ symbol to type #.)
Chapter 3: Readable code and the MyMagic8Ball game 29
Code Box 3.1
# MyMagic8Ball
import random
# write answers
ans1="Go for it!"
ans2="No way, Jose!"
ans3="I’m not sure. Ask me again."
ans4="Fear of the unknown is what imprisons us."
ans5="It would be madness to do that!"
ans6="Only you can save mankind!"
ans7="Makes no difference to me, do or don’t - whatever."
ans8="Yes, I think on balance that is the right choice."
Now you should save your work by choosing Save from the File menu. It is a good idea
to save all your code into a special folder which you can call – ‘Python Code’ – in your
documents folder. Call the new file myMagic8Ball.py.
The # symbol says to the computer, ‘ignore the rest of the text on this line, it is for
humans’. This is called commenting. You have typed in two comments so far.
A module is a Python file with special code that you do not have to write yourself but that
you can use. There are many modules available and it is also possible to write your own. So
import random brings in to your application a selection of functions that you can use later
in your program. (Chapter 4 is all about functions.)
String variables
The last 8 lines of code are the variables where you store some strings (bits of
text) that will be used later in the game. At this early stage you may be asking Delving deeper
yourself, how do I know what to call my variables? Well within reason you can
call them what you like. There are only 31 reserved words in Python. There are 31 Python words that you cannot
use as your own variable names. These are:
and as assert break class continue
Python does not require semicolons or curly brackets. Semicolons can be very annoying as
they are easy to forget and if you do forget one, your program will not run at all.
In Python, each line of code simply requires that you have a line ending. This is a lot easier
to spot if you do manage to forget!
To group lines of code together you indent the code (four taps on the space bar). However
IDLE will usually know when you should indent and do it for you when you press return!
This indenting produces ‘white space’. The code is grouped according to how you arrange the
white space. This is how the same code would look in Python.
class Lift():
current_floor=0
def getFloor():
return current_floor
def moveToFloor(floor_number):
current_floor = floor_number
Python code. Chapter 3: Readable code and the MyMagic8Ball game 32
Delving deeper
There are other differences to note. Java has a lot of extra words like public, private, int and void. This is
because it is a very strict language where everything has to be carefully defined. Python instead, will usually
work out whether something is an integer (number) or string (text) for the programmer. Both languages have
their advantages and disadvantages.
Classes are not dealt with in this book but we do have to use some for our final project in chapter 5. You will
learn about the def keyword in the next chapter!
Python code with too many comments. Chapter 3: Readable code and the MyMagic8Ball game 33
As you can see, it is possible to add too much commenting! Sometimes simply naming things
well is much better. The names chosen by the programmer here include Lift,
current_floor, getFloor, moveToFloor and floor_number. The only Python code words
are class and def.
Naming variables
If you want to store a number or some text somewhere you do so in a variable.
Variables should always be named with descriptive names. You should always start with a
little letter. You can separate words with underscores like this my_own_variable.
• By combining print() with input() you can make up for input’s inability to handle
complicated combinations of strings and maths. See if you can work out how. (Hint:
Just use input() on its own, after a complicated print() function.)
After your eight variables in myMagic8Ball.py, miss a line and type in the code from Code
Box 3.3.
A simple dice
To create a dice requires only one line of code in interactive mode.
>>> random.randint(1, 6)
We have to put random. before randint() to tell the computer that this function can be
found in the random module. The two arguments are the start number and the end number.
The function randomly chooses 1, 2, 3, 4, 5 or 6. Try it out a few times in interactive mode to
see it in action.
(Hint: You can save yourself a lot of typing by copying and pasting. Remember that
whenever you do this, it means there is probably a better way of writing your code!)
if
choice == 1:
answer = ans1
The first line says, ‘if the value of choice is equal to 1, then run the code that is indented
after the colon.’
Notice how the comparison operator == is used, in the same way as it was with the while
loop in chapter 2.
The random generator randint(1, 8) may not have produced the value 1 though, so
if
the next bit of the code handles the situation if choice equals 2:.
if
elif choice == 2: else elif
answer=ans2 else
So in this case answer would hold the string, "No way, Jose!".
This continues until the application handles all other situations with else:.
In your program this means if the choice is 8.
else:
answer=ans8
The input() function is used twice in this program. The first time, it takes the
user input and stores it in a variable called question.
Do you remember how the user’s input is not actually required? What this line of code does
do, is wait until the return key is pressed and stores the input just in case we decide to use it
some other time.
This line does not even bother storing the user input at all. It just supplies two line returns
and a message to say the game is over. The program again waits for the user to press the
return key and then finishes.
This is much better than suddenly finishing the game unexpectedly and you will see it used
a lot from now on.
You have entered all the code for this program now. If you have not saved it, do so now and
then check it against the complete listing in Code Box 3.5.
You have worked hard and learned a lot in this chapter. It is time you experimented a bit!
Idea 1
ry out the game on some friends or relatives. (Hint: Make sure they cannot see the
T
code, as this will ruin the game.)
Idea 2
Change the eight string variables to answers you want your Magic8Ball to say.
There are several ways to do this. An example answer can be found on the Coding Club
website.
Chapter 4: Functions 45
Functions
You have already met and used a few functions. The first one you used was print().
Functions have brackets after their name. This is where we supply arguments separated by
commas. Some functions do not need them, they do their jobs without argument!
There are many functions that are built in to Python that we can already use. We can also
make our own. We create functions with the def keyword. Here is the code for a
counting function.
In interactive mode, type in the above code. You will need to press return twice
to get back to the Python prompt. Then type count(10) and press return.
Chapter 4: Functions 46
Delving deeper
An infinite loop can be created by running a while loop that never stops. This is not a good
thing! It usually means you have made a mistake.
You may get into a similar situation if you try playing with the count() or the
times_tables() functions later in this chapter.
If your program keeps running and will not stop just close the window. Python will ask if you
want to kill the program. Don’t be scared … kill it!
(Sometimes simply holding ctrl and pressing the c key will work better.) 1 × 12 = 12
2 × 12 = 24
3 × 12 = 36
4 × 12 = 48
Times tables anyone? 5
6
×
×
12
12
=
=
60
72
To get Python to produce any of the times tables is easy, with a while loop. However, if we
want to be able to quickly choose which times table we want, then it is probably easier to
write a new function rather than keep hacking your code.
We need to supply a value that indicates which times table we want. This is a number so we
could call this argument num:
def times_tables(num):
Now we need to produce a while loop. But first let’s work out the code for one line of the
table e.g. 2 × 12 = 24 . To do this the 2 is a counter which we will use in the while loop
(Simply use n, not all variable names have to be descriptive!). The 12 is num and the 24 is
Chapter 4: Functions 47
obtained by multiplying n by num. The rest is just text. We can put all this together into one
print statement.
Quick Quiz 3
Which of these produces the output we want?
1 print(n, " x ", num, " = ", n*num)
2 print(num, " x ", n, " = ", num*n)
3 print(n, " * ", num, " = " n*num)
Using IDLE’s interactive mode, type in and think about the code in Code Box 4.1. Don’t
forget to press return twice to get back the Python prompt. Nothing should happen yet – all
will be revealed shortly.
Chapter 4: Functions 48
To run this code and output the 12 times table, type the code from Code Box 4.2
and press return.
If all goes well you should have a screen that looks like this:
>>> times_tables(12)
1 x 12 = 12
2 x 12 = 24
3 x 12 = 36
4 x 12 = 48
5 x 12 = 60
6 x 12 = 72
7 x 12 = 84
8 x 12 = 96
9 x 12 = 108
10 x 12 = 120
>>>
Times tables.
Chapter 4: Functions 49
What if you prefer to have your times tables twelve lines long, so that you get
12 x 12 = 144. Now you have to go back and edit the function. This could become
tiring in interactive mode and a small annoyance if your function was saved times_tables()
as a Python file. Let's try re-writing the function so that it takes two arguments
instead. Still in interactive mode, try entering the code in Code Box 4.3 and you
will see the power of functions. Enjoy! times_tables(num):
Chapter 4: Functions 50
Code Box 4.4
# myNumber.py
# This game uses a home made function
import random
# Think of a number
computer_number = random.randint(1, 100)
There are two new things to you in this game. The return keyword tells the is_same()
function what value should be sent back after it is called. We know functions can be sent
arguments, well they can also return data.
In this case it returns the value stored in the variable result. So, if the two numbers are the
same it returns the string Win, if the supplied number is higher than the target, the function
returns the value High and if the supplied number is lower than the target, Low.
The second new thing to you is converting the user’s input into an integer by wrapping it in
int( input goes here ). This is because anything coming from keyboard input is received
as strings. The process of converting one data-type into another data-type is called casting.
Have you remembered to save the file to your Python Code folder? If so, you can run it by
choosing Run Module from the Run menu or pressing F5.
Chapter 4: Functions 52
Chapter summary
In this chapter you have learned:
You have worked hard and learned a lot about functions in this chapter. Here are a few ideas
that you may enjoy. There are several ways to do them. Examples can be found on the web site.
Idea 1
• Put the code from Code Box 4.3 into a script mode file called times_tables.py.
• Add some user interaction so that it asks which table you want and how far it should go.
• Do not forget to add a line of code to stop the program nicely.
Now you have a times table app you can use whenever you want.
Chapter 4: Functions 53
Idea 2 Idea 4
ake a copy of
M A harder challenge is to get the myNumber.py game to offer a choice of levels.
myNumber.py and • Easy: choose from numbers between 1 and 10.
then add some code • Medium: numbers up to 20.
to make it count and • Hard: numbers between 1 and 100.
display how many This can be split into a number of shorter tasks.
guesses it took the 1 Ask the user what level they would like to play and collect and store the new
player. (Hint: you will input as "e", "m" or "h".
need another variable 2 Add the following code to catch any input we do not want the user to enter.
which you could call
counter.) while level != "e" and level != "m" and level != "h":
level = input("Sorry. You must type in one of the
letters 'e', 'm' or 'h'\ne/m/h:")
3 Use if, elif and else to sort out the upper limit and store the result in a
Idea 3 suitable variable.
4 Move the code where the computer thinks of a number, to below this section and
Make the insert your upper limit variable in place of the appropriate argument.
myNumber.py game 5 Adjust the print() function below the # Start the game comment so that it
easier for younger outputs the correct information.
children by reducing 6 Adjust the code so the output all looks nice.
the range of numbers
between 1 and 100 to
between 1 and 10.
Chapter 4: Functions 54
Chapter 5
MyEtchASketch
In this chapter you are going to:
Chapter 5: MyEtchASketch 55
The tkinter library
In the previous chapters we saw how to import a module. A module is a file that gives us
access to a number of functions we do not have to write ourselves. So far we have used the
random module.
We are now going to import a whole library of modules that give us access to graphical
functions, such as the ability to make a window and a canvas to draw on.
As there are a number of modules we simply import them all like this.
The asterisk means everything. It is not being used as a multiplication symbol here!
As tkinter uses classes (which we are not learning about in this book), some of
the code looks a bit strange. Do not worry about it. This is an introductory book.
You can learn about classes later. The term Canvas() for example takes its
arguments in a different form because Canvas is a class. Also notice it starts with
a capital letter.
We are going to make a window that is 600 pixels (dots on the screen) wide and
400 pixels high with a canvas we can draw on. In our case the canvas is black.
We do this using the code from Code Box 5.1. First we must open a new file in
script mode and type it in.
MyEtchASketch in a window.
Then save it as myEtchASketch.py
Chapter 5: MyEtchASketch 56
Code Box 5.1
# myEtchASketch application from Coding Club: Python Basics
##### main:
window = Tk()
window.title("MyEtchASketch")
canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0)
canvas.pack()
window.mainloop()
You can try running myEtchASketch.py now. Although it is not very exciting, it is the
first time you have made a window! Notice how something also happens in the interactive
mode window. This is now acting as a console where we will get, among other things, error
messages.
Chapter 5: MyEtchASketch 57
The plan
Now that you have a window in which to make your application and a canvas to draw
on, it is time to start planning the rest of the application. To do this we break down the
task into functions. First we need to be able to draw a vertical line a bit at a time and then
horizontally. As these are going to be controlled by the up, down, left and right arrow keys
on the keyboard it makes sense to have four functions that are all going to be similar and
then attach those functions to the keys. So to start with, let’s just try and create a function
that draws a line up when we press the up key. If we can achieve this we know that we will
be able to complete this project.
The coordinates
Unlike in maths, tkinter and most computer languages use coordinates that count from the
top left of the screen. So our canvas looks like this.
(0, 0) (300, 0)
Chapter 5: MyEtchASketch 58
So a point on the screen is represented by two numbers:
e.g. (100, 50) = a point 100 pixels along the x-axis and 50 pixels down the y-axis.
The functions should come next. They need to be before the main section that runs your
application. That way it can use them! Therefore the code from Code Box 5.1 has been split
in Code Box 5.2 to make room for all our functions.
You can add the new code to your myEtchASketch.py file now. It will not do anything
different yet. How the function works will be explained in the next analysis section.
Chapter 5: MyEtchASketch 59
Code Box 5.2
Code Box 5.2
# myEtchASketch application from Coding Club: Python Basics
p1_x = canvas_width/2
p1_y = canvas_height
p1_colour = "green"
line_width = 5
line_length = 5
##### Functions:
# player controls
def p1_move_N(self):
global p1_y
Chapter 5: MyEtchASketch 60
Code canvas.create_line(p1_x,
Box 5.2 p1_y, p1_x, (p1_y-line_length), width=line_width, fill=p1_colour)
p1_y = p1_y - line_length
##### main:
window = Tk()
window.title("MyEtchASketch")
canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0)
canvas.pack()
window.mainloop()
Chapter 5: MyEtchASketch 61
The variables
Instead of adding lots of squares to make our lines, the code is simpler if you draw lots of
little lines. You make a square by setting the line_width equal to the line_length. This
works well because a line has a beginning and end coordinate, which is just what we want to
keep track of. The variables are listed in Table 5.1.
p1_move_N(self) is going to be a function that sends the line drawn by player 1 up the
screen.
Chapter 5: MyEtchASketch 62
self
As this uses methods from tkinter, this function has to be supplied with the argument self.
This is to do with tkinter’s methods being in classes. Functions in classes are called methods.
(Remember though, that we are not covering classes in this book.) For now, just always
supply self.
global
At the start of our script, we declared all our variables and gave them some default values.
As they are outside any functions, they are global variables. This means that they are
available throughout the program. However, any variables declared inside a function are
called local variables, which means that they are not available outside their function and
will be lost when the function call is over. As we want all our functions to use our global
variables we have to tell the function this, by re-declaring them inside the function, using
the keyword global. This is only required if the function is going to change the variable. By
doing this the function is using the same variables as the rest of the program.
canvas.create_line(arguments go here)
The arguments required are shown in Table 5.2 on the next page.
Chapter 5: MyEtchASketch 63
Arguments required by tkinter Your supplied variables
x1 (x-coordinate of beginning of line) p1_x (current x-coordinate of player 1)
y1 (y-coordinate of beginning of line) p1_y (current y-coordinate of player 1)
x2 (x-coordinate of end of line) p1_x (current x-coordinate of player 1)
y2 (y-coordinate of end of line) p1_y – line_length (current y-coordinate of
player 1 minus the length of the line)
Table 5.2 Arguments required for MyEtchASketch to move north.
To draw on the canvas we create lots of little lines that always start with the same
coordinates that the last one ended with. This is easier than making little squares. Instead,
we draw green lines that are 5 pixels wide to match our line length. Thus, we need to supply
two more optional arguments to the create_line() method as shown in Table 5.3.
Chapter 5: MyEtchASketch 64
Optional arguments Your supplied variables
width line_width
fill p1_colour
Table 5.3 Optional arguments for MyEtchASketch.
As we are moving up the screen, it is only necessary to subtract the line length
from p1_y but you must add one more line of code to this function to store the
new p1_y position for next time.
If we wanted the a key we would supply the argument "a" but for the up arrow key
we give "<Up>".
window.bind("<Up>", p1_move_N)
Chapter 5: MyEtchASketch 65
Now add the code from Code Box 5.3 to your myEtchASketch.py file. When you
run this, if all is well, you will find that by pressing the up arrow on your keyboard
you can make a series of green squares 5 pixels wide by 5 pixels long.
window.mainloop()
Chapter 5: MyEtchASketch 66
Finishing off
Once you have movement upwards, you will find the other directions are easy to write code
for. To move down we add 5 pixels to our y-coordinate, to move right we add 5 pixels to our
x-coordinate and to go left we take 5 pixels from our x-coordinate.
Add the rest of the functions from Code Box 5.4 (this is the final step). Since we are repeating
this code so often, this should indicate that there is probably a better way of writing this
program. We will examine this in the activity section at the end of the chapter.
If you find your program does not run the first time; try to sort out any problems
yourself. If you do get stuck though, you can download the code from the
companion website.
Chapter 5: MyEtchASketch 67
Code Box 5.4
# player controls
def p1_move_N(self):
global p1_y
canvas.create_line(p1_x, p1_y, p1_x, (p1_y-line_length), width=line_width, fill=p1_colour)
p1_y = p1_y - line_length
def p1_move_S(self):
global p1_y
canvas.create_line(p1_x, p1_y, p1_x, p1_y+line_length, width=line_width, fill=p1_colour)
p1_y = p1_y + line_length
def p1_move_E(self):
global p1_x
canvas.create_line(p1_x, p1_y, p1_x + line_length, p1_y, width=line_width, fill=p1_colour)
p1_x = p1_x + line_length
def p1_move_W(self):
global p1_x
canvas.create_line(p1_x, p1_y, p1_x - line_length, p1_y, width=line_width, fill=p1_colour)
p1_x = p1_x - line_length
Chapter 5: MyEtchASketch 68
def erase_all(self):
canvas.delete(ALL)
##### main:
window = Tk()
window.title("MyEtchASketch")
canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0)
canvas.pack()
# bind movement to key presses
window.bind("<Up>", p1_move_N)
window.bind("<Down>", p1_move_S)
window.bind("<Left>", p1_move_W)
window.bind("<Right>", p1_move_E)
window.bind("u", erase_all)
window.mainloop()
Chapter 5: MyEtchASketch 69
Chapter summary
In this chapter you have learned:
This chapter provides us with many possibilities for ideas. As you have organised your
code well, the following Quick Ideas can be easily achieved by simply adjusting the
variables at the beginning of your file.
Quick Ideas
• Make line_length longer and see what happens.
• Change the colour a few times and find out what named colours tkinter supports.
• Generally change the square size to find a size that you like.
• Completely customise the code adjusting all the variables until you are happy.
Chapter 5: MyEtchASketch 70
Puzzle
Remember we said that copying and pasting indicates that there are better ways of coding.
This puzzle encourages you to write better code.
ake a new function called p1_move(x, y) so that the four movement methods can be
M
simplified to something like this.
def p1_move_N(self):
p1_move(0, -line_length)
There are several ways to do this. An example answer can be found on the website.
Also on the website you will find the code for a two-player game called
ourEtchASketch.py. If you are feeling keen, you could try to make it yourself – it is not
really very difficult and takes advantage of the better code structure from this chapter’s
puzzle. This two-player game is also fun for one player because it allows you to draw in two
colours. It also provides the opportunity to give you a few more extra ideas.
Chapter 5: MyEtchASketch 71
Extra ideas
• Download ourEtchASketch.py and try drawing something colourful.
• Look at the code and see how easy it was to make this into a two-player game.
• Try playing it as a timed competition to see who has the most squares visible at
the end. The object is to draw over your opponent as much as possible. (Hint: It
might be best to make the squares bigger.)
• Try playing a weird game of Tron. As there is no collision detection, you will have
to be honest about when you collide. (Hint: If you do not know what Tron is, ask
an adult.)
• Try making the canvas tall and thin and then having a race with a friend to the
top of the screen.
• Make the racing game more interesting by putting some obstacles in the way.
(Hint: draw some random-sized and coloured lines on the screen at the start just
before the code that binds the functions to the keyboard.)
Chapter 5: MyEtchASketch 72
Taking things further
When you have finished this book we hope you will want to continue to learn to code. Here
are some other places and resources that you might wish to look at.
More Python
Other books in the series, found at this book's companion website: http://www.codingclub.co.uk
PyGame Website: This site provides a set of modules that need to be downloaded that aid
with making games. It has a community of Python coding enthusiasts and enables you to
post your games for others to play.
Website: http://www.codingclub.co.uk
Here you will find answers to the challenges and puzzles at the end of chapters. The
complete source code for all the projects is also here.
Escape sequences
Escape sequence What they do
\n creates a line return in a string
\t creates a tab style indent in a string
\\ allows a backslash to appear in a string
\" allows a speech mark to be used in a string
Table A1 Escape sequences.
Appendix 74
Mathematical operators
Operator Name Example Answer
* multiply 2*3 6
/ divide (normal) 20/8 2.5
// divide (integer) 20//8 2
% modulus 20%8 4
+ add 2+3 5
- minus 7-3 4
w
Table A2 Mathematical operators.
Comparison operators
Operator Meaning
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Table A3 Comparison operators.
Appendix 75
End game code snippet
input("\n\nPress the RETURN key to finish.")
##### main:
window = Tk()
window.title("My Game Title")
canvas = Canvas(bg = "black", height = canvas_height, width = canvas_width, highlightthickness = 0)
canvas.pack()
window.mainloop()
import random
dice_number = random.randint(1,6)
Appendix 76
Glossary and index
argument
a piece of information that is required by a function so that it can perform
its task; usually a string or number, my_function(arguments go here) 36
bug
a piece of code that is causing a program to fail to run properly or at all 14
casting
the process of converting one data-type into another; e.g. sometimes a
number may stored as text but need to be converted in to an integer – this
can be done like this: int(“3”) 52
commenting
some text in a computer program that is for the human reader and is
ignored by the computer when running the program – in Python all
comments begin with a hash symbol # 30
comparative operator sometimes called logic operators, they allow us to compare data in a
program; they include == and > (others are found in Table 3 in the Appendix) 25
data-type
different types of information stored by the computer, for example floats,
integers and strings 52
default
a value given to an argument or variable as a starting point 63
Glossary and index 77
equals operator the equals sign is used to assign a value to a variable in coding, for
example n=2 assigns the value 2 to the variable n23
escape sequence when characters that have certain meanings in Python are required in
strings they have to be “escaped” so that the computer knows they do not
have their usual meaning; this is done by putting a slash in front of them e.g. \" 17
float
a number data-type that can have a decimal value 20
function
a reusable piece of code 19
hacking
taking some previously written code and re-writing bits to make it do
something different 47
IDE
stands for Integrated Development Environment; IDLE is an example of
one – they are special text editors with useful tools built in for programmers 12
IDLE
stands for Integrated DeveLopment Environment; this is the IDE that
comes with a normal Python 3 install 10
infinite loop a piece of code that keeps running forever; this is usually a bad thing 47
integer
a number data-type that cannot have a decimal value and must be a whole number 20
interactive mode this is when we use IDLE to try out snippets of code without saving them 12
loop
a piece of code that keeps repeating until a certain condition is met 22
mathematical operator an operator that performs some mathematical function on some numbers;
e.g. multiplication or addition 20
method
the name given to a function in a class 63
module
a saved python file whose functions can be used by another program 31
modulus
a mathematical operator that is used to return the remainder from a
division calculation; e.g. 22%7 returns 120
operator
a symbol that performs a simple function on some code such as
multiplying two numbers or comparing them to see if they are equal; see
also comparative operator and mathematical operator25
output
data that is sent from a program to a screen or printer, etc 13
return
(1) the value a function will produce after it has been run – it is also a Python
keyword; (2) the ‘end of line’ key on a keyboard, sometimes called the enter key 52
script mode this is when we use IDLE to help us write code that we will save in a file 29
string
text data, which can be stored in a variable 19
syntax error an error produced when a computer fails to run a program because it
cannot recognise the format of the code supplied; e.g. a syntax error would
be produced if a bracket had not been closed 14
tkinter
a package of classes that are often imported in to Python programs that
give methods that are useful for producing windows, drawing images and
producing animations 56
variable
a name that refers to a place in a computer’s memory where data is stored;
more loosely, it can also be used to refer to that data 23
while loop a kind of loop that repeats code while a comparative statement returns True22
Quick Quiz 2
Answer = 11 divided by 4 also equals: 2 remainder 3
Quick Quiz 3
Answer = 1
A book that purports to teach coding to youngsters has to be tried out on youngsters. My thanks therefore must go to
The Coding Club boys of Ewell Castle School and my youngest son Daniel who endured the early versions and helped
me find out what worked and what (unfortunately for them) didn’t.
It was fantastic when I realised that the Raspberry Pi foundation had the same aims and root motivations as myself
and the encouragement of Jack Lang and the enormous help from Alex Bradbury in ensuring my code and Computer
Science was technically correct was invaluable.
I also want to personally thank Ohio Art Company who own and sell the amazing Etch A Sketch® toy who were also
very enthusiastic and quick to give me permission to use their registered trademarks.
My two eldest sons have left the nest but thanks to modern technology have also shared the journey and made
invaluable contributions and suggestions. Finally, writing books and programs in the evenings and holidays takes time.
My eternal thanks go to my wife Rita for never begrudging me this time or complaining, even when listening to me
talking about code snippets!
Acknowledgements 82
The author and publisher acknowledge the following sources of copyright material and are
grateful for the permissions granted. While every effort has been made, it has not always
been possible to identify the sources of all the material used, or to trace all copyright holders.
If any omissions are brought to our notice, we will be happy to include the appropriate
acknowledgements on reprinting.
The word mark, logo, and configuration of the Etch A Sketch® product are registered
trademarks of the Ohio Art Company.
Acknowledgements 83