Main Coding Games in Python

Coding Games in Python

, , , ,
A visual step-by-step guide to writing code in Python.
Beginners and experienced programmers can use Python to build and play computer games, from mind-bending brainteasers to crazy action games with explosive sound effects and 3-D graphics.
Each chapter in Coding Games in Python shows how to construct a complete working game in simple numbered steps. The book teaches how to use freely available resources, such as PyGame Zero and Blender, to add animations, music, scrolling backgrounds, 3-D scenery, and other pieces of professional wizardry to games. After building a game, instructions show how to adapt it using secret hacks and cheat codes. Instructions are illustrated with zany Minecraft-style pixel art.
Master the key concepts that programmers need to write code--not just in Python, but in all programming languages. Find out what bugs, loops, flags, strings, tuples, toggles, and turtles are. Learn how to plan and design the ultimate game--and then play it to destruction as you test and debug it.
With coding theory interwoven into the instructions for building each game, learning coding is made effortless and fun.
Year:
2018
Edition:
1
Publisher:
DK Children
Language:
english
Pages:
224 / 226
ISBN 10:
1465473610
ISBN 13:
978-1465473615
File:
PDF, 29.56 MB
Download (pdf, 29.56 MB)

You may be interested in

 

Most frequently terms

 
 
You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
1

Cânticos dos Orixás na África

Language:
portuguese
File:
PDF, 44.86 MB




R

codinG
IN PYTHON
Games

US_001_half_title.indd   1 23/02/18   6:38 pm



US_002-003_Title.indd   2 23/02/18   6:38 pm

R

codinG
IN PYTHON
Games

US_002-003_Title.indd   3 23/02/18   6:38 pm



R

codinG
IN PYTHON
Games

US_002-003_Title.indd   3 23/02/18   6:38 pm



DK INDIA
Senior editor Bharti Bedi 

Project art editor Sanjay Chauhan
Editor Tina Jindal

Assistant art editors Rabia Ahmad,  
Simar Dhamija, Sonakshi Singh

Jacket designer Juhi Sheth
Jackets editorial coordinator Priyanka Sharma

Managing jackets editor Saloni Singh
DTP designer Sachin Gupta 

Senior DTP designer Harish Aggarwal
Senior managing editor Rohan Sinha
Managing art editor Sudakshina Basu

Pre-production manager Balwant Singh

First American Edition, 2018
Published in the United States by DK Publishing
345 Hudson Street, New York, New York 10014

Copyright © 2018 Dorling Kindersley Limited 
DK, a Division of Penguin Random House LLC 

18 19 20 21 22 10 9 8 7 6 5 4 3 2 1
001–309872–July/2018

All rights reserved.
Without limiting the rights under the copyright reserved above, no part 

of this publication may be reproduced, stored in or introduced into a 
retrieval system, or transmitted, in any form, or by any means (electronic, 

mechanical, photocopying, recording, or otherwise), without the prior 
written permission of the copyright owner. 

Published in Great Britain by Dorling Kindersley Limited

A catalog record for this book  
is available from the Library of Congress.

ISBN: 978-1-4654-7361-5

Printed in China

A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW

www.dk.com

DK UK
Project editor Ben Ffrancon Davies

Senior art editor Sunita Gahir
Consultant editor Craig Steele

Jacket design development manager Sophia MTT
Jacket editor Claire Gell

Producer, pre-production Gillian Reid
Senior Producer Alex Bell

US editors Jill Hamilton, Kayla Dugger
Managing editor Lisa Gillespie

Managing art editor Owen Peyton Jones
Publisher Andrew Macintyre

Associate publishing director Liz Wheeler
Art director Karen Self

Design dire; ctor Phil Ormerod
Publishing director Jonathan Metcalf

US_004-005_imprint.indd   4 22/02/18   1:40 pm

CAROL VORDERMAN MBE is one of Britain’s best-loved TV presenters and is 
renowned for her mathematical skills. She has hosted numerous TV shows on 
science and technology, from Tomorrow’s World to How 2, and was co-host of 
Channel 4’s Countdown for 26 years. A Cambridge University engineering 
graduate, she has a passion for communicating science and technology and  
is particularly interested in coding.

CRAIG STEELE is a specialist in computing science education who helps people 
develop digital skills in a fun and creative environment. He is a founder of 
CoderDojo in Scotland, which runs free coding clubs for young people. Craig  
has run digital workshops with the Raspberry Pi Foundation, Glasgow Science 
Centre, Glasgow School of Art, BAFTA, and the BBC micro:bit project. Craig’s first 
computer was a ZX Spectrum.

DR. CLAIRE QUIGLEY studied computing science at Glasgow University, 
where she obtained BSc and PhD degrees. She has worked in the Computer 
Laboratory at Cambridge University and Glasgow Science Centre, and is 
currently working on a project to develop a music and technology resource 
for primary schools in Edinburgh. She is a mentor at CoderDojo Scotland.

DANIEL McCAFFERTY holds a degree in computer science from the University 
of Strathclyde. He has worked as a software engineer for companies big and 
small in industries from banking to broadcasting. Daniel lives in Glasgow with 
his wife and two children, and when not teaching young people to code, he 
enjoys bicycling and spending time with his family.

DR. MARTIN GOODFELLOW is a teaching associate in the Computer and 
Information Sciences department at the University of Strathclyde. He has 
also developed educational computer science content and workshops for 
other organizations in the UK and China, including CoderDojo Scotland, 
Glasgow Life, Codemao, and the BBC. He is currently the Scottish 
Ambassador for National Coding Week.

US_004-005_imprint.indd   5 22/02/18   1:40 pm



CAROL VORDERMAN MBE is one of Britain’s best-loved TV presenters and is 
renowned for her mathematical skills. She has hosted numerous TV shows on 
science and technology, from Tomorrow’s World to How 2, and was co-host of 
Channel 4’s Countdown for 26 years. A Cambridge University engineering 
graduate, she has a passion for communicating science and technology and  
is particularly interested in coding.

CRAIG STEELE is a specialist in computing science education who helps people 
develop digital skills in a fun and creative environment. He is a founder of 
CoderDojo in Scotland, which runs free coding clubs for young people. Craig  
has run digital workshops with the Raspberry Pi Foundation, Glasgow Science 
Centre, Glasgow School of Art, BAFTA, and the BBC micro:bit project. Craig’s first 
computer was a ZX Spectrum.

DR. CLAIRE QUIGLEY studied computing science at Glasgow University, 
where she obtained BSc and PhD degrees. She has worked in the Computer 
Laboratory at Cambridge University and Glasgow Science Centre, and is 
currently working on a project to develop a music and technology resource 
for primary schools in Edinburgh. She is a mentor at CoderDojo Scotland.

DANIEL McCAFFERTY holds a degree in computer science from the University 
of Strathclyde. He has worked as a software engineer for companies big and 
small in industries from banking to broadcasting. Daniel lives in Glasgow with 
his wife and two children, and when not teaching young people to code, he 
enjoys bicycling and spending time with his family.

DR. MARTIN GOODFELLOW is a teaching associate in the Computer and 
Information Sciences department at the University of Strathclyde. He has 
also developed educational computer science content and workshops for 
other organizations in the UK and China, including CoderDojo Scotland, 
Glasgow Life, Codemao, and the BBC. He is currently the Scottish 
Ambassador for National Coding Week.

US_004-005_imprint.indd   5 22/02/18   1:40 pm



  GETTING STARTED
12 What is Python? 

14 Gaming in Python

16 Installing Python

18 Installing Pygame Zero

20 Using IDLE

22 Your first program

  LEARNING THE BASICS
28 Creating variables 

32 Making decisions

36 Playing with loops

40 Functions

44 Fixing bugs

  SHOOT THE FRUIT
50 How to build Shoot the Fruit 

Contents

  COIN COLLECTOR
60 How to build Coin Collector

  FOLLOW THE NUMBERS
70 How to build Follow the Numbers

  RED ALERT
82 How to build Red Alert 

8 F O R E W O R D 

Score: 0

US_006-007_Contents.indd   6 22/02/18   12:23 pm

  HAPPY GARDEN
156 How to build Happy Garden

  SLEEPING DRAGONS
178 How to build Sleeping Dragons

  REFERENCE
198 Project reference

220 Glossary

222 Index

224 Acknowledgments

  BIG QUIZ
100 How to build Big Quiz

  BALLOON FLIGHT
118 How to build Balloon Flight

  DANCE CHALLENGE
138 How to build Dance Challenge 

Garden happy for: 16 seconds

26

Score: 0

Score: 0

7
London

Berlin

Paris

Tokyo

What is the  
capital of France?

US_006-007_Contents.indd   7 22/02/18   12:23 pm



  HAPPY GARDEN
156 How to build Happy Garden

  SLEEPING DRAGONS
178 How to build Sleeping Dragons

  REFERENCE
198 Project reference

220 Glossary

222 Index

224 Acknowledgments

  BIG QUIZ
100 How to build Big Quiz

  BALLOON FLIGHT
118 How to build Balloon Flight

  DANCE CHALLENGE
138 How to build Dance Challenge 

Garden happy for: 16 seconds

26

Score: 0

Score: 0

7
London

Berlin

Paris

Tokyo

What is the  
capital of France?

US_006-007_Contents.indd   7 22/02/18   12:23 pm



Foreword

Computer programmers are the unsung heroes of the modern world. From smartphones 
to laptops, traffic systems to bank cards, their hard work touches almost every aspect 
of our lives. Behind each technological advance is a team of creative coders.

Over the past 30 years, computer games have become one of the most exciting and 
popular areas of the entertainment industry to work in. Becoming a game programmer 
takes creative flair to help create the story, graphics, music, and characters you need 
for your games, and the technical know-how to bring them to life. Who knows? This 
book may be the very first step on your journey from gamer to game maker.

Learning to code isn’t just for people who want to be professional programmers, 
though. Coding skills are useful in lots of different jobs that may seem to have nothing 
to do with computers at first. Programming expertise is essential to subject areas as 
diverse as science, business, art, and music. 

This book uses a programming language called Python®, a fairly simple text-based 
language, and is perfect for beginners, or as a step up from Scratch™. However,  
unlike Scratch, it was not created especially to teach coding. Python is as popular with 
budding coders as it is with professionals, and is one of the most widely used 
professional programming languages in the world. It pops up in banking, medicine, 
animation, and even space exploration.

The best way to learn any new language is to get immersed in it, and programming 
languages are no different. Building your own computer games is a fun way to combine 
theory and practice. If you’re a brand-new coder, start off with the basics at the 

US_008-009_Foreword.indd   8 22/02/18   12:23 pm

beginning of this book before moving on to the more complex games as the book 
progresses. By following the step-by-step guides, you’ll find out how professional 
coders think when they’re building a computer game. Follow those steps carefully and 
you’ll have your own games up and running in no time. Then, if you really want to push 
yourself, you can try tweaking the code to make your games unique. 

Everybody, whether a beginner or a pro, makes mistakes. Nothing frustrates a coder 
more than the bugs that manage to creep into their programs. If something goes  
wrong in one of your games, go back over your code and check it all carefully. There  
are hints and tips throughout the book that will help you do this. Most importantly, 
don’t get disheartened—finding and fixing errors in your code is all part of being a 
programmer. The more practice you get, the fewer bugs your code will contain, and  
the quicker you’ll catch the little ones that still appear. 

Most importantly, have fun! Once you’ve completed the games, you can show them off 
to your friends and family—they’ll be amazed by what you’ve managed to make. This 
book is packed with games to suit every audience, and we hope you enjoy building and 
playing them as much as we enjoyed creating them for you. 

Have fun coding!

US_008-009_Foreword.indd   9 23/02/18   2:31 pm



beginning of this book before moving on to the more complex games as the book 
progresses. By following the step-by-step guides, you’ll find out how professional 
coders think when they’re building a computer game. Follow those steps carefully and 
you’ll have your own games up and running in no time. Then, if you really want to push 
yourself, you can try tweaking the code to make your games unique. 

Everybody, whether a beginner or a pro, makes mistakes. Nothing frustrates a coder 
more than the bugs that manage to creep into their programs. If something goes  
wrong in one of your games, go back over your code and check it all carefully. There  
are hints and tips throughout the book that will help you do this. Most importantly, 
don’t get disheartened—finding and fixing errors in your code is all part of being a 
programmer. The more practice you get, the fewer bugs your code will contain, and  
the quicker you’ll catch the little ones that still appear. 

Most importantly, have fun! Once you’ve completed the games, you can show them off 
to your friends and family—they’ll be amazed by what you’ve managed to make. This 
book is packed with games to suit every audience, and we hope you enjoy building and 
playing them as much as we enjoyed creating them for you. 

Have fun coding!

US_008-009_Foreword.indd   9 23/02/18   2:31 pm



US_010-011_Chapter_opener_1.indd   10 22/02/18   1:40 pm

Getting 
started

US_010-011_Chapter_opener_1.indd   11 22/02/18   1:40 pm



Getting 
started

US_010-011_Chapter_opener_1.indd   11 22/02/18   1:40 pm



12 G E T T I N G  S T A R T E D

What is Python?
Computers need step-by-step instructions  
to perform different tasks. A set of instructions, 
or code, can be written in different 
programming languages. Python is one of  
the most popular programming languages.

Why Python?
Python is a powerful programming language that 
you can use to code simple programs quickly. It’s 
not too hard to learn and it’s great for building 
apps and games. Here are some of the reasons 
why Python is such a great tool for programmers.

1+1=2

△ Packed with tools 
Python comes with everything you need to start 
coding right away, so programmers say it comes 
with “batteries included.” It contains lots of 
prewritten code, called the Standard Library,  
that you can use in your programs.

Python is great!  
I can take  

it anywhere.

△ Portable
The same Python code will work on PCs, 
Macs, Linux machines, and Raspberry Pi 
computers. The programs act in a similar  
way on each platform, so games created  
with Python can be played on lots of 
machines all around the world.

△ Lots of help
Python’s website is packed with support 
materials to help you learn how to use it. It has a 
guide to getting started, several pieces of sample 
code, and a reference section to help you 
understand the code.

△ Easy to understand 
Unlike some other programming languages, Python 
doesn’t use complicated symbols. You type the  
code using a mixture of English words, characters, and 
numbers, so it’s easy to read and write—just like a book. 

◁ Diverse applications 
Python is used to build 
systems and tools for lots of 
interesting tasks in different 
industries, such as banking, 
healthcare, the space industry, 
education, and many others.

Better get started!

US_012_013_what_is_python.indd   12 22/02/18   12:23 pm

13W H A T  I S  P Y T H O N ?

From Scratch to Python
Scratch is a visual language, whereas Python is text  
based. If you’ve used Scratch, you will recognize some  
of the features and ideas in Python. The two languages 
might look different, but lots of the elements that are  
used in Scratch are also used in Python.

Goodbye!

△ Set a condition with Scratch
The “if-then-else” block lets you choose which part of  
the script to run depending on whether the condition  
is True or False.

when  clicked

say    Hello World!

Hello World!

This block displays 
the message in a 
speech bubble.

△ Print in Scratch
In Scratch, the “say” block is used to 
display a message on the screen.

Type your 
message here.

The message appears 
on the screen like this.

△ Print in Python
In Python, the “print” command displays  
a message on the screen.

say    Hello!

say    Goodbye!

a =    2if

else

then

Goodbye!
?Hello!

△ Set a condition with Python
In Python, “if-then-else” commands work 
exactly the same way, but they don’t use  
the word “then.”

This command  
is executed if the 
condition after  
if is False.

This message is 
displayed if the 
answer is False.

if a == 2:

    print("Hello!")

 else:

    print("Goodbye!")

 print("Hello World!")

Hello World!

This command  
is executed if  
the condition  
after if is True.

This message is 
displayed if the  
answer is True.

This is the end of the 
“if-then-else” block.

US_012_013_what_is_python.indd   13 22/02/18   12:23 pm



13W H A T  I S  P Y T H O N ?

From Scratch to Python
Scratch is a visual language, whereas Python is text  
based. If you’ve used Scratch, you will recognize some  
of the features and ideas in Python. The two languages 
might look different, but lots of the elements that are  
used in Scratch are also used in Python.

Goodbye!

△ Set a condition with Scratch
The “if-then-else” block lets you choose which part of  
the script to run depending on whether the condition  
is True or False.

when  clicked

say    Hello World!

Hello World!

This block displays 
the message in a 
speech bubble.

△ Print in Scratch
In Scratch, the “say” block is used to 
display a message on the screen.

Type your 
message here.

The message appears 
on the screen like this.

△ Print in Python
In Python, the “print” command displays  
a message on the screen.

say    Hello!

say    Goodbye!

a =    2if

else

then

Goodbye!
?Hello!

△ Set a condition with Python
In Python, “if-then-else” commands work 
exactly the same way, but they don’t use  
the word “then.”

This command  
is executed if the 
condition after  
if is False.

This message is 
displayed if the 
answer is False.

if a == 2:

    print("Hello!")

 else:

    print("Goodbye!")

 print("Hello World!")

Hello World!

This command  
is executed if  
the condition  
after if is True.

This message is 
displayed if the  
answer is True.

This is the end of the 
“if-then-else” block.

US_012_013_what_is_python.indd   13 22/02/18   12:23 pm



14 G E T T I N G  S T A R T E D

Gaming in Python
Video games are computer programs that 
contain a bunch of instructions. Python can 
be used to build lots of different types of 
games. With Python, there’s something for 
every gamer!

Types of games
There are lots of different categories, or 
genres, of computer games. These range  
from simple one-button games to more 
complex strategy ones. Which genre would 
you like to create first?

△ Platform
Platform games, such as racing games, create 
the illusion of speed by making the background 
scroll past the player’s viewpoint. The gameplay 
generally involves moving around obstacles or 
jumping over them. 

▷ One button
With Python, you can build fun, 
action-packed games that only 
need one button to be played. 
These games are so addictive, 
you’ll want to play them over 
and over again.

◁ Puzzles
Puzzles are a great  
way to exercise your 
brain or test someone’s 
general knowledge. 
They come in all shapes 
and sizes, from jigsaw 
puzzles to word and 
number games. 

◁ Strategy
A strategy game is all 
about decisions. You 
need to plan ahead 
and make the right 
choices to win.

△ Multiplayer
Some games you play by yourself, but others let you 
compete against other players. You can use Python to 
build multiplayer games and challenge your friends. 

US_014-015_Gaming_in_python.indd   14 22/02/18   12:24 pm

15G A M I N G  I N  P Y T H O N

Python modules
Python has bundles of code called “modules” 
that help you complete common coding 
tasks. You can use these modules by 
importing them into your programs.  
Here are some Python modules that you 
might find useful.

▽ Pygame
Pygame is designed for writing games in Python. 
With this module, you can easily add and control 
game characters, update scores and timers, use 
special animations and graphics, and use gamepads 
and joysticks with your games. It is not a built-in 
Python module, so it needs to be installed separately. 

◁ Pygame Zero
Pygame Zero is a great module for 
beginner game programmers. It’s a 
simplified version of Pygame, which makes 
it even easier to get started by hiding some 
of Pygame’s more complicated features. It 
comes with several tools that are useful for 
beginners, but it’s also powerful enough  
to build some impressive games.

▷ Random
This module can pick a random 
number or shuffle a list into a 
random order. It is great for 
adding an element of chance 
to a game. Use it when you 
want to simulate rolling dice  
or when choosing a random 
enemy for the player to face.

◁ Tkinter
This tool is used to build 
simple graphics in games 
to create Graphical  
User Interfaces (GUIs, 
pronounced “goo-eys”)  
that let users interact  
with, and control,  
Python programs.

◁ Time
This module provides tools to 
work with time and dates in  
a program. For example, you 
might need to calculate how 
many seconds have passed 
since a game started.

▷ Math
Math is a standard Python 
module that can be used to 
perform simple calculations  
in games. However, you might 
need to use other modules for 
trickier calculations.

E X P E R T  T I P S

Downloading modules
Python comes with several built-in modules  
for developing games, such as Pyglet. But  
some other modules, like Pygame, have to  
be downloaded separately.

US_014-015_Gaming_in_python.indd   15 22/02/18   12:24 pm



15G A M I N G  I N  P Y T H O N

Python modules
Python has bundles of code called “modules” 
that help you complete common coding 
tasks. You can use these modules by 
importing them into your programs.  
Here are some Python modules that you 
might find useful.

▽ Pygame
Pygame is designed for writing games in Python. 
With this module, you can easily add and control 
game characters, update scores and timers, use 
special animations and graphics, and use gamepads 
and joysticks with your games. It is not a built-in 
Python module, so it needs to be installed separately. 

◁ Pygame Zero
Pygame Zero is a great module for 
beginner game programmers. It’s a 
simplified version of Pygame, which makes 
it even easier to get started by hiding some 
of Pygame’s more complicated features. It 
comes with several tools that are useful for 
beginners, but it’s also powerful enough  
to build some impressive games.

▷ Random
This module can pick a random 
number or shuffle a list into a 
random order. It is great for 
adding an element of chance 
to a game. Use it when you 
want to simulate rolling dice  
or when choosing a random 
enemy for the player to face.

◁ Tkinter
This tool is used to build 
simple graphics in games 
to create Graphical  
User Interfaces (GUIs, 
pronounced “goo-eys”)  
that let users interact  
with, and control,  
Python programs.

◁ Time
This module provides tools to 
work with time and dates in  
a program. For example, you 
might need to calculate how 
many seconds have passed 
since a game started.

▷ Math
Math is a standard Python 
module that can be used to 
perform simple calculations  
in games. However, you might 
need to use other modules for 
trickier calculations.

E X P E R T  T I P S

Downloading modules
Python comes with several built-in modules  
for developing games, such as Pyglet. But  
some other modules, like Pygame, have to  
be downloaded separately.

US_014-015_Gaming_in_python.indd   15 22/02/18   12:24 pm



16 G E T T I N G  S T A R T E D

Installing Python
The games in this book use Python 3. It’s 
free, and you can download it from the 
Python website. Follow the instructions  
that match your computer. Never install  
any program unless you have the computer 
owner’s permission. 

Installing Python on Windows
First you need to find out if your computer uses the 
32-bit or 64-bit version of Windows. Go to the Start 
menu, then Computer, Properties, and choose 
System if the option appears.

Click the 
installer.

Install Python
Open the installer file, then click Custom 
Installation, then Next until you get to Advanced 
Options. Leave the checked boxes as they are, but 
make sure “Install for all users” and “Add Python to 
environment variables” are also checked. Then 
click Install and Next at each prompt.

2

Start IDLE
Once the installation process is complete,  
open IDLE by searching for it or going to  
the Start menu, choosing All Apps, then 
selecting IDLE. A window like the one  
below should appear.

3

Download Python
Go to www.python.org and click on Downloads. Click  
on the latest version of Python for Windows. It should 
start with the number 3. Select executable installer 
from the different installer options that appear.  

Use this installer if 
you have a 32-bit 
version of Windows. 

Use this installer if 
you have a 64-bit 
version of Windows.

The version number might not be 
exactly the same as this one—just 
make sure it has 3 at the beginning.

•     Python 3.6.2 - 2017-05-15 
             •     Windows x86 executable installer 
             •     Windows x86-64 executable installer

1

Python 3.6.2 (v3.6.2:5fd3365926, Aug 15 2017, 00:45:10) [MSC v.1900 32 bit 

(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.

>>>

Python 3.6.2 Shell

IDLE        File        Edit        Shell        Debug        Window        Help

L I N G O

IDLE
When you install Python 3, you will  
also get another free program called 
IDLE (short for Integrated Development 
Environment). Designed for 
beginners, IDLE includes a basic  
text editor that allows you to write  
and edit Python code. 

Z Z Z

US_016-017_Installing_python.indd   16 23/02/18   3:52 pm

I N S T A L L I N G  P Y T H O N 17

Start IDLE
Once the installation is complete, check that it was 
successful by opening the IDLE program. Search for  
it in Spotlight or select the Applications folder, then  
the Python folder, and double-click IDLE. A window  
like this should appear.

Download Python
Go to www.python.org and click on Downloads.  
Click on the version of Python 3 that matches your 
operating system. The “Python.pkg” file will download 
to your Mac automatically.

Install Python
Double-click the “.pkg” file in the Downloads folder  
to start the installation. Select Continue and then  
Install to accept the default settings.

Installing Python on a Mac
Before you install Python 3 on a Mac, you need to check 
which operating system your Mac uses. To do this, click 
the Apple icon in the top left of the screen and choose 
About This Mac from the drop-down menu.

The version number might not be exactly  
the same as this one—just make sure it  
has a 3 at the beginning.

Click the package  
to run the installer.

•     Python 3.6.2 - 2017-08-15 
       •     Download macOS X 64-bit/32-bit installer

Python 3.6.2 (v3.6.2:5fd3365926, Aug 15 2017, 13:38:16) 

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "copyright", "credits" or "license()" for more information.

>>>

Python 3.6.2 Shell

IDLE        File        Edit        Shell        Debug        Window        Help

1

2

3

I better  
get going!

Where should 
I plug this in?

E X P E R T  T I P S

Raspberry Pi
If you’re using a Raspberry Pi computer, 
then you can skip the download  
step because Python 2 and Python 3 
come preinstalled on the machine. 
Remember this book uses Python 3, so 
make sure you open the right version. 
You’ll find Python 3 in the Applications 
menu on your Raspberry Pi. Open it 
now and check that it works.

US_016-017_Installing_python.indd   17 22/02/18   12:24 pm



I N S T A L L I N G  P Y T H O N 17

Start IDLE
Once the installation is complete, check that it was 
successful by opening the IDLE program. Search for  
it in Spotlight or select the Applications folder, then  
the Python folder, and double-click IDLE. A window  
like this should appear.

Download Python
Go to www.python.org and click on Downloads.  
Click on the version of Python 3 that matches your 
operating system. The “Python.pkg” file will download 
to your Mac automatically.

Install Python
Double-click the “.pkg” file in the Downloads folder  
to start the installation. Select Continue and then  
Install to accept the default settings.

Installing Python on a Mac
Before you install Python 3 on a Mac, you need to check 
which operating system your Mac uses. To do this, click 
the Apple icon in the top left of the screen and choose 
About This Mac from the drop-down menu.

The version number might not be exactly  
the same as this one—just make sure it  
has a 3 at the beginning.

Click the package  
to run the installer.

•     Python 3.6.2 - 2017-08-15 
       •     Download macOS X 64-bit/32-bit installer

Python 3.6.2 (v3.6.2:5fd3365926, Aug 15 2017, 13:38:16) 

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "copyright", "credits" or "license()" for more information.

>>>

Python 3.6.2 Shell

IDLE        File        Edit        Shell        Debug        Window        Help

1

2

3

I better  
get going!

Where should 
I plug this in?

E X P E R T  T I P S

Raspberry Pi
If you’re using a Raspberry Pi computer, 
then you can skip the download  
step because Python 2 and Python 3 
come preinstalled on the machine. 
Remember this book uses Python 3, so 
make sure you open the right version. 
You’ll find Python 3 in the Applications 
menu on your Raspberry Pi. Open it 
now and check that it works.

US_016-017_Installing_python.indd   17 22/02/18   12:24 pm



G E T T I N G  S T A R T E D18

Installing  
Pygame Zero
Now it’s time to add some extra tools to  
help you build great games. In this book,  
you’ll need two additional modules—Pygame 
and Pygame Zero. These are not included  
with Python, so you need to install  
them separately. 

E X P E R T  T I P S

Admin access
Make sure you're signed into your 
computer as an admin; otherwise, 
the system won't let you install 
things properly. Always ask 
permission before installing new 
software on someone's computer.

Installing Pygame Zero on Windows
Follow these steps to install the latest versions of 
Pygame and Pygame Zero on your Windows computer. 
Your machine needs to be connected to the Internet  
to complete some of these steps.

Install a package manager
A package manager called “pip” should come  
with Python when you install it. It’s a tool that 
makes it easier to install Pygame Zero and other 
Python modules. Type this command into the 
Command Prompt and press Enter—it will  
check if pip is on your computer and install  
it if it is not.

2

Install Pygame Zero
Finally, type this command. When you  
press Enter, this will install Pygame Zero,  
also known as pgzero for short.

4

pip install pgzero

Install Pygame
Once the package manager is installed, 
type the following command and press 
Enter. This uses pip to install Pygame.

3

pip install pygame

Open the Command Prompt
Click Start. Scroll down and open the Windows 
System folder. Click Command Prompt. If you 
can’t find it, try searching for it. You’ll need to 
type in some commands and press Enter to  
run each one. Make sure you spell everything 
correctly and put spaces in the right places  
or it won’t work.

1

python -m pip install -U pip

Command Prompt

Look out for 
this thumbnail 
in the menu.

A C C E S S  D E N I E D

c:\

US_018-019_Installing_pygame_zero.indd   18 22/02/18   12:24 pm

I N S T A L L I N G  P Y G A M E  Z E R O 19

Installing Pygame Zero  
on a Mac
Follow these steps to install the latest 
versions of Pygame and Pygame Zero 
on your Mac. Your machine needs  
to be connected to the Internet to 
complete some of these steps.

Open Terminal
You’ll need to use the Terminal app to  
install the modules. You can find it in your 
Applications folder, or you can search for  
it with Spotlight. Follow the steps below, 
making sure all the spellings are correct  
and the spaces are in the right place.

Install Pygame
Now it’s time to install Pygame. Type  
in this command and press Enter. 

5

Install other tools
Type in this command next and press 
Enter. It uses Homebrew to install some 
tools that will be needed by Pygame Zero.

4

1

6 Install Pygame ZeroFinally, this last command will install 
Pygame Zero.

Check that Python 3 is installed
Homebrew will check if Python 3 is 
already installed on your Mac and will 
install it if it’s not there. Even though 
you’ve already installed Python, it’s  
worth checking just to be sure. 

3

Install a package manager
Homebrew is a package manager tool 
that makes it easier to install Pygame Zero 
and other Python modules. Type in the 
command at right and press Enter to 
install Homebrew. It might ask you to 
enter your password again, and it will take 
a short while to install, so don't panic if 
nothing happens right away.

2

brew install sdl sdl_mixer sdl_sound sdl_ttf

pip3 install pygame

Don’t put a  
space before 3.

This should fit  
on one line when 
you type it in.

Type this line carefully in the 
Terminal window and check for any 

spelling errors and extra spaces.

brew install python3

pip3 install pgzero

E X P E R T  T I P S

Having trouble?
Installing these modules might be a bit tricky at first. If 
you’re having trouble, you can get the most up-to-date 
installation instructions on the Pygame Zero website: 
https://pygame-zero.readthedocs.io

This is what the 
Terminal app 
thumbnail looks like.

Rabiahma – bash – 80x24

Last login: Thu Sep 14 11:22:51 on ttys000

LC-0926:~ rzvz ruby -e "$(curl -fsSL https://raw.git

 hubusercontent.com/Homebrew/install/master/install)"

I N S T A L L I N G

>_

US_018-019_Installing_pygame_zero.indd   19 22/02/18   12:24 pm



I N S T A L L I N G  P Y G A M E  Z E R O 19

Installing Pygame Zero  
on a Mac
Follow these steps to install the latest 
versions of Pygame and Pygame Zero 
on your Mac. Your machine needs  
to be connected to the Internet to 
complete some of these steps.

Open Terminal
You’ll need to use the Terminal app to  
install the modules. You can find it in your 
Applications folder, or you can search for  
it with Spotlight. Follow the steps below, 
making sure all the spellings are correct  
and the spaces are in the right place.

Install Pygame
Now it’s time to install Pygame. Type  
in this command and press Enter. 

5

Install other tools
Type in this command next and press 
Enter. It uses Homebrew to install some 
tools that will be needed by Pygame Zero.

4

1

6 Install Pygame ZeroFinally, this last command will install 
Pygame Zero.

Check that Python 3 is installed
Homebrew will check if Python 3 is 
already installed on your Mac and will 
install it if it’s not there. Even though 
you’ve already installed Python, it’s  
worth checking just to be sure. 

3

Install a package manager
Homebrew is a package manager tool 
that makes it easier to install Pygame Zero 
and other Python modules. Type in the 
command at right and press Enter to 
install Homebrew. It might ask you to 
enter your password again, and it will take 
a short while to install, so don't panic if 
nothing happens right away.

2

brew install sdl sdl_mixer sdl_sound sdl_ttf

pip3 install pygame

Don’t put a  
space before 3.

This should fit  
on one line when 
you type it in.

Type this line carefully in the 
Terminal window and check for any 

spelling errors and extra spaces.

brew install python3

pip3 install pgzero

E X P E R T  T I P S

Having trouble?
Installing these modules might be a bit tricky at first. If 
you’re having trouble, you can get the most up-to-date 
installation instructions on the Pygame Zero website: 
https://pygame-zero.readthedocs.io

This is what the 
Terminal app 
thumbnail looks like.

Rabiahma – bash – 80x24

Last login: Thu Sep 14 11:22:51 on ttys000

LC-0926:~ rzvz ruby -e "$(curl -fsSL https://raw.git

 hubusercontent.com/Homebrew/install/master/install)"

I N S T A L L I N G

>_

US_018-019_Installing_pygame_zero.indd   19 22/02/18   12:24 pm



20 G E T T I N G  S T A R T E D

Using IDLE
In IDLE, you can work in two different windows. 
The editor window can be used to write and 
save programs, while the shell window runs 
Python instructions immediately.

The shell window
When you open IDLE, the shell window pops up. 
This is the best place to get started because you 
don’t have to create a new file first. You just type 
the code directly into the shell window. 

>>> print("You've unlocked a new level!")

>>> ''.join(reversed("Time to play"))

>>> 123 + 456 * (7 / 8)

E X P E R T  T I P S

Different windows
To help you know which window you should 
type your code in, we’ve given each window 
in IDLE a different color. 

Shell window

Editor window

△ Give the shell a test run
Type each of these code snippets into the shell window 
and press Enter after each one. The first line displays a 
message and the second line does a calculation. Can you 
figure out what the third line does?

▽ Working in the shell
You can use the shell window to test out 
snippets of code before you add them into  
a bigger program. The code you type can  
be run right away, and any messages  
or “bugs” (errors) are displayed. 

This line  
shows the 
version of 
Python  
you have.

You type 
in code at 

the >>> 
prompt.

Python 3.6.2 (v3.6.2:5fd3365926, Aug 15 2017, 13:38:16) 

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "copyright", "credits" or "license()" for more information.

>>> from turtle import *

>>> forward(200)

>>> left(90)

>>> forward(300)

>>>

Python 3.6.2 Shell

IDLE        File        Edit        Shell        Debug        Window        Help

The text here 
will depend 
on your 
operating 
system.

These four 
lines of code 
are a simple 

drawing 
program—try 

it out for 
yourself.

Look at  
my pretty shell!

US_020-021_Using_Idle.indd   20 14/03/18   12:18 PM

U S I N G  I D L E 21

The editor window
The shell window can’t save your code, so when you 
close it, the code you typed is gone forever. When you 
are working on a game, you should use IDLE’s editor 
window. This will let you save your code. It also has 
built-in tools to help you write your programs and  
troubleshoot any errors.

▽ The editor window
To open the editor window  
in IDLE, click on the File menu at 
the top and choose New File.  
An empty editor will then appear. 
You’ll use the editor window to 
write the programs for the games 
in this book.

You can run Python programs from 
this menu, but you will run Pygame 
Zero programs a different way.

The name of the 
file is shown here.

The menu bar for  
the editor window is 
different from the one 
for the shell window.

 for count in range(10):

    if ((count % 2) == 0):

        print(count)

        print("is even")

    else:

        print(count)

        print("is odd")

EvensandOdds.py

IDLE        File        Edit        Format        Run        Window        Help

E X P E R T  T I P S

Colors in the code
IDLE automatically colors 
the text to highlight 
different parts of the code. 
The colors make it easier to 
understand the code, and 
they’re useful when you’re 
trying to spot mistakes.

Text in quotation marks
Any text in quotation 
marks is green. These are 
called strings.

Output
Any text produced when  
a program runs is blue. 

Keywords
Certain words, such as if and  
else, are special Python keywords. 
They are shown in orange.

Built-in commands
Python commands, 
such as print(), are 
shown in purple.

Symbols and names
Most code text is colored 
black.

Errors
Python uses red to 
alert you to any errors 
in your code.

Anything you tell 
Python to print 

gets displayed in 
the shell window.

You type in the code 
here. This program  

prints a list that tells 
you which numbers 
are even and which 

ones are odd.

US_020-021_Using_Idle.indd   21 22/02/18   12:24 pm



U S I N G  I D L E 21

The editor window
The shell window can’t save your code, so when you 
close it, the code you typed is gone forever. When you 
are working on a game, you should use IDLE’s editor 
window. This will let you save your code. It also has 
built-in tools to help you write your programs and  
troubleshoot any errors.

▽ The editor window
To open the editor window  
in IDLE, click on the File menu at 
the top and choose New File.  
An empty editor will then appear. 
You’ll use the editor window to 
write the programs for the games 
in this book.

You can run Python programs from 
this menu, but you will run Pygame 
Zero programs a different way.

The name of the 
file is shown here.

The menu bar for  
the editor window is 
different from the one 
for the shell window.

 for count in range(10):

    if ((count % 2) == 0):

        print(count)

        print("is even")

    else:

        print(count)

        print("is odd")

EvensandOdds.py

IDLE        File        Edit        Format        Run        Window        Help

E X P E R T  T I P S

Colors in the code
IDLE automatically colors 
the text to highlight 
different parts of the code. 
The colors make it easier to 
understand the code, and 
they’re useful when you’re 
trying to spot mistakes.

Text in quotation marks
Any text in quotation 
marks is green. These are 
called strings.

Output
Any text produced when  
a program runs is blue. 

Keywords
Certain words, such as if and  
else, are special Python keywords. 
They are shown in orange.

Built-in commands
Python commands, 
such as print(), are 
shown in purple.

Symbols and names
Most code text is colored 
black.

Errors
Python uses red to 
alert you to any errors 
in your code.

Anything you tell 
Python to print 

gets displayed in 
the shell window.

You type in the code 
here. This program  

prints a list that tells 
you which numbers 
are even and which 

ones are odd.

US_020-021_Using_Idle.indd   21 22/02/18   12:24 pm



22 G E T T I N G  S T A R T E D

How it works
This Python program will check if everything 
is set up properly so you can start building 
some games. It uses Pygame Zero to display 
the word “Hello” on the screen. 

Draw a message  
on the screen

Start

End

Your first program
After you’ve installed Python, Pygame, 
and Pygame Zero, follow these steps  
to write your first Python program.  
This simple program will display a 
message on the screen.

2

1

Start IDLE 
Open IDLE on your 
computer. From the 
File menu, choose 
New File to create an 
empty editor window 
where you can write 
your program.

Set up a folder 
Before you start, create a folder called python-games 
somewhere easy to find, such as on your Desktop. 
Create another folder within your python-games 
folder and call it hello. 

E X P E R T  T I P S

Type carefully
Make sure you type all your code 
exactly as it’s written in this book.  
The grid will help you get it all correct. 
A tiny typo in just one line of code can 
cause a whole program to crash.

△ Hello flowchart
When building a game, programmers use 
diagrams called flowcharts to plan their game 
and show how it works. Each step is shown in  
a box, with an arrow leading to the next step. 
More complicated games might have steps 
with questions and more than one arrow 
leading to different boxes, depending on the 
answer to the question.

Hello!

File

  New File

  Open...

  Open Module...  

  Recent Files              ▶

  Class Browser              

python-games
hello

Desktop

US_022-023_Your_first_Program_1.indd   22 22/02/18   12:24 pm

23Y O U R  F I R S T  P R O G R A M

Save the file 
Now let‘s save the file. Go to the File menu and 
choose Save As.... Name the file hello.py  
and save it in the folder you created earlier.

Type the first line of code
Write this first line of code that tells Python 
to show, or “draw,” something on the 
screen. Press Enter when you’re done. 

Type the second line of code 
Then type in this second line of code. Check 
that it starts with four spaces. This is called  
an “indent,” and your code won’t work  
without it!

E X P E R T  T I P S

E X P E R T  T I P S

Saving your code
Always save your code before you run it, 
especially after you make any changes.  
If you don’t, Python will run an out-of-date 
version of your code.

Indents
There should be four blank spaces at the 
start of the second line of your code. This  
is called an “indent.” Python uses them to 
separate different blocks of code. Spaces 
and indents are very important—your code 
will not work if you miss them or put them 
in the wrong place. They’re one of the most 
common bugs in Python programs!

Save As:

hello

Cancel Save

hello.py

Tags:

Where:

This line of code is used 
to print something on 
the screen.

Add four blank spaces 
here if IDLE hasn’t 
done it automatically.

Make sure you 
have two closing 

parentheses here.

5

3

4

When you save a program, 
IDLE adds “.py” to the end 
automatically, so you don‘t 
have to type it in.

Here we go!

Hey, grab on!  
I’ll save you!

 def draw():

 def draw():

    screen.draw.text("Hello", topleft=(10, 10))

US_022-023_Your_first_Program_1.indd   23 22/02/18   12:24 pm



23Y O U R  F I R S T  P R O G R A M

Save the file 
Now let‘s save the file. Go to the File menu and 
choose Save As.... Name the file hello.py  
and save it in the folder you created earlier.

Type the first line of code
Write this first line of code that tells Python 
to show, or “draw,” something on the 
screen. Press Enter when you’re done. 

Type the second line of code 
Then type in this second line of code. Check 
that it starts with four spaces. This is called  
an “indent,” and your code won’t work  
without it!

E X P E R T  T I P S

E X P E R T  T I P S

Saving your code
Always save your code before you run it, 
especially after you make any changes.  
If you don’t, Python will run an out-of-date 
version of your code.

Indents
There should be four blank spaces at the 
start of the second line of your code. This  
is called an “indent.” Python uses them to 
separate different blocks of code. Spaces 
and indents are very important—your code 
will not work if you miss them or put them 
in the wrong place. They’re one of the most 
common bugs in Python programs!

Save As:

hello

Cancel Save

hello.py

Tags:

Where:

This line of code is used 
to print something on 
the screen.

Add four blank spaces 
here if IDLE hasn’t 
done it automatically.

Make sure you 
have two closing 

parentheses here.

5

3

4

When you save a program, 
IDLE adds “.py” to the end 
automatically, so you don‘t 
have to type it in.

Here we go!

Hey, grab on!  
I’ll save you!

 def draw():

 def draw():

    screen.draw.text("Hello", topleft=(10, 10))

US_022-023_Your_first_Program_1.indd   23 22/02/18   12:24 pm



24 G E T T I N G  S T A R T E D

7

Open Command Prompt or Terminal window
To run the program, you can use the command line. 
If you’re using a Windows computer, this is in the 
Command Prompt app. If you’re on a Mac, open  
the Terminal app.

Drag and drop the IDLE file
Keep the app open, and using Explorer (Windows) or 
Finder (Mac), go to the folder where you saved your 
program. Once you find it, drag and drop the .py file 
into the command line.

Type in the Pygame Zero command
To tell Pygame Zero to run the game, type 
pgzrun into the command line and leave  
a space, but don’t press Enter yet!

Run the program 
Now that you’ve typed in the pgzrun command 
and your computer knows where to find the IDLE 
file, press Enter. This will launch Pygame Zero.

9 Final screen If your program is working correctly, you’ll see  
a window with a “Hello” message written in the  
top-left corner of the screen. Good job! Now  
it’s time to become a Python games coder!

10

Don’t forget to leave  
a space after pgzrun.

The location of your  
IDLE file will appear here 
when you drop it in.

Drag and drop hello.py  
into the Command Prompt  
or Terminal window.

6

8

Sanjay – bash – 80x24

Sanjay – bash – 80x24

Last login: Sun Sep 3 17:18:36 on ttys000

LC-0797:~ sanjay$ pgzrun 

Last login: Sun Sep 3 17:18:36 on ttys000

LC-0797:~ sanjay$ pgzrun User/Documents/python-games/hello.py

Running your program
Because your games use Pygame Zero,  
you usually have to run them in a different 
way from normal Python programs. It isn’t 
difficult once you get used to it, however.

This is what the icon 
for Command Prompt 
looks like.

This is what the icon 
for the Terminal 
window looks like.

Name

hello

python-games

hello.py

c:\ >_

US_024-025_Your_first_Program_2.indd   24 14/03/18   4:29 PM

import pgzrun

def draw():

    screen.draw.text("Hello", topleft=(10, 10))

pgzrun.go()

25Y O U R  F I R S T  P R O G R A M

Type import pgzrun at the very top of your program and 
pgzrun.go() at the very end. The entire code for your game 
should now sit between these two lines.

To run the game in IDLE go to the 
Run menu and click Run Module,  
or just press the F5 key.

I M P O R T A N T !

Fix mistakes
If nothing happens when you run one of your programs, or if you 
get an error message—don’t panic! It’s normal to experience 
errors (these are called “bugs”) when coding a program. If an error 
message appears, ask yourself the following questions:

 ▪ Does the code match the given example exactly? 
 ▪ Have I saved the program in the right folder? 
 ▪  Have I typed pgzrun correctly?
 ▪ Are Pygame and Pygame Zero installed correctly?

Running your program using IDLE
It’s possible to run your Pygame Zero programs using IDLE. To do 
this you need to add two extra lines to your code. It’s a good idea to 
wait until you have finish writing your program before doing this.  

E X P E R T  T I P S

Rerunning programs
When you’re building a program, you need to run the code 
frequently to check for bugs. To save time, you can press the 
Up arrow key in Command Prompt or Terminal to see your 
recent commands. You can then press Enter to run one of 
them again. If your game is still running, you need to close it 
before rerunning your code. If you don’t, nothing will happen!

I think there’s some bug 
spray on pages 44–47!

This should now be the 
last line of your program.

This should now be the 
first line of your program.

21

Run

  Python Shell

  Check Module

  Run Module...   F5

US_024-025_Your_first_Program_2_new.indd   25 20/03/18   2:34 PM



import pgzrun

def draw():

    screen.draw.text("Hello", topleft=(10, 10))

pgzrun.go()

25Y O U R  F I R S T  P R O G R A M

Type import pgzrun at the very top of your program and 
pgzrun.go() at the very end. The entire code for your game 
should now sit between these two lines.

To run the game in IDLE go to the 
Run menu and click Run Module,  
or just press the F5 key.

I M P O R T A N T !

Fix mistakes
If nothing happens when you run one of your programs, or if you 
get an error message—don’t panic! It’s normal to experience 
errors (these are called “bugs”) when coding a program. If an error 
message appears, ask yourself the following questions:

 ▪ Does the code match the given example exactly? 
 ▪ Have I saved the program in the right folder? 
 ▪  Have I typed pgzrun correctly?
 ▪ Are Pygame and Pygame Zero installed correctly?

Running your program using IDLE
It’s possible to run your Pygame Zero programs using IDLE. To do 
this you need to add two extra lines to your code. It’s a good idea to 
wait until you have finish writing your program before doing this.  

E X P E R T  T I P S

Rerunning programs
When you’re building a program, you need to run the code 
frequently to check for bugs. To save time, you can press the 
Up arrow key in Command Prompt or Terminal to see your 
recent commands. You can then press Enter to run one of 
them again. If your game is still running, you need to close it 
before rerunning your code. If you don’t, nothing will happen!

I think there’s some bug 
spray on pages 44–47!

This should now be the 
last line of your program.

This should now be the 
first line of your program.

21

Run

  Python Shell

  Check Module

  Run Module...   F5

US_024-025_Your_first_Program_2_new.indd   25 20/03/18   2:34 PM



US_026-027_Chapter_opener_2.indd   26 22/02/18   1:40 pm

Learning 
the basics

Y T H O NP

US_026-027_Chapter_opener_2.indd   27 22/02/18   1:40 pm



Learning 
the basics

Y T H O NP

US_026-027_Chapter_opener_2.indd   27 22/02/18   1:40 pm



28 L E A R N I N G  T H E  B A S I C S

Creating variables
Variables are used to store and label pieces  
of information. You’ll use them a lot in your 
code—for example, to hold your current score  
or keep track of how many lives you have left.

How to create a variable
You need to give each variable a name that describes 
what data is stored inside it. What the variable stores is 
called its value. Type the name followed by an equals 
sign, then type the value, with a space between each 
part. This is called “assigning a value” to the variable.

This is the 
variable’s name.

This is the value 
stored in the variable.

1 Assign a valueOpen IDLE’s shell window. Type this line  
of code to create a variable called score  
and assign a value to it. 

Print the value 
Now type print(score) into the window after 
the code you typed in Step 1. Press Enter to 
see what happens.

2

E X P E R T  T I P S

Naming variables
Always choose a meaningful name  
for each variable in your programs.  
For example, a variable for tracking the 
number of attempts a player has left 
could be called attempts_remaining, 
rather than just attempts or a. Variable 
names can contain letters, numbers, and 
underscores, but they should always start 
with a letter. Follow these rules and you 
won’t go wrong.

Dos and don’ts
 ▪ Always start the variable’s name with a letter.
 ▪ Any letter or number can be used in the name.
 ▪ Symbols such as -, /, #, @ aren’t allowed.
 ▪ Do not use spaces. An underscore ( _ ) can be used instead.
 ▪ Uppercase (capital) and lowercase letters are different.  

   Python will treat Score and score as two different variables.
 ▪ Avoid words that are used in Python or Pygame Zero as  

   commands, such as “function” or “screen.”

This is the  
value of score.

The print() function displays the value 
of the variable in the parentheses.

25

>>> score = 0

>>> score = 0

>>> print(score)

0

△ Storage box
A variable is like a box with a name label. 
You can store data in the box and then use 
its name to find the data again when you 
need to use it.

US_028-029_Variables_1.indd   28 22/02/18   12:24 pm

29C R E A T I N G  V A R I A B L E S

Using numbers
Variables can be used to store numbers,  
which can then be used in calculations. You 
can use them with symbols, just like you do 
in math. Be careful with multiplication and 
division, though, because they use different 
symbols from the ones you use at school.

1 A simple calculation Type this code into the shell window. It  
uses two variables, x and y, which store 
integers to perform a simple calculation. 
Press Enter to see the answer.

2 Change a value To change the value of a variable, just assign a 
new value to it. In this code, assign the value 5 
to x. Print the value assigned to y again. What 
do you think the result will be?

* =
L I N G O

Integers and floats
In coding, different types of numbers can be 
stored in variables. Whole numbers are called 
“integers,” and numbers with a decimal point  
in them are called “floats.” Integers are usually 
used to count things, like a player’s score, 
whereas floats are usually used for 
measurements, such as temperature.

1 sheep  
(an integer)

0.5 sheep 
(a float)

Update the value 
The value of y needs to be updated to  
get the correct result. To do this, you need  
to run the y = x * 3 calculation again. Now  
the code assigns the new value to y after x  
has been changed.

3

Create a new variable, x, 
and assign the value 2 to it.

The result of 
the calculation.

Multiply x by 3 and assign the 
result to another variable, y.

Print the value 
assigned to y.

Change the 
value of x.

The result hasn’t changed—
next we’ll find out why. 

>>> x = 2

>>> y = x * 3

>>> print(y)

6

>>> x = 5

>>> print(y)

6

Symbol

+

–

*

/

add

subtract

multiply

divide

Meaning

You need to redo the 
calculation to update 
the value of y.

>>> x = 5

>>> y = x * 3

>>> print(y)

15

US_028-029_Variables_1.indd   29 22/02/18   12:24 pm



29C R E A T I N G  V A R I A B L E S

Using numbers
Variables can be used to store numbers,  
which can then be used in calculations. You 
can use them with symbols, just like you do 
in math. Be careful with multiplication and 
division, though, because they use different 
symbols from the ones you use at school.

1 A simple calculation Type this code into the shell window. It  
uses two variables, x and y, which store 
integers to perform a simple calculation. 
Press Enter to see the answer.

2 Change a value To change the value of a variable, just assign a 
new value to it. In this code, assign the value 5 
to x. Print the value assigned to y again. What 
do you think the result will be?

* =
L I N G O

Integers and floats
In coding, different types of numbers can be 
stored in variables. Whole numbers are called 
“integers,” and numbers with a decimal point  
in them are called “floats.” Integers are usually 
used to count things, like a player’s score, 
whereas floats are usually used for 
measurements, such as temperature.

1 sheep  
(an integer)

0.5 sheep 
(a float)

Update the value 
The value of y needs to be updated to  
get the correct result. To do this, you need  
to run the y = x * 3 calculation again. Now  
the code assigns the new value to y after x  
has been changed.

3

Create a new variable, x, 
and assign the value 2 to it.

The result of 
the calculation.

Multiply x by 3 and assign the 
result to another variable, y.

Print the value 
assigned to y.

Change the 
value of x.

The result hasn’t changed—
next we’ll find out why. 

>>> x = 2

>>> y = x * 3

>>> print(y)

6

>>> x = 5

>>> print(y)

6

Symbol

+

–

*

/

add

subtract

multiply

divide

Meaning

You need to redo the 
calculation to update 
the value of y.

>>> x = 5

>>> y = x * 3

>>> print(y)

15

US_028-029_Variables_1.indd   29 22/02/18   12:24 pm



30 L E A R N I N G  T H E  B A S I C S

Working with strings
A string is any data made up of a sequence of letters 
or other characters. Words and sentences are stored 
as strings. In Python, most programs use at least 
one string. Any character that you can type on  
your keyboard can be stored in a string. Y T H O NP

E X P E R T  T I P S

Length of a string
For some programs, it’s useful to be able to count 
the number of characters in a string. You can do  
this using the function len(). A function is a useful 
operation that contains multiple lines of code,  
so you don’t have to enter them manually. To  
find out the number of characters in the string  
Hello Martin, type this line of code into the shell  
after you’ve created the string, then hit Enter.

What’s the weather 
like up there?

Strings in variables
Strings can be assigned to variables. Type this code 
into the shell window. It assigns the string Martin 
to the name variable and then displays it. Strings 
must be written between quotation marks to show 
where they start and end.

1 Quotation marks tell the computer 
that it’s a string.

Press Enter to  
print the string. Remember the space 

after the greeting.

The + symbol can 
be used to join 
strings together.

Joining strings together
Variables can be combined to create new ones.  
For example, you can add two strings and store the 
combination in a new variable. Type this code into 
the shell window to try this out. You can change the 
greeting and the name to make a new message.

2

Remember the quotation  
marks, and leave a space  

after Hello.

message is a new variable  
that contains the greeting  
and name variables. 

The number  
of characters, 
including spaces,  
is counted.

>>> name = "Martin"

>>> print(name)

Martin

>>> len(message)

12

>>> greeting = "Hello "

>>> name = "Martin"

>>> message = greeting + name

>>> print(message)

Hello Martin

!

US_030-031_Variables_2.indd   30 23/02/18   2:31 pm

31C R E A T I N G  V A R I A B L E S

Making lists
A list is used to store a collection of data. It can  
hold many different values and keep them in order. 
For example, a list can store a deck of cards for a 
game, such as Snap, so the code knows which card  
to deal next. The position of each value in the list  
is identified with a number, starting from 0. You  
can use these numbers to change list values.

Getting items from a list
It’s easy to work with a list once you have  
all your values in it. To get an item from a 
list, type the name of the list, followed by 
the item’s position in the list within square 
parentheses. But watch out—in Python, the 
first position in a list is 0, not 1. Now try 
getting different cards out of your cards list. 

3

List in a variable
It would be much easier to use a list to store all the 
values of the cards instead of setting up so many 
variables individually. To create a list, surround the 
values you want to store with square brackets. 

2

There’s no  
need to type  
this code out.

More than one variable
Imagine you’re coding a multiplayer game 
and want to have a different variable for 
each card. You would need 52 variables to 
store a whole deck of cards, but we’ll just 
work with six for now.

1 >>> card1 = "1 hearts"
>>> card2 = "2 hearts"

>>> card3 = "3 hearts"

>>> card4 = "4 hearts"

>>> card5 = "5 hearts"

>>> card6 = "6 hearts"

The values must be 
separated by commas.

This line gets the first 
value in the list.

This is the last 
value in our list.

For our small list, the last 
position is 5, but for the entire 
cards list it would be 51.

>>> cards[0] 

>>> "1 hearts"

>>> cards[5]

>>> "6 hearts"

>>> cards = ["1 hearts", "2 hearts", "3 hearts", "4 hearts", "5 hearts", "6 hearts"]

The list is assigned to  
the variable cards.

US_030-031_Variables_2.indd   31 22/02/18   12:24 pm



31C R E A T I N G  V A R I A B L E S

Making lists
A list is used to store a collection of data. It can  
hold many different values and keep them in order. 
For example, a list can store a deck of cards for a 
game, such as Snap, so the code knows which card  
to deal next. The position of each value in the list  
is identified with a number, starting from 0. You  
can use these numbers to change list values.

Getting items from a list
It’s easy to work with a list once you have  
all your values in it. To get an item from a 
list, type the name of the list, followed by 
the item’s position in the list within square 
parentheses. But watch out—in Python, the 
first position in a list is 0, not 1. Now try 
getting different cards out of your cards list. 

3

List in a variable
It would be much easier to use a list to store all the 
values of the cards instead of setting up so many 
variables individually. To create a list, surround the 
values you want to store with square brackets. 

2

There’s no  
need to type  
this code out.

More than one variable
Imagine you’re coding a multiplayer game 
and want to have a different variable for 
each card. You would need 52 variables to 
store a whole deck of cards, but we’ll just 
work with six for now.

1 >>> card1 = "1 hearts"
>>> card2 = "2 hearts"

>>> card3 = "3 hearts"

>>> card4 = "4 hearts"

>>> card5 = "5 hearts"

>>> card6 = "6 hearts"

The values must be 
separated by commas.

This line gets the first 
value in the list.

This is the last 
value in our list.

For our small list, the last 
position is 5, but for the entire 
cards list it would be 51.

>>> cards[0] 

>>> "1 hearts"

>>> cards[5]

>>> "6 hearts"

>>> cards = ["1 hearts", "2 hearts", "3 hearts", "4 hearts", "5 hearts", "6 hearts"]

The list is assigned to  
the variable cards.

US_030-031_Variables_2.indd   31 22/02/18   12:24 pm



L E A R N I N G  T H E  B A S I C S32

Making decisions
Playing a game involves making decisions  
about what to do next. These are often  
based on answers to questions. For 
example, “Do I have any lives left?”; “Is 
someone chasing me?”; “Have I beaten 
the highest score?”

Comparisons
Computers also make decisions about what to 
do next by asking questions. These questions 
usually involve comparing two values. For 
instance, is one number bigger than the other? 
If it is, the computer might skip a block of code 
that it would otherwise have run. 

△ Boolean values
The questions that computers ask only 
have two possible answers: True or False. 
Python calls these two values Boolean 
values, and they must always start with  
a capital letter. You can store a Boolean 
value in a variable.

△ Logical operators
The symbols and words shown here are 
called “logical operators,” and they help 
computers make comparisons in order  
to ask questions.

>>> answer_one = True

>>> answer_two = False Boolean value

Variable

This compares your 
age with the variable.

The code prints the 
message if the two match.

This sets the 
value of  

the variable.

E X P E R T  T I P S

Equals signs
In Python, there are two types of equals sign: a single equals 
sign = and a double equals sign ==. These signs have different 
meanings. You use a single equals sign when you want to store 
a value in a variable. For example, lives = 10 stores the value 
10 in the variable lives. However, use a double equals sign 
when you want to compare two values.

Which door should  
we go through?

>>> age = 10

>>> if age == 10:

        print("You are ten years old.")

Meaning

equal to

greater than

less than

not equal to

==

!=

<

>

Symbol

US_032-033_Making_Decisions_1.indd   32 23/02/18   2:31 pm

M A K I N G  D E C I S I O N S 33

>>> monsters = 3

>>> coins = 4

>>> coins > monsters

True

>>> coins > monsters

True

>>> monsters < coins

True

>>> monsters == coins

False

>>> (monsters == 3) and (coins == 4)

True

>>> (monsters == 7) or (coins == 4)

True

Monsters and coins
Let’s try an example in the shell window. You  
can use the variables monsters and coins  
to represent three monsters and four coins, 
respectively. Type in the following code.

This variable 
stores the  
number of coins.

This expression is 
True because the 
number of coins is 
greater than the 
number of monsters. 

This expression  
is True because  
the number of 
monsters is less 
than the number 
of coins.

This expression  
is False because 
the number of 
monsters and the 
number of coins 
aren’t equal.

When using and, both  
the comparisons need  
to be correct for the 
Boolean value to be True.

coins is a variable. 

> is a logical 
operator.

monsters is a 
variable. 

True is a 
Boolean value.

When using or, only  
one of the comparisons  

needs to be correct for the 
Boolean value to be True.

This value is stored  
in the variable 
monsters.

▽ Let’s compare
Now type the following lines of code to compare 
the values in the two variables. After typing each 
line, press Enter and Python will tell you if the 
statements are True or False.

▽ Multiple comparisons
In Python, you can also combine more than 
one comparison by using the logical operators 
and and or. 

L I N G O

Boolean expressions
Statements that contain variables and values 
and use logical operators always give you a 
Boolean value—True or False. Because of this, 
these statements are called Boolean expressions. 
All of the statements about monsters and coins 
in the examples are Boolean expressions.

US_032-033_Making_Decisions_1.indd   33 22/02/18   12:24 pm



M A K I N G  D E C I S I O N S 33

>>> monsters = 3

>>> coins = 4

>>> coins > monsters

True

>>> coins > monsters

True

>>> monsters < coins

True

>>> monsters == coins

False

>>> (monsters == 3) and (coins == 4)

True

>>> (monsters == 7) or (coins == 4)

True

Monsters and coins
Let’s try an example in the shell window. You  
can use the variables monsters and coins  
to represent three monsters and four coins, 
respectively. Type in the following code.

This variable 
stores the  
number of coins.

This expression is 
True because the 
number of coins is 
greater than the 
number of monsters. 

This expression  
is True because  
the number of 
monsters is less 
than the number 
of coins.

This expression  
is False because 
the number of 
monsters and the 
number of coins 
aren’t equal.

When using and, both  
the comparisons need  
to be correct for the 
Boolean value to be True.

coins is a variable. 

> is a logical 
operator.

monsters is a 
variable. 

True is a 
Boolean value.

When using or, only  
one of the comparisons  

needs to be correct for the 
Boolean value to be True.

This value is stored  
in the variable 
monsters.

▽ Let’s compare
Now type the following lines of code to compare 
the values in the two variables. After typing each 
line, press Enter and Python will tell you if the 
statements are True or False.

▽ Multiple comparisons
In Python, you can also combine more than 
one comparison by using the logical operators 
and and or. 

L I N G O

Boolean expressions
Statements that contain variables and values 
and use logical operators always give you a 
Boolean value—True or False. Because of this, 
these statements are called Boolean expressions. 
All of the statements about monsters and coins 
in the examples are Boolean expressions.

US_032-033_Making_Decisions_1.indd   33 22/02/18   12:24 pm



L E A R N I N G  T H E  B A S I C S34

>>> score = 110

>>> snails = 3

>>> (score > 100) and (snails >= 4)

False

◁ Eye on the ball
Imagine you’re playing a soccer game and you need to 
decide which way to aim the ball at the goal. You could 
ask yourself, “Is the goalkeeper near the left side of the 
goal?” If he is, you aim at the right side of the goal. If  
he isn’t, you aim left. In Python, the different routes 
through a program lead to different blocks of code. The 
computer uses a Boolean expression, or a condition, to 
decide which blocks to run. 

Store values  
in variables.

This is a Boolean expression 
meaning “score greater  

than 100 and snails more  
than or equal to 4.”

This shows you cannot 
progress to Level 2 yet.

Branching
Sometimes you need to make decisions when 
playing a game. Should you turn right to 
investigate the library or turn left to look at 
the kitchen? Computer programs often contain 
code that runs only in certain situations. This 
means the computer makes decisions about 
which parts of the code to run.

Level up
Imagine you’re creating a game that has two levels. To get 
to Level 2, you need to have at least four magic snails and 
a score of more than 100 points. At this point, you have 
110 points but only three magic snails. Use the shell 
window to see if you can still get to Level 2. First, create 
variables for the score and number of snails collected and 
assign the correct values to them. Then type the rules for 
getting to Level 2 as a Boolean expression.

L2
L1

US_034-035_Making_Decisions_2.indd   34 14/03/18   12:18 PM

M A K I N G  D E C I S I O N S 35

ghosts = 3

if ghosts > 1:

    print("It’s so spoooooky!")

elif ghosts > 0:

    print("Get that ghost!")

else:

    print("Ghosts all gone!")

▽ One branch
The simplest type of branching command is an if 
statement. It only has one branch, which the computer 
takes if the condition is True.

▽ Two branches
What if you want the program to do one thing if a 
condition is True, but another if it’s False? In this case,  
you need a command with two possible branches,  
called an if-else statement.

◁ More than two branches
When there are more than two possible paths, the 
command elif (short for “else-if”) can be used in 
your program. In the following example, you need 
to capture several ghosts in one go.  

How it works
In this example, the program checks to see the number 
of spells you’ve cast. If it’s more than ten, the program 
prints “You gained the title Enchanter!” If the number  
of spells you’ve cast is less than ten, the message  
is not printed.

How it works
In this example, there’s a variable 
called game_over, which is set to 
True. The if statement checks to  
see if game_over is True. If it is, the 
program prints “Game Over!” If it 
isn’t, the else statement runs to 
print “Keep playing!” Try running this 
code with game_over set to True, 
then False, to see this in action.

How it works
In this program, the variable ghosts has been set  
to 3, so the first branch is True and the program 
prints “It’s so spoooooky!” But if the value in ghosts 
was 1, the first branch would be False, so the 
second branch would run, printing “Get that ghost!” 
If neither of the above branches are True, the 
program moves on to the third branch to print 
“Ghosts all gone!” An elif statement must always 
come after if and before else.

This block runs  
if the second 
condition is True. This block runs if 

both conditions 
are False.

This branch runs if 
the condition is True.

spells = 11

if (spells > 10):

    print("You gained the title Enchanter!")

Behold! I grant 
thee the title... 

Enchanter!

GAME 
OVER!

This is the first condition.

This comparison 
is the condition.

game_over = True

if game_over:

    print("Game Over!")

else:

    print("Keep playing!")

This block runs 
if the condition 
is False.

US_034-035_Making_Decisions_2.indd   35 14/03/18   12:18 PM



M A K I N G  D E C I S I O N S 35

ghosts = 3

if ghosts > 1:

    print("It’s so spoooooky!")

elif ghosts > 0:

    print("Get that ghost!")

else:

    print("Ghosts all gone!")

▽ One branch
The simplest type of branching command is an if 
statement. It only has one branch, which the computer 
takes if the condition is True.

▽ Two branches
What if you want the program to do one thing if a 
condition is True, but another if it’s False? In this case,  
you need a command with two possible branches,  
called an if-else statement.

◁ More than two branches
When there are more than two possible paths, the 
command elif (short for “else-if”) can be used in 
your program. In the following example, you need 
to capture several ghosts in one go.  

How it works
In this example, the program checks to see the number 
of spells you’ve cast. If it’s more than ten, the program 
prints “You gained the title Enchanter!” If the number  
of spells you’ve cast is less than ten, the message  
is not printed.

How it works
In this example, there’s a variable 
called game_over, which is set to 
True. The if statement checks to  
see if game_over is True. If it is, the 
program prints “Game Over!” If it 
isn’t, the else statement runs to 
print “Keep playing!” Try running this 
code with game_over set to True, 
then False, to see this in action.

How it works
In this program, the variable ghosts has been set  
to 3, so the first branch is True and the program 
prints “It’s so spoooooky!” But if the value in ghosts 
was 1, the first branch would be False, so the 
second branch would run, printing “Get that ghost!” 
If neither of the above branches are True, the 
program moves on to the third branch to print 
“Ghosts all gone!” An elif statement must always 
come after if and before else.

This block runs  
if the second 
condition is True. This block runs if 

both conditions 
are False.

This branch runs if 
the condition is True.

spells = 11

if (spells > 10):

    print("You gained the title Enchanter!")

Behold! I grant 
thee the title... 

Enchanter!

GAME 
OVER!

This is the first condition.

This comparison 
is the condition.

game_over = True

if game_over:

    print("Game Over!")

else:

    print("Keep playing!")

This block runs 
if the condition 
is False.

US_034-035_Making_Decisions_2.indd   35 14/03/18   12:18 PM



36 L E A R N I N G  T H E  B A S I C S

Playing with loops
When you’re coding a game, you often need  
to run the same bit of code several times, 
but it would be pretty boring if you had to 
type it in every single time. Luckily, you can 
use a loop to run the same block of code 
over and over again. There are many 
different types of loops.

Range
In Python, the word range followed  
by two numbers in parentheses stands 
for “all the numbers in the list from the 
first number to the second-to-the-last 
number.” Therefore, range(1, 5) 
contains the numbers 1, 2, 3, and 4,  
but not 5, so the loop runs four times. 

E X P E R T  T I P S

“For” loops
When you know exactly how many times you 
want a loop to repeat, you can use a for loop. In 
this example, the code prints “You are the high 
scorer!” ten times. Try out the code for yourself 
in the shell window.

This is the  
loop variable.

The code that gets 
repeated is known  
as the “loop body.”

Loop variable
The loop variable keeps track of how many 
times the loop has run so far. At the start of the 
loop, it’s equal to the first number in the range. 
The second time around, it’s equal to the 
second number in the range, and so on. Once 
it completes the second-to-last number in the 
range, the loop stops.

Loop body 
The block of code that gets repeated in a loop is  
called the loop body. You must always indent the 
commands in the body four spaces from the  
beginning of the line that starts the for loop. 

How are you  
doing that?

>>> for count in range(1, 11):

        print("You are the high scorer!")

Just three more laps.  
I mean loops!

US_036-037_Loopy_Loops_1.indd   36 22/02/18   12:24 pm

37

>>> robots = ["Bing", "Bleep", "Bloop"]

>>> colors = ["red", "orange", "purple"]

>>> index = 0

>>> for each in robots:

        print("My name is " + robots[index] + ". I am " + colors[index])

        index = index + 1

P L A Y I N G  W I T H  L O O P S

Looping over a list
Gaming programs often use a collection  
of items grouped together in a list. If you  
want to do something with each item  
on the list, you can use a for loop.

Looping over two lists
Python can loop through a list from start to finish more 
or less automatically. But if you want to loop through 
two lists at once, you need to use an extra variable to 
tell Python to move through both lists.

How it works
We create a temporary variable called 
robot that holds a single item in the 
list. The value in robot is updated 
each time around the loop, so that it 
holds Bing, then Bleep, and finally 
Bloop. Once it reaches the end of the 
list, the loop stops.

The index variable 
keeps track of the 
position each list is at.

index will help Python 
move through both 

lists in order.

This line updates 
index so Python 

moves through the 
lists with each loop.

Robots with colors 
In this example, we have two lists. One is called robots and 
holds the names of the robots. The other is called colors and 
tells you the color of each robot. This program uses a variable 
called index to move through both lists, printing out each 
robot’s name and also what color it is. 

Page 31 will  
help you out  

with lists.

Listing robots
In this example, there is a list that contains 
the names of three robots that the player 
has to escape from in a game.

robot is a temporary variable 
that moves along the robots 
list each time the loop runs.

Python will add 
one of the robots’ 
names here.

>>> robots = ["Bing", "Bleep", "Bloop"]

>>> for robot in robots:

        print("I am a robot. My name is " + robot)

US_036-037_Loopy_Loops_1.indd   37 22/02/18   12:24 pm



37

>>> robots = ["Bing", "Bleep", "Bloop"]

>>> colors = ["red", "orange", "purple"]

>>> index = 0

>>> for each in robots:

        print("My name is " + robots[index] + ". I am " + colors[index])

        index = index + 1

P L A Y I N G  W I T H  L O O P S

Looping over a list
Gaming programs often use a collection  
of items grouped together in a list. If you  
want to do something with each item  
on the list, you can use a for loop.

Looping over two lists
Python can loop through a list from start to finish more 
or less automatically. But if you want to loop through 
two lists at once, you need to use an extra variable to 
tell Python to move through both lists.

How it works
We create a temporary variable called 
robot that holds a single item in the 
list. The value in robot is updated 
each time around the loop, so that it 
holds Bing, then Bleep, and finally 
Bloop. Once it reaches the end of the 
list, the loop stops.

The index variable 
keeps track of the 
position each list is at.

index will help Python 
move through both 

lists in order.

This line updates 
index so Python 

moves through the 
lists with each loop.

Robots with colors 
In this example, we have two lists. One is called robots and 
holds the names of the robots. The other is called colors and 
tells you the color of each robot. This program uses a variable 
called index to move through both lists, printing out each 
robot’s name and also what color it is. 

Page 31 will  
help you out  

with lists.

Listing robots
In this example, there is a list that contains 
the names of three robots that the player 
has to escape from in a game.

robot is a temporary variable 
that moves along the robots 
list each time the loop runs.

Python will add 
one of the robots’ 
names here.

>>> robots = ["Bing", "Bleep", "Bloop"]

>>> for robot in robots:

        print("I am a robot. My name is " + robot)

US_036-037_Loopy_Loops_1.indd   37 22/02/18   12:24 pm



38 L E A R N I N G  T H E  B A S I C S

How it works
robots[index] and colors[index] both use the value 
of index to decide which item in their list to print. 
Since index is set to 0 to begin with, both lists will 
start with the first item—remember the first position 
in Python lists is always 0, not 1. Since Bing is at 
position 0 of the list robots and red is at position 0  
of the list colors, that means Bing is red. Each time 
the loop runs, it adds 1 to index, moving each list 
onto the next item, so Bleep will be orange and  
Bloop will be purple. The loop will continue until  
it reaches the end of the lists.

Indentation error
Just like the for loop, the code in  
the body of a while loop must be 
four spaces further in than the line 
starting the loop. If you don’t do this, 
Python will show an error message 
saying “unexpected indent.”

SyntaxError

OK

unexpected indent

Nobody enters without 
the magic key!

Loop condition
A while loop includes a question whose answer can either 
be True or False. This is called a loop condition. The while 
loop will only start if the answer to the loop condition is 
True. Imagine you are playing a game where a castle is 
guarded by a dragon that checks if you have the magic 
key. “Do you have the magic key?” would be the loop 
condition and the castle would be the loop body. If you 
have the magic key, the loop condition is True and you 
can enter the castle. But if you don’t have the key, the 
loop condition is False, so you can’t get into the loop! 

“While” loops
Sometimes, while coding a program, you  
might not know exactly how many times  
you want a loop to repeat. Don’t worry! In  
this case, you can use a while loop. 

Dude, when are 
we supposed  

to stop?

E X P E R T  T I P S

US_038-039_Loopy_Loops_2.indd   38 22/02/18   12:24 pm

39P L A Y I N G  W I T H  L O O P S

How it works
The loop condition here is answer == "y", which means 
you want to throw a water balloon. The loop body prints 
“Splash!!!” to show a balloon being thrown and asks if  
you want to throw another. If your answer is y, the loop 
condition is True again and the loop is repeated. If your 
answer is n (or anything other than y), the loop condition 
is False and the program exits the loop and prints 
“Goodbye!” before ending.

Infinite loops
Sometimes, you might want a loop  
to repeat as long as the program is 
running. This can be done with an 
infinite loop. You can make an infinite 
loop by setting the loop condition  
to True, so that it keeps repeating  
a block of code forever!

Making an escape
If you don’t want to run an infinite loop,  
it’s important to make sure the body of a 
while loop does something that could make 
the loop condition False. But don’t worry if 
you accidentally code a program with an 
infinite loop—you can escape it by holding 
down the Ctrl key and pressing the C key 
along with it.

There is no False 
option to escape 
the loop.

This line gets the new 
value of answer (used 
in loop condition).

This line gets the value of 
answer (used in loop condition).

When the loop is complete, 
this line prints “Goodbye!”

Balloon fight
In this example, the 
program asks if you want 
to throw a water balloon.  
If your answer is y, it prints 
“Splash!!!” and asks if you 
want to throw another 
balloon. If your answer  
is n, the program prints 
“Goodbye!” and ends.

It’s really wet  
in here! 

They got  
away!

answer = input("Throw a water balloon? (y/n)")

 while answer == "y":

    print("Splash!!!")

    answer = input("Throw another water balloon? (y/n)")

print("Goodbye!")

>>> while True:

        print("This is an infinite loop!")

US_038-039_Loopy_Loops_2.indd   39 22/02/18   12:24 pm



39P L A Y I N G  W I T H  L O O P S

How it works
The loop condition here is answer == "y", which means 
you want to throw a water balloon. The loop body prints 
“Splash!!!” to show a balloon being thrown and asks if  
you want to throw another. If your answer is y, the loop 
condition is True again and the loop is repeated. If your 
answer is n (or anything other than y), the loop condition 
is False and the program exits the loop and prints 
“Goodbye!” before ending.

Infinite loops
Sometimes, you might want a loop  
to repeat as long as the program is 
running. This can be done with an 
infinite loop. You can make an infinite 
loop by setting the loop condition  
to True, so that it keeps repeating  
a block of code forever!

Making an escape
If you don’t want to run an infinite loop,  
it’s important to make sure the body of a 
while loop does something that could make 
the loop condition False. But don’t worry if 
you accidentally code a program with an 
infinite loop—you can escape it by holding 
down the Ctrl key and pressing the C key 
along with it.

There is no False 
option to escape 
the loop.

This line gets the new 
value of answer (used 
in loop condition).

This line gets the value of 
answer (used in loop condition).

When the loop is complete, 
this line prints “Goodbye!”

Balloon fight
In this example, the 
program asks if you want 
to throw a water balloon.  
If your answer is y, it prints 
“Splash!!!” and asks if you 
want to throw another 
balloon. If your answer  
is n, the program prints 
“Goodbye!” and ends.

It’s really wet  
in here! 

They got  
away!

answer = input("Throw a water balloon? (y/n)")

 while answer == "y":

    print("Splash!!!")

    answer = input("Throw another water balloon? (y/n)")

print("Goodbye!")

>>> while True:

        print("This is an infinite loop!")

US_038-039_Loopy_Loops_2.indd   39 22/02/18   12:24 pm



40 L E A R N I N G  T H E  B A S I C S

Functions
Functions are really handy tools for all coders. 
They let you name useful chunks of code so 
that you can use them over and over again 
without having to type the whole thing out 
each time—you just have to type in the name! 
Python comes with some built-in functions, 
but you can also write your own to handle 
tasks specific to your games.

Using functions
When you want to use one of Python’s built-in functions, 
all you need to do is “call” it by typing out its name 
followed by a pair of empty parentheses. This tells Python 
to run the code saved in that function. If you need to  
give a function some data to use, it goes inside the 
parentheses. This is called a “parameter.”

Built-in functions
Python comes with a number of built-in functions.  
They allow you to perform a variety of tasks, from 
printing messages to converting one type of data  
to another.

The string parameter 
is printed.

>>> print("This is a parameter")

This is a parameter

This calls the print() function 
with a string parameter.

△ print()
One of the most commonly used functions is print(). 
This function lets you display a string (a series of 
letters, numbers, or other characters) on the screen. 
The string is a parameter in this case.

L I N G O

Function terms
Call  When you want to use a 
function, you “call” it by typing 
the name of the function, 
followed by parentheses, which 
may contain a parameter.

Define  When you use the  
def keyword and write your 
own code for a function, you 
are “defining” that function.

Parameter  A parameter is  
a piece of data (information) 
that you give a function to use.

Return value  A return value  
is data that you pass from a 
function back to the main code 
by using the keyword return.

I need to build this  
very carefully!

US_040-041_Functions_1.indd   40 22/02/18   12:24 pm

41F U N C T I O N S

▷ input() 
This function lets the player enter information for the 
game to use, rather than the coder putting it in the 
original code. For example, imagine you’re creating  
a game and you want to create a variable to store  
the player’s name, but you don’t know what they’re 
called. You can use input() to make the game ask the 
player what their name is. Their answer becomes a 
return value, which the function will then assign to 
the name variable.

You can type your 
own name in here.

input() has assigned the 
answer to the name variable.

input() asks the 
user what their 
name is. 

This is a variable 
that will later store 
the player’s name.

Another way to call functions
Some types of data, such as integers and strings, have their 
own built-in functions that are used to manipulate or 
change that data. These are known as “member” functions 
and can be called by placing a dot immediately after the 
data, followed by the name of the function and a pair of 
parentheses. Try these out in the shell window. 

△ count()
This function is used with strings. It is called on one 
string, with another string as a parameter of the 
function count(). The return value tells you how many 
times the second string appears in the first string.

△ reverse()
You can also call a member function on a variable.  
In this example, the function reverse() is used  
to reverse the order of the list of numbers stored  
in the variable countdown.

>>> "functions are fun".count("fun")

2

A list of numbers is 
assigned to a variable.

Members only

△ upper()
This function takes an existing string and returns a new 
string, replacing all the lowercase letters with uppercase 
(capital) letters. 

This is the new string, all in capitals.The string fun appears twice.

>>> "blue".upper()

'BLUE'

△ replace()
For this function, you need two parameters—the first is  
the part of a string you want to replace, and the second  
is what you want to replace it with. The function returns  
a new string with the replacement made.

>>> countdown = [1, 2, 3]

>>> countdown.reverse()

>>> print(countdown)

[3, 2, 1]

The reverse function  
is called on the list  
of numbers. The function has two parameters, 

which are separated by a comma.

>>> message = "Coding makes me happy"

>>> message.replace("happy", ":D") 

'Coding makes me :D'

>>> name = input("What is your name?")

What is your name?Ben

>>> print(name)

Ben

US_040-041_Functions_1.indd   41 22/02/18   12:24 pm



41F U N C T I O N S

▷ input() 
This function lets the player enter information for the 
game to use, rather than the coder putting it in the 
original code. For example, imagine you’re creating  
a game and you want to create a variable to store  
the player’s name, but you don’t know what they’re 
called. You can use input() to make the game ask the 
player what their name is. Their answer becomes a 
return value, which the function will then assign to 
the name variable.

You can type your 
own name in here.

input() has assigned the 
answer to the name variable.

input() asks the 
user what their 
name is. 

This is a variable 
that will later store 
the player’s name.

Another way to call functions
Some types of data, such as integers and strings, have their 
own built-in functions that are used to manipulate or 
change that data. These are known as “member” functions 
and can be called by placing a dot immediately after the 
data, followed by the name of the function and a pair of 
parentheses. Try these out in the shell window. 

△ count()
This function is used with strings. It is called on one 
string, with another string as a parameter of the 
function count(). The return value tells you how many 
times the second string appears in the first string.

△ reverse()
You can also call a member function on a variable.  
In this example, the function reverse() is used  
to reverse the order of the list of numbers stored  
in the variable countdown.

>>> "functions are fun".count("fun")

2

A list of numbers is 
assigned to a variable.

Members only

△ upper()
This function takes an existing string and returns a new 
string, replacing all the lowercase letters with uppercase 
(capital) letters. 

This is the new string, all in capitals.The string fun appears twice.

>>> "blue".upper()

'BLUE'

△ replace()
For this function, you need two parameters—the first is  
the part of a string you want to replace, and the second  
is what you want to replace it with. The function returns  
a new string with the replacement made.

>>> countdown = [1, 2, 3]

>>> countdown.reverse()

>>> print(countdown)

[3, 2, 1]

The reverse function  
is called on the list  
of numbers. The function has two parameters, 

which are separated by a comma.

>>> message = "Coding makes me happy"

>>> message.replace("happy", ":D") 

'Coding makes me :D'

>>> name = input("What is your name?")

What is your name?Ben

>>> print(name)

Ben

US_040-041_Functions_1.indd   41 22/02/18   12:24 pm



L E A R N I N G  T H E  B A S I C S42

Making your own functions
There isn’t a built-in function for everything, 
so you need to know how to write, or “define,” 
your own. A function should have one clear 
purpose and a name that describes what it 
does. Follow these steps to create a function 
that calculates a player’s score.

E X P E R T  T I P S

Naming your functions
It’s important to give your functions 
accurate names that explain what they do. 
This will help you understand the code. 
Names can contain letters, numbers, and 
underscores, but they should always begin 
with a letter. You can’t use spaces, so if 
there are multiple words in the name  
of your function, separate them by using 
underscores instead. For example, if you 
were creating a function to end the game, 
you could name it game_over(). 

Use the def keyword  
to define a function.

This function doesn’t 
take a parameter.

The score is displayed 
in the shell.

def fruit_score():

    print(10)

    

fruit_score()

10

1 Define the functionLet’s create a function to keep score in a game. 
Open an editor window in IDLE and save it as 
functions.py. Then type in the code below, 
making sure you get all the indents right.  
After each step, save the file, go to the  
Run menu, and click Run Module.

2 Add some parametersThe function works well so far, but what  
if you want to have different scores for 
different fruits you collect? For the 
function to know which score to print,  
it needs to know which fruit you have 
collected. Imagine you get ten points  
for an apple, but five points for an orange. 
You can do this by adding a parameter  
to the function.

def fruit_score(fruit):

    if fruit == "apple":

        print(10)

    elif fruit == "orange":

        print(5)

fruit_score("apple")

fruit_score("orange")

The function now 
takes a parameter.

These lines give  
a value to the 
parameter.

The function is called 
twice—once with 
each parameter.

10

5

The score that gets printed 
depends on whether the 
parameter is apple or orange.

This calls the function, 
running the code 

you’ve stored in it.

This is the code 
you’re storing in 
the function.

US_042-043_Functions_2.indd   42 14/03/18   12:18 PM

43F U N C T I O N S

3 Return a valueRather than printing out the score, you might  
want to use it elsewhere in your code. You can ask 
to get a value out of a function to be used later. 
This is called “returning” a value. Type in the 
keyword return before the value you want it to 
return in each case. Try switching your print 
statements to return statements.

4 Using the return valueYou can use the return value of a function 
elsewhere in your code. In this case, we make 
two calls to the function—one for each fruit. We 
then add these results together to get a total 
score. Add this code underneath what you wrote 
in Step 3 and then go to the Run menu and click 
Run Module.

def fruit_score(fruit):

    if fruit == "apple":

        return 10

    elif fruit == "orange":

        return 5

15

I would like to return  
these oranges and buy  
some apples instead.

E X P E R T  T I P S

Indentation Errors
Python uses indentation to understand 
where a block of code starts and stops.  
An “IndentationError” appears when 
something is wrong with the way you’ve 
structured the code. Remember that if  
a line of code ends with a colon ( : ), the  
next line needs to be indented. If Python 
does not add them automatically, use the 
Space bar to manually insert four spaces.

Error... error!
The values are returned for 
use later in the code. They 
will not appear in the shell.

The two return values 
are added together.

return 5

apple_score = fruit_score("apple")

 orange_score = fruit_score("orange")

total = fruit_score("apple") + fruit_score("orange")

 print(total)

Don’t use 
parentheses with the 
return statements. 

US_042-043_Functions_2.indd   43 14/03/18   12:18 PM



43F U N C T I O N S

3 Return a valueRather than printing out the score, you might  
want to use it elsewhere in your code. You can ask 
to get a value out of a function to be used later. 
This is called “returning” a value. Type in the 
keyword return before the value you want it to 
return in each case. Try switching your print 
statements to return statements.

4 Using the return valueYou can use the return value of a function 
elsewhere in your code. In this case, we make 
two calls to the function—one for each fruit. We 
then add these results together to get a total 
score. Add this code underneath what you wrote 
in Step 3 and then go to the Run menu and click 
Run Module.

def fruit_score(fruit):

    if fruit == "apple":

        return 10

    elif fruit == "orange":

        return 5

15

I would like to return  
these oranges and buy  
some apples instead.

E X P E R T  T I P S

Indentation Errors
Python uses indentation to understand 
where a block of code starts and stops.  
An “IndentationError” appears when 
something is wrong with the way you’ve 
structured the code. Remember that if  
a line of code ends with a colon ( : ), the  
next line needs to be indented. If Python 
does not add them automatically, use the 
Space bar to manually insert four spaces.

Error... error!
The values are returned for 
use later in the code. They 
will not appear in the shell.

The two return values 
are added together.

return 5

apple_score = fruit_score("apple")

 orange_score = fruit_score("orange")

total = fruit_score("apple") + fruit_score("orange")

 print(total)

Don’t use 
parentheses with the 
return statements. 

US_042-043_Functions_2.indd   43 14/03/18   12:18 PM



L E A R N I N G  T H E  B A S I C S44

Fixing bugs
If there’s an error, or a “bug,” in your code, 
Python will show an error message. These 
messages can be a bit confusing sometimes, 
but they tell you what is wrong with your 
code and how to fix it. 

Error alert
In IDLE, both the editor and shell windows  
can display an error message when something 
unexpected happens. This message highlights 
the error and shows you which line of code  
to find it in.

▽ Messages in Command Prompt/Terminal
Error messages in Pygame Zero are shown in 
the Command Prompt or Terminal window. 
When an error is discovered, the program will 
stop running and will tell you what the error is 
and where to look for it in the code.

E X P E R T  T I P S

Catching bugs
When you see an error in the Command 
Prompt (Windows) or Terminal (Mac), look at 
the line number. Go back to your code in 
IDLE and click anywhere in the file. The line 
number will be displayed at the bottom-
right corner of the screen—for example,  
Ln: 12. Then use the Up or Down arrow  
to find the line with the error in it.

Help me find  
those delicious bugs!

  File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pgzrun", line 11, in <module>

    load_entry_point('pgzero==1.1', 'console_scripts', 'pgzrun')()

  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/

pgzero/runner.py", line 88, in main

    exec(code, mod.__dict__)

  File "score.py", line 2, in <module>

    print("Game Over: Score " + score)

TypeError: must be str, not int
This is a type error.

The error is on line 2.

Rabiahma – bash – 80x24

US_044-045_Fixing_bugs.indd   44 22/02/18   12:24 pm

F I X I N G  B U G S 45

Syntax errors
The structure of statements used in a coding 
language is known as syntax. A syntax error means 
that you’ve typed something wrong. You could have 
missed a part of a statement or misspelled a word. 
Syntax errors are the easiest mistakes to fix. Go to the 
line with the error and change what you’ve mistyped. 

Indentation errors
Python uses indentation to show where 
blocks of code begin and end. Indentation 
errors are displayed if you make a mistake 
with the structure of the code. If a line of 
code ends with a colon, you must indent 
the next line. Python automatically 
indents after colons, but you can also  
do it manually by adding four spaces.

The different indents tell 
Python which block each 
line of code belongs to.

Each indent is 
four spaces.

The closing 
parenthesis is missing.

The closing quotation 
mark is missing.

This is a spelling mistake. It’s supposed  
to be referencing the variable named 
“horse,” so it should be horse.draw().

Block 1

Block 2

Block 3

Block 2, continuation

▷ Mistakes to  
watch out for
Do your opening and 
closing parentheses match?  
Are you missing a quotation 
mark? Have you spelled 
everything correctly? These 
are the main causes of 
syntax errors.

◁ Indent each new block
Python programs usually have blocks of code  
within other blocks, such as an if statement inside  
a loop. Every line in a block must be indented by the 
same amount. This can be done for each indent by 
pressing the Space bar four times. Even though 
Python automatically indents after colons, you should 
get used to checking if the indentation is correct.

Block 1, continuation

H

e

l l o !
 print(score

 horse = Actor("horse)

 hrse.draw()

Indenting the code by adding 
four spaces will fix this error.

Not leaving any spaces here 
will cause an indentation error.

if play: 

 horse.draw()

if play: 

    horse.draw()

US_044-045_Fixing_bugs.indd   45 22/02/18   12:24 pm



F I X I N G  B U G S 45

Syntax errors
The structure of statements used in a coding 
language is known as s