Python Projects
Python Projects
ProJecTs
PYTHON
®
R
IN
DK UK
Senior editors Ben Morgan, Steve Setford
Senior art editor Peter Radcliffe
US editors Jill Hamilton, Margaret Parrish
Consultant editor Craig Steele
Jacket design development manager Sophia MTT
Jacket editor Claire Gell
Producer, pre-production Robert Dunn, Nadine King
Producer Anna Vallarino
Managing editor Lisa Gillespie
Managing art editor Owen Peyton Jones
Publisher Andrew Macintyre
Associate publishing director Liz Wheeler
Art director Karen Self
Design director Phil Ormerod
Publishing director Jonathan Metcalf
DK INDIA
Project editor Suefa Lee
Art editor Sanjay Chauhan
Assistant editor Isha Sharma
Assistant art editors Yashashvi Choudhary,
Simar Dhamija, Sonakshi Singh
Jacket designer Juhi Sheth
Jackets editorial coordinator Priyanka Sharma
Managing jackets editor Sreshtha Bhattacharya
DTP designer Sachin Gupta
Senior DTP designer Harish Aggarwal
Senior managing editor Rohan Sinha
Deputy managing art editor Anjana Nair
Pre-production manager Balwant Singh
12 What is coding?
14 Meet Python
16 Installing Python
18 Using IDLE TURTLE GRAPHICS
72 Robot Builder
FIRST STEPS 82 Kaleido-spiral
90 Starry Night
98 Mutant Rainbow
22 Your first program
24 Variables
28 Making decisions
32 Loopy loops PLAYFUL APPS
36 Animal Quiz
44 Functions
48 Fixing bugs 110 Countdown Calendar
52 Password Picker 120 Ask the Expert
58 Modules 130 Secret Messages
60 Nine Lives 142 Screen Pet
Let’sssss get
sssstarted!
GAMES IN PYTHON
158 Caterpillar
168 Snap
180 Matchmaker
190 Egg Catcher
REFERENCE
We live in a digital world, and computers are part of almost everything we do. Not so
long ago, computers were bulky, noisy machines that lived mainly on desks, but now
they are tiny, silent devices hidden inside our phones, cars, TVs, and even watches.
We use them to work, play games, watch movies, go shopping, and keep in touch with
our friends and family.
Today’s computers are so simple to use that anyone can operate them. But not as
many people know how to write the code that makes them work. Becoming a coder
allows you to look under the hood and see how a computer really works. With a bit
of practice, you can build your own apps, write your own games, or just tinker with
other people’s programs and customize your own ingenious creations.
As well as being an addictive hobby, coding is a skill that’s in huge demand all over
the world. Learn how to code and it will set you in good stead wherever your life
leads, whether you’re interested in science, art, music, sport, or business.
Today, there are hundreds of coding languages you can learn, from simple, drag-and-
drop languages like ScratchTM to web-programming languages like JavaScript®. This
book is based on Python®, one of the world’s most widely used coding languages.
Equally popular with students and professionals, Python is easy to pick up yet powerful
and versatile. It’s a great language to learn whether you’re a beginner or moving up
from a simple language like Scratch.
The best way to learn to code is to get immersed, and that’s how this book is designed
to work. Just follow the numbered steps and you’ll be building apps, games, graphics,
and puzzles in no time. Learning to code is easier if you’re having fun, so we’ve tried
to make the projects as much fun as possible.
If you’re new to programming, start at the beginning and work your way through.
Don’t worry if you don’t understand every detail—it doesn’t matter. The more projects
you build, the better you’ll get. And don’t worry if your programs don’t work the first
time you run them. Even the pros have to debug their work.
Once you’ve finished building each project, there are tips on how to tweak and adapt
it. Feel free to try your own hacks. With a little bit of imagination and skill, there’s
no limit to what a coder can achieve.
What is coding?
Computer programmers, or “coders,” are people
who write step-by-step instructions that can
make a computer perform a task. Coders can get
computers to do addition, make music, move a
robot across a room, or fly a rocket to Mars.
Programming languages
In order to tell a computer what to do, you need
to learn a programming language. Visual languages
are easy for beginners to learn, while professional
coders use text-based languages. This book is based Why don’t you say
on the popular text-based language Python. something?
▽ Scratch ▽ Python
Scratch is a visual programming language. Python is a text-based programming
It’s great for creating games, animations, and language. In Python, programmers write
interactive stories. You write code in Scratch code using words, abbreviations, numbers,
by snapping together blocks of instructions. and symbols. Instructions are typed in using
the computer’s keyboard.
6
W H AT I S C O D I N G ? 13
Anyone can code
To be a coder you just need to learn a few basic rules and
commands, and then you can start writing programs to
suit your skills and interests. If you’re into science, for
example, you could make an app that draws graphs from
the results of your experiments. Or you could use your art
skills to design an alien world for your own video game.
LINGO
Bugs
Get coding
Bugs are errors in code that make Coding may sound daunting, but learning how
programs behave in unexpected ways.
to do it is easy. The secret is to just jump in. This
They are so-called because early
computers sometimes went wrong when book is designed to teach you how to code by
insects got stuck in their circuits! guiding you through simple projects. Just follow
the numbered steps and you’ll be creating
games, apps, and digital art in no time.
I’m on a
bug hunt!
14 S TA R T I N G W I T H PY T H O N
▷ Great support
△ Works everywhere Python has well-written
Python is portable. This means you can write and documentation. It has a
run Python code on lots of different computers. guide to getting started, a
The same Python code will work on PCs, Macs, reference section for looking
Linux machines, and Raspberry Pi computers. The up what things mean, and
programs behave the same way on each machine. a bunch of example code.
MEET PYTHON 15
Python in action EXPERT TIPS
Python isn’t just an educational tool. The interpreter
It’s such a powerful program it’s used
for many interesting and exciting tasks Some programming languages use an interpreter.
The interpreter is a program that can translate from
in business, medicine, science, and the
one programming language into another. Every time
media. It can even be used to control you run a Python program, the interpreter translates
the lights and heating in your home. each line of Python code into a special code that the
computer can understand, known as machine code.
Action!
We’ve been
expecting you!
△ In the movies
Disney uses Python to automate repetitive parts of
△ Out of this world the animation process. Rather than animators carrying
Software engineers used Python to create tools for out the same steps over and over, they use a Python
NASA’s Mission Control Center. These tools help the crew program to repeat the steps automatically. This saves
prepare for and monitor the progress of each mission. work, shortening the time it takes to make a film.
16 S TA R T I N G W I T H PY T H O N
All the projects in this book use Python 3, so IDLE (short for Integrated
make sure you download the correct version Development Environment) is
from the website. Follow the instructions a free app that you get when
you install Python. Designed for
that match your computer. beginners, IDLE includes a basic
text editor that allows you to write
and edit Python code.
Python on Windows
Before you install Python 3 on a Windows PC, find out
if it uses the 32-bit or 64-bit version of windows. Click
“Start”, right-click “Computer”, and left-click “Properties”.
Then choose “System” if the option appears.
Click the
installer.
4 Open IDLE
When the installation is finished, check that it was
successful by opening the IDLE program. Go to the
“Start” menu, choose “All Apps”, then select “IDLE”.
A window like the one below should open up.
3 Install Python
You’ll find the .pkg file in the “Downloads” folder. Its
The version number might not be
icon looks like an opened parcel. Double-click it to exactly the same as this one—just
start the installation. At the prompts, click “Continue” make sure you download the one
and then “Install” to accept the default settings. that has a 3 at the beginning.
EXPERT TIPS
Colors in the code
IDLE automatically colors ◁ Symbols and names ◁ Keywords
the text to highlight Most code text is colored Certain words, such as
different parts of the code. black. “if” and “else”, are special
The colors make it easier to words that Python uses.
understand the code, and They are called keywords
they’re useful when you’re ◁ Output and are shown in orange.
trying to spot mistakes. Any text produced when
a program runs is blue.
◁ Text in quotes
◁ Built-in commands ◁ Errors Text in quote marks is
Python commands, Python uses red to green. A green bracket
such as “print”, are alert you to any errors around text shows you’re
shown in purple. in your code. missing a quote mark.
First
steps
22 FIRST STEPS
Recent Files
▷ Hello World flowchart
Programmers use diagrams Start Class Browser
called flowcharts to plan their
Path Browser
programs and to show how they
work. Each step is shown in a
box, with an arrow leading to
the next step. Sometimes the Say hello
steps are questions and have 2 Type the first line
In the editor window, type this line of text.
more than one arrow leading The word “print” is a Python instruction that
onward, depending on the tells the computer to display something on
answer to the question. Ask user to type the screen, such as the words “Hello, World!”
their name
print('Hello, World!')
End Close
Save
Save As...
YO U R F I R S T P RO G R A M 23
5 Check it works
Now run the first line of the program
Python Shell >>>
to see if it works. Open the Run menu Check Module Hello, World!
and choose Run Module. You should
>>>
see the message “Hello, World!” in the Run Module
shell window.
The message will
appear in the shell.
6 Fix mistakes
If the code isn’t working, stay calm!
EXPERT TIPS
Every programmer makes mistakes, Keyboard shortcut
and finding these “bugs” is vital if you
want to become an expert at coding. A handy shortcut to run a program from
Go back and check your code for the editor window is simply to press F5 on
typing errors. Did you include the your keyboard. This is a lot quicker than
brackets? Did you spell the word selecting “Run” and then “Run Module”.
“print” correctly? Fix any mistakes,
then try running the code again.
8 Final task
Run the code again to check it. When you type in your Hello, World!
User’s
name and hit the enter/return key, the shell should show What's your name?Josh name
a personalized message. Congratulations on completing
Hello, Josh
your first Python program! You’ve taken your first steps
towards becoming a powerful programmer.
24 FIRST STEPS
Variables
If you want to write useful code, you’ll need to be able
to store and label pieces of information. That’s what
variables do. Variables are great for all sorts of things—
from tracking your score in a game to performing
calculations and holding lists of items.
1 Assign a value
In the shell window, type this line of code to
>>> age = 12
EXPERT TIPS
Naming variables
Choosing good names for your variables Dos and don’ts
will make your program easier to • Start the variable’s name with a letter.
understand. For example, a variable • Any letter or number can be used in the name.
tracking a player’s lives in a game could • Symbols such as -, /, #, or @ aren’t allowed.
be called lives_remaining, rather
• Spaces can’t be used.
than just lives or lr. Variable names
can contain letters, numbers, and • An underscore ( _ ) can be used instead of a space.
underscores, but they should begin • Uppercase (capitals) and lowercase letters are different.
with a letter. Follow the rules shown Python will treat “Score” and “score” as two different variables.
here and you won’t go wrong. • Avoid words Python uses as commands, such as “print”.
VA R I A B L E S 25
LINGO
Integers and floats
In coding, whole numbers are called “integers”,
while numbers with a decimal point in them
are known as “floats”. Programs usually count
things using integers. Floats are more often
used for measurements. 0.5 sheep
1 sheep (an integer) (a float)
1 A simple calculation
Type this code in a shell window. It uses >>> x = 6
numbers stored in two variables, named x >>> y = x * 7
and y, to carry out a simple multiplication.
>>> print(y)
Hit the enter/return key to get the answer.
42
2 Change a value
To change the value of a variable, you just >>> x = 10
assign a new value to it. In your code, change >>> print(y)
the value of x to 10 and run the calculation
42
again. What do you expect the result to be?
1 Strings in variables
Strings can be put into variables. Type this
>>> name = 'Ally Alien'
2 Combining strings
Variables become really useful when you
>>> name = 'Ally Alien'
combine them to make new variables. If you >>> greeting = 'Welcome to Earth, '
add two strings together, you can store the >>> message = greeting + name
combination in a new variable. Try this out.
>>> print(message)
Welcome to Earth, Ally Alien
EXPERT TIPS
Length of a string The + symbol
joins one string
The quote marks to another.
You can use a handy trick, len(), to aren’t shown when
count the number of characters in a string you print a string.
(including the spaces). The command
len() is an example of what coders call a
function. (You’ll use lots of functions in this
book.) To find out how many characters He doesn’t have
there are in 'Welcome to Earth, Ally a clue!
Alien', type the line below into the Take me to your
leader...
shell once you’ve created the string, then
hit enter/return.
>>> len(message)
28
The number of
characters counted
VA R I A B L E S 27
Lists
When you want to store a lot of data, or
perhaps the order of the data is important,
you may need to use a list. A list can hold
many items together and keep them in order.
Python gives each item a number that shows
its position in the list. You can change the
items in the list at any time.
1 Multiple variables
Imagine you’re writing a multiplayer game
>>> rockets_player_1 = 'Rory'
>>> rockets_player_2 = 'Rav'
and want to store the names of the players
in each team. You could create a variable for >>> rockets_player_3 = 'Rachel'
each player, which might look like this...
>>> planets_player_1 = 'Peter'
>>> planets_player_2 = 'Pablo'
With three players per team, >>> planets_player_3 = 'Polly'
you’d need six variables.
Hit enter/return to
retrieve the item.
28 FIRST STEPS
▽ ▷ Make comparisons
>>> zebras < pineapples
Now try typing the following lines of code to compare
the values of the two variables. After you’ve typed each True
line, press the return key and Python will tell you if the
statements are True or False. The number of zebras is less
than the number of pineapples.
This is a Boolean
>>> age = 10 expression meaning
These two lines >>> height = 1.5 “older than 8 and more
assign values to than 4 ft 7 in tall”.
the variables. >>> (age > 8) and (height > 53 inches)
True
Mia can go on the
rollercoaster!
Branching
Computers often need to make decisions about
which parts of a program to run. This is because
most programs are designed to do different
things in different situations. The route through
the program splits like a path branching off into
side paths, each leading to a different place.
▷ Two branches This line asks for input from the user. Condition
Do you want a program to do one thing if
a condition’s True and another thing if it’s tentacles = input('Do you have tentacles? (n/y)')
False? If so, you need a command with two if tentacles == 'y':
branches, called an if-else statement.
This program asks if the user has tentacles. print('I never knew octopuses could type!')
If they answer “Yes”, it decides they must else:
be an octopus! If they answer “No”, it
print('Greetings, human!')
decides they’re human. Each decision
prints a different message.
This block runs if the This block runs if the
condition is True. condition is False.
▷ Multiple branches
weather = input ('What is the forecast for today? (rain/snow/sun)')
When there are more than
two possible paths, the First condition This block runs if the
statement elif (short for if weather == 'rain': first condition is True.
“else-if”) comes in handy. This
program asks the user to type print('Remember your umbrella!')
in the weather forecast: either elif weather == 'snow':
“rain”, “snow”, or “sun”. It then Second
print('Remember your wooly gloves!')
chooses one of three branches condition
and weather conditions. else:
print('Remember your sunglasses!')
△ How it works
An elif statement must always come after if and
before else. In this code, elif checks for snow only
when the condition set by the if statement is False.
You could insert additional elif statements to check
for more types of weather.