Instant Access to Coding Club Level 1 Python Basics Roffey C. ebook Full Chapters
Instant Access to Coding Club Level 1 Python Basics Roffey C. ebook Full Chapters
https://ebookultra.com
https://ebookultra.com/download/coding-club-
level-1-python-basics-roffey-c/
https://ebookultra.com/download/coding-club-level-3-python-building-
big-apps-roffey-c/
ebookultra.com
https://ebookultra.com/download/passages-level-1-teacher-s-edition-
jack-c-richards/
ebookultra.com
https://ebookultra.com/download/dead-simple-python-idiomatic-python-
for-the-impatient-programmer-jason-c-mcdonald/
ebookultra.com
https://ebookultra.com/download/c-python-tricks-and-tips-4th-edition/
ebookultra.com
Python Create Modify Reuse 1., Auflage Edition Knowlton
https://ebookultra.com/download/python-create-modify-reuse-1-auflage-
edition-knowlton/
ebookultra.com
https://ebookultra.com/download/aqa-a-level-physics-studentbook-1-aqa-
a-level-science-nick-england/
ebookultra.com
Love and Monsters Book Club Boys 1 1st Edition Max Walker
https://ebookultra.com/download/love-and-monsters-book-club-
boys-1-1st-edition-max-walker/
ebookultra.com
https://ebookultra.com/download/brickwork-level-1-2nd-edition-malcolm-
thorpe/
ebookultra.com
https://ebookultra.com/download/restaurant-law-basics-1st-edition-
stephen-c-barth/
ebookultra.com
Coding Club Level 1 Python Basics Roffey C. Digital
Instant Download
Author(s): Roffey C.
ISBN(s): 9781107658554, 1107658551
Edition: Spi ed.
File Details: PDF, 3.44 MB
Year: 2012
Language: english
Codi
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.
• P
ython is brilliant for writing quick applications, running programming experiments
and for building larger applications, including games.
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.
• Try and see what you can do with input() without supplying any text.
• 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.