Coding Club Level 1 Python Basics
Coding Club Level 1 Python Basics
Clubng
Python
Basics
Contents
Introduction4
Chapter 1: Python, IDLE and your first program
16
28
Chapter 4: Functions
45
Chapter 5: MyEtchASketch
55
73
Appendix74
Glossary and Index
77
81
Acknowledgements82
Contents
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.
Introduction
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.
Introduction
Introduction
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
Chapter 1
Python, IDLE and your first program
In this chapter you are going to:
learn about computer programming and the different languages that you can use
meet the Python programming language
learn how to use IDLE, which will help organise your programs and allow you to run
them easily
check that your computer has been set up correctly
write and run your first program.
Coding
Coding is writing instructions for a computer to perform a task. This code has to be in a form
that the computer can understand. This is more formally known as computer programming.
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 Pythons 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.
HTML is good for producing web pages.
SQL is great at making databases do what you want.
Python is brilliant for writing quick applications, running programming experiments
and for building larger applications, including games.
If you have previously programmed in Scratch (produced by MIT) you will find you can
pick up Python very quickly. Scratch is great for learning how to think like a programmer
and is very good for making games. If you have not tried Scratch before, you might
enjoy trying that next because the ability to learn a new programming language is an
important skill for coders. You will find it is a lot easier than learning a new human
language.
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.
Python is a powerful, modern programming language used by many famous organisations
such as YouTube and NASA. It is one of three programming languages that can be used to
write Google Apps. Python is a great language. Enjoy!
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.
Chapter 1: Python, IDLE and your first program
10
The code you want to run is typed after the special entry prompt:
>>> my code goes here
To run the code we press the return key. This is how Python runs in IDLEs interactive mode.
Python can run files as well but to start with, this is all we need.
Lets see how IDLE looks on a Windows PC:
11
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.
12
Hello World!
13
Making mistakes
Did you get a syntax error?
Syntax errors are very common when typing in code (as are other errors). If you make one
or two it is not your fault. It is because although computers are fast, they can also be a bit
stupid. If there are any tiny mistakes in your code, they panic and produce error messages.
These messages try to explain to you what the problem is but they are often difficult to
understand.
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 IDLEs standard display. This should
help you to spot bugs in your code.
Chapter 1: Python, IDLE and your first program
14
Chapter summary
In this chapter you have learned:
that programming is writing instructions for computers
that there are many different computer languages
why Python is a great language to learn
how to use IDLE in interactive mode
how to write and run a simple program
that the print() command means show on the screen not send to the printer.
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
In this chapter you are going to:
learn how to do some more with text
get Python to do some maths for you
learn about how while loops work
learn lots of useful operators.
This is a fun chapter as we get to start some real programming!
16
Text
Escape sequences
Try opening IDLE in interactive mode and enter the code in Code Box 2.1.
Escape sequence
What it does
\n
\t
\\
\"
17
Experiment
Try writing a variety of little programs in IDLE using the escape sequences
in Table 2.1 until you feel you know what they all do.
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.
18
The backslash is used to escape characters that are used in Python. When we want to print some
text to the screen we wrap it in speech marks. This now means that there is a problem if you want
to type some speech marks. Well, you know what to do about it put a backslash before it. So
what do you do if you want to actually print a backslash to the screen? Put a backslash before it!
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? Dont forget you can also add in escape sequences.
Maths
Using Python as a calculator is easy, if you remember two things:
1 In Python, as in almost all programming languages, the multiplication symbol is an
asterisk.
2 The division symbol is a forward slash.
>>> 10/4
2.5
>>> 3*3
9
>>>
19
There is another way of dividing. If you use two forward slashes instead of one, Python will
produce an integer as an answer. An integer is a whole number (adecimal such as 2.5 is
called a float). You can now find the remainder, with another mathematical operator
called the modulus. This is represented by a% sign.
>>> 11/4
2.75
>>> 11//4
2
>>> 11%4
3
>>>
Operator
Name
Example
Answer
2*3
multiply
divide (normal)
20/8
2.5
//
divide (integer)
20//8
modulus
20%8
add
2+3
subtract
7-3
20
Experiment
In interactive mode, check that the examples in Table 2.2 do give the
correct answers and then try out some of your own favourite sums. You
might like to see what happens if you wrap a maths sum inside speech
marks in the print() function.
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)
21
Going loopy
Computers are great at repetitive tasks. So are humans, but we get bored easily! Computers
are not only good at them, they are fast! Therefore we need to know how to tell them to do
repeats. To do this we use a while loop. This runs some code while something is true and
stops when it becomes false.
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.
22
The code in Code Box 2.5 is clever look carefully to see what is happening. Run it if you are
not sure. Although the code in Code Box 2.4 is longer, awhile loop is often more useful as it
can do far more complex tasks. For example, with a while loop you can ask a computer to
count to 100. Tryentering the code from Code Box 2.6 and running it.
23
The last line of code number = number+1 is in the loop. It keeps adding 1 to number for
each passage through the loop. Dont forget the variables value can be changed with the
equals operator at any time.
number = 1
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.
24
Operators
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
>=
<=
We use a double equals sign to compare two values and a single equals sign to assign a
value to a variable.
25
Chapter summary
In this chapter you have learned:
how the print() function is very flexible
how to write and run simple maths code
how to output a mixture of strings, maths or numbers
how to write a while loop and use comparative operators
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.
26
Puzzle 3
See if you can re-write the following code in three different ways so that each
program still produces output which counts to a hundred.
>>> 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:
<=>!=
27
Chapter 3
Readable code and the MyMagic8Ball game
In this chapter you are going to:
write and save a Python file using script mode
learn how to write clear readable code
run a Python file
learn about how to get user input
learn about if and else
write a short game called MyMagic8Ball.
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.
28
Script Mode
Open IDLE in interactive mode and then from the File menu choose New Window. A new
window appears that is apparently blank. When you type in this window and save the file you
are working in script mode. The file name must end in .py to show that it is Python code.
# MyMagic8Ball
import random
# write answers
ans1=Go for it!
ans2=No way, Jose!
ans3=Im 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 dont - whatever.
ans8=Yes, I think on balance that is the right choice.
print(Welcome to MyMagic8Ball.)
# get the users question
question = input(Ask me for advice then press ENTER to shake me.\n)
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
30
Modules
import random uses a new Python word import followed by the name of a Python module.
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
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.
White space
Lots of computer languages like Java, PHP and C++ wrap chunks of code in
curly brackets. Each statement has to end in a semicolon.
Delving deeper
There are 31 Python words that you cannot
use as your own variable names. These are:
and as assert break class continue
def del elif else except finally
for from global if import in is
lambda nonlocal not or pass print
raise return try while with yield
You must also be very careful to use only
letters and underscores and no unusual
characters such as & ! @ $ * ( ) ? : ; [ ]
< > ` | = { } \ /. Spaces are not allowed
either. Numbers are allowed but not at the
beginning of your variable names.
31
{
private int current_floor = 0;
public int getFloor()
{
return current_floor;
}
public void moveToFloor(int floor_number)
{
current_floor = floor_number;
}
}
Java code.
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.
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!
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.
34
Experiment
In interactive mode, try typing the code in Code Box 3.2 to see how this works. When
the computer asks for your name, tell it who you are, press return and then complete
the code.
35
The variable question is given the value from the result of the input() function. That is,
it now stores whatever was typed by the person playing the game before they pressed return.
In this version you will not use this variable. In fact the player might as well speak. However,
you may want to customise the game later so it is good design to store this input somewhere
obvious, just in case. You will find that you understand the rest of this code now. If you are
not sure what the last line in Code Box 3.3 does, you could copy that into the interactive
mode window and find out.
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.
36
37
else:
answer=ans8
# print the answer to the screen
print(answer)
input("\n\nPress the RETURN key to finish.")
38
So, if choice does equal 1 the program creates a new variable and calls it answer. Using the
equals sign it is given the string that is held by your variable ans1 which you typed at the
beginning of the program. So now answer would hold the string "Go for it!".
The random generator randint(1, 8) may not have produced the value 1 though, so
the next bit of the code handles the situation if choice equals 2:.
if
if
elif choice == 2:
answer=ans2
else
elif
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
39
question = input(
"Ask me for advice then press ENTER to shake me.\n")
Do you remember how the users 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.
At the end of the program we use the input() function again.
input("\n\nPress the RETURN key to finish.")
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.
40
41
elif choice==2:
answer=ans2
elif choice==3:
answer=ans3
elif choice==4:
answer=ans4
elif choice==5:
answer=ans5
elif choice==6:
answer=ans6
elif choice==7:
answer=ans7
else:
answer=ans8
# print the answer to the screen
print(answer)
input("\n\nPress the RETURN key to finish.")
42
Chapter summary
In this chapter you have learned:
how to write and save a Python file using script mode
how to write clear readable code with comments and descriptive variable names
how to run a Python file
how to get user input
about if, elif and else
how to write a short game called MyMagic8Ball.
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.
43
Challenge
Add some code to myMagic8Ball.py so that the Magic8Ball says Hi and asks for the
users name at the start of the game.
It should then store the input in a variable such as user_name.
Re-write the code so that the Magic8Ball talks to the user using their name. At the end
for example, it could say: Thanks for playing [users name]. Please press the return
key to finish.
There are several ways to do this. An example answer can be found on the Coding Club
website.
44
Chapter 4
Functions
In this chapter you are going to:
learn about functions
write your own functions
create a number guessing game.
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!
print("This is my number: ", number)
an argument
another 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.
>>> def count(number):
n=1
while n <= number:
print(n)
n = n+1
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. Dont be scared kill it!
(Sometimes simply holding ctrl and pressing the c key will work better.)
1
2
3
4
5
6
12
12
12
12
12
12
=
=
=
=
=
=
12
24
36
48
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.
Lets start thinking...
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 lets 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)
Now lets stick it all together.
Using IDLEs interactive mode, type in and think about the code in Code Box 4.1. Dont
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.
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
times_tables(num):
will see the power of functions. Enjoy!
50
51
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 users 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:
about functions and how to write your own
about building small programs, using functions and while loops
a little about the steps needed when designing a function
how to create a number guessing game
how to stop a program that just keeps running kill it; (or press ctrl-c)
how to easily copy portions of code in IDLE.
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 howfar 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
ake a copy of
M
myNumber.py and
then add some code
to make it count and
display how many
guesses it took the
player. (Hint: you will
need another variable
which you could call
counter.)
Idea 3
Make the
myNumber.py game
easier for younger
children by reducing
the range of numbers
between 1 and 100 to
between 1 and 10.
Idea 4
A harder challenge is to get the myNumber.py game to offer a choice of levels.
Easy: choose from numbers between 1 and 10.
Medium: numbers up to 20.
Hard: numbers between 1 and 100.
This can be split into a number of shorter tasks.
1 Ask the user what level they would like to play and collect and store the new
input as "e", "m" or "h".
2 Add the following code to catch any input we do not want the user to enter.
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
suitable variable.
4 Move the code where the computer thinks of a number, to below this section and
insert your upper limit variable in place of the appropriate argument.
5 Adjust the print() function below the # Start the game comment so that it
outputs the correct information.
6 Adjust the code so the output all looks nice.
Chapter 4: Functions
54
Chapter 5
MyEtchASketch
In this chapter you are going to:
learn how to use the tkinter library
make your own MyEtchASketch game
learn how to put an application in its own window
learn how to attach functions to keyboard presses.
Chapter 5: MyEtchASketch
55
MyEtchASketch in a window.
Chapter 5: MyEtchASketch
56
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, lets 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.
(300, 0)
(0, 0)
x
y
(300, 400)
(600, 400)
Chapter 5: MyEtchASketch
58
Chapter 5: MyEtchASketch
59
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
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.
Code
What it means
Initial settings
p1_x
p1_y
p1_colour
"green"
line_width
5 pixels
line_length
5 pixels
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 tkinters 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.
Chapter 5: MyEtchASketch
63
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
width
line_width
fill
p1_colour
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.
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
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:
how to use the tkinter library
how to make your own MyEtchASketch game
how to put an application in its own window
how to attach functions to keyboard presses
that copy and pasting hints at a better way of doing things
how to clear a canvas. (If you typed out the code you should have spotted an extra
function that was sneaked in: erase_all(self) . This clears the screen when the
user presses the u key on their keyboard.)
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 chapters
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 it out with a friend as a cooperative drawing 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.)
Make up some other games of your own.
Chapter 5: MyEtchASketch
72
More Python
Other books in the series, found at this book's companion website: http://www.codingclub.co.uk
The official python documentation: http://docs.python.org/py3k/
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.
73
Appendix
Some key bits of information
Companion website
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
\t
\\
\"
Appendix
74
Mathematical operators
Operator
Name
Example
Answer
2*3
multiply
divide (normal)
20/8
2.5
//
divide (integer)
20//8
20%8
modulus
add
2+3
minus
7-3
w
Table A2 Mathematical operators.
Comparison operators
Operator
Meaning
==
equal to
!=
not equal to
>
greater than
<
less than
>=
<=
Appendix
75
or
window.bind("a", my_function)
Basic tkinter code for making a canvas to draw in its own window
from tkinter import *
##### Set variables:
canvas_height = 400
canvas_width = 600
##### main:
window = Tk()
window.title("My Game Title")
canvas = Canvas(bg = "black", height = canvas_height, width = canvas_width, highlightthickness = 0)
canvas.pack()
window.mainloop()
76
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
63
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
78
local variable a variable that is defined inside a function and is only usable inside that
function63
logical operator see comparative operator25
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
Glossary and index
79
statement
used in this book to mean a snippet of code; strictly speaking it is a piece of
code that represents a command or action; e.g. a print statement
48
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 computers 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
80
Quick Quiz 2
Answer = 11 divided by 4 also equals: 2 remainder 3
Quick Quiz 3
Answer = 1
81
Acknowledgements
Although this is a small book it has been a lot more work than I expected. My aim has always been to produce a series
of books that are produced to a standard that young people deserve. To that end I sought an established publisher
and my thanks have to go to Claudia Bickford-Smith for her enthusiasm for the project. I am so glad that Cambridge
University Press were able to take me on. The hard work of Heather Mahy and Carl Saxton who had the unenviable job
of keeping me on the straight and narrow while making the project a reality is also much appreciated.
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) didnt.
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.
Fran, I love the illustrations.
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!
Thanks guys thighs.
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.
p. 28 ImageZoo/Alamy; p. 36 Sukhonosova Anastasia/Shutterstock; p. 37 Stock Illustrations
Ltd/Alamy; p. 55 Judith Collins/Alamy
The word mark, logo, and configuration of the Etch A Sketch product are registered
trademarks of the Ohio Art Company.
Acknowledgements
83