Coding Projects in Python
Coding Projects in Python
P roJecTs
IN PYTHON
®
R
!
H e l l o W, o r l d
G
P roJecTs
IN PYTHON ®R
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
STARTING WITH
PYTHON
12 What is coding?
14 Meet Python
16 Installing Python
18 Using IDLE
TURTLE GRAPHICS
FIRST STEPS
72 Robot Builder
82 Kaleido-spiral
22 Your first program 90 Starry Night
24 Variables 98 Mutant Rainbow
28 Making decisions
32 Loopy loops
36 Animal Quiz
44 Functions PLAYFUL APPS
48 Fixing bugs
52 Password Picker
58 Modules 110 Countdown Calendar 120 Ask the
GAMES IN PYTHON
158 Caterpillar
168 Snap
180 Matchmaker
190 Egg Catcher
REFERENCE
6 >>> 3 + 3
6
Both these bits of code
do the same thing. You hit the enter/return key
to see the result.
WHAT IS CODING? 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.
▽ Think logically
Coders need to think logically and carefully to write
good code. If the instructions aren’t quite right or the
steps are in the wrong order, a program won’t work
properly. Think through each step and make sure
things happen in a logical order—after all, you
wouldn’t put your coat on before your sweater, would
you!
LINGO
Bugs
Bugs are errors in code that make
programs behave in unexpected
ways. They are so-called because
early
computers sometimes went wrong
when insects got stuck in their circuits!
I’m on a
bug hunt!
▽ Pay attention to
detail
If you’re good at spot-the-difference puzzles, you’ll
probably be a great coder. An important skill in
coding is spotting mistakes in your code. These
mistakes are called bugs, and even tiny bugs can
cause big problems. Eagle-eyed coders can pick
out spelling mistakes and faults with the logic or
order of the instructions. Debugging a program
can be tricky, but learning from your mistakes is a
great way to improve your coding powers.
Get coding
Coding may sound daunting, but learning
how to do it is easy. The secret is to just
jump in. This book is designed to teach you
how to code by guiding you through simple
projects. Just follow the numbered steps and
you’ll be creating games, apps, and digital
art in no time.
Python
▽ Batteries included
Python is one of the most popular Programmers say Python has “batteries included.” This
is because it comes with everything you need to start
computer programming languages coding right away.
in the world. It was first released in
the 1990s and is now used to build
millions of apps, games, and
websites.
Why Python?
Python is a great language for getting started
with computer programming. Many schools simple to read, write, and understand.
and universities use it to teach coding. Here
are some of the reasons that Python’s so
useful.
MEET PYTHON 15
Python is widely used on the Internet. Parts of Google’s
search engine are
Python in action
The interpreter
Some programming languages use an interpreter.
The interpreter is a program that can translate from
EXPERT TIPS one programming language into another. Every time
Python isn’t just an educational tool. It’s suchyou run a Python program, the interpreter translates
a powerful program it’s used for many each line of Python code into a special code that
the computer can understand, known as machine
interesting and exciting tasks in business,
code.
medicine, science, and the media. It can
even be used to control the lights and
heating in your home.
I’m a mighty
We’ve been
expecting you!
powerful program!
Action!
Installing
Python
All the projects in this book use
1
Python 3, so make sure you 2
download the correct version from Go to the Python website
Type the address below into your web
the website. Follow the instructions browser to go to the Python website.
that match your computer. Then click on “Downloads” to open the
download page.
Python on a Mac
Before you install Python 3 on a Mac, check
which operating system the computer uses.
Click the Apple icon in the top left of the
screen and choose “About this Mac” from
the drop-down menu.
12
Go to the Python website
Type the address below into your web browser
to go to the Python website. Then click on
“Downloads” to open the download page.
https://www.python.org/
INSTALLING PYTHON 17
3
Install Python
Download Python You’ll find the .pkg file in the “Downloads” folder. Its
From the downloads options, click on the latest version icon looks like an opened parcel. Double-click it to
of Python 3 that matches your operating system. The start the installation. At the prompts, click “Continue”
Python.pkg file will download to your Mac automatically. and then “Install” to accept the default settings.
4
Open IDLE
When the intallation is finished, check that it was that has a 3 at the beginning.
successful by opening the IDLE program. Open the
“Applications” folder, and then the “Python” folder.
Double-click “IDLE” and a window like this should IMPORTANT!
appear.
Ask permission
Python 3.6.0a4 Shell
• Python 3.6.0a4 - 2016-08-15 Never install Python or any other
• Download macOS X 64-bit/32-bit installer program unless you have permission
to do so from the computer’s owner.
You may also need to ask the owner
The version number might not be to provide an administration password
exactly the same as this one—just during installation.
make sure you download the one
USING IDLE 19
EXPERT TIPS
◁ Built-in commands
◁ Keywords
Python commands,
Certain words, such as “if”
such as “print”, are and “else”, are special
shown in purple. words that Python uses.
They are called keywords
and are shown in orange.
◁ Symbols and names
Most code text is colored
black. ◁ Text in quotes
Text in quote marks is
◁ Output green. A green bracket
Colors in the code Any text produced when
around text shows you’re
missing a quote mark.
a program runs is blue.
IDLE automatically colors
the text to highlight
Firs
t
step
s
22 FIRST STEPS program in Python.
Follow these steps to
create a simple program
Your first that greets the user with a
cheery message.
program
Now that you’ve installed
Hello Cedric!
Python and IDLE, it’s
time to write your first
1 Launch IDLE
End
Path
Browser
Save your file
Before you can run the
Type the code, you must save it. Go
first line to the File menu and
In the choose Save.
editor
3 window,
type this
Close
line of text. Save
The word
“print” is a Save As...
Python
instruction
that tells
the
computer
to display
something
on the
screen,
such as
the words
“Hello,
World!”
Fix mistakes
If the code isn’t working,
stay calm! Every
programmer makes print('Hello,
World!')
Go back to the editor window and add two more lines person = input('What’s your name?')
to your script. Now the middle line asks for your print('Hello,', person)
name and then stores it in a variable. The last line
uses your name to print a new greeting. You can
change it to a different greeting if you prefer—as This line asks for the user’s name and
stores it in a variable called “person”.
polite or as rude as you like!
Hello, World!
User’s
8
Final task
Run the code again to check it. When you type in
your
name and hit the enter/return key, taken your first steps towards Hello, Josh
the shell should show a becoming a powerful
personalized message. programmer. name
Congratulations on completing What's your name?Josh
your first Python program! You’ve
create the variable age and assign a value
EXPERT TIPS
How to create a variable This is the variable’s name.
Naming variables
Choosing good names for your variables will make
your program easier to understand. For example, a
variable tracking a player’s lives in a game could
be called lives_remaining, rather than just
lives or lr. Variable names can contain letters,
numbers, and underscores, but they should begin
with a letter. Follow the rules shown here and you
won’t go wrong.
0.5 sheep
(a float)
1 sheep (an integer)
Using numbers *
Symbol Meaning be
familiar, but watch out for the
Variables can be used to store numbers symbols meaning
and do sums.
+
You can use them with symbols to do
/
calculations,
“multiply” and “divide”—they’re slightly
–
different
just like you do in maths. Some of these add
from the ones you use in class. Some of the Python math symbols Create a new variable, x, and give it the
value 6.
2 Change a value
>>> x = 10
To change the value of a variable, you just >>> print(y)
assign a new value to it. In your code, change
the value of x to 10 and run the calculation 42
Coders use the word “string” for any
data made up of a sequence of letters
or other characters. Words and
sentences are stored as strings.
3 Almost all programs use strings at
Update the value some point. Every character that you
The value of y needs to be updated to get can type on your keyboard, and even
the correct result. Type these lines. Now those you can’t, can be stored in a
the code assigns the new value to y after x
has been changed. If you update the value string.
of one variable in your own programs,
always check to see if you need to update
any others.
The result hasn’t changed;
next we’ll find out why.
Update the value of y.
Y 0
>>> x = 10 P T H N
>>> y = x * 7
>>> print(y) A string is simply a
sequence of characters.
70
The number of
characters counted He doesn’t have
The + a clue!
symbol Take me to your
joins one string leader...
VARIABLES 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 3
Getting items from a list
Multiple variables
Once your data is in a list, it’s easy to work
Imagine you’re writing a multiplayer game
with. To get an item out of a list, first type the
and want to store the names of the
name of the list. Then add the item’s position
players in each team. You could create a
in the list, putting it inside square brackets.
variable for each player, which might look
Be careful: Python starts counting list items
like this...
from 0 rather than 1. Now try getting different
players’ names out of your team lists. The
first player is at position 0, while the last
With three players per team,
player is at position 5.
you’d need six variables.
2
Put a list in a variable
...but what if there were six players per
team? Managing and updating so many
variables would be difficult. It would be
better to use a list. To create a list, you
surround the items you want to store with
square brackets. Try out these lists in the
shell.
>>> rockets_players[0]
'Rory'
>>> planets_players[5]
'Patrick'
Hit enter/return to
retrieve the item.
>>> rockets_player_1 =
'Rory'
>>> rockets_player_2 = 'Rav'
>>> rockets_player_3 = 'Rachel'
>>> planets_player_1 = 'Peter'
>>> planets_player_2 = 'Pablo'
>>> planets_player_3 = 'Polly'
MAKING DECISIONS 29
Pineapples and zebras
Let’s try an example using the shell. We can
represent having five pineapples and two
zebras by using the variables pineapples
and zebras. Type these lines into the shell.
2
This variable stores
>>> pineapples the number of
pineapples.
= 5 >>> zebras =
LINGO
Boolean expressions
Statements about variables and values that
use the logical operators always give us a
Boolean value, such as True or False.
Because of this, these statements are called
Boolean expressions. All of our statements
about pineapples and zebras are Boolean
expressions.
zebras
False
▽ Multiple comparisons
You can use and a nd or t o combine more than
one comparison. If you use and, both parts of
the comparison must be correct for the
statement to be True. If you use or, only one
part needs to be correct.
Branching
These two lines >>> age = 10
△ How it works
Second
condition
For loops
When you know how many times you want to run a
block of code, you can use a for loop. In this
example, Emma has written a program to make a
sign for her
door. It prints “Emma’s Room—Keep then hit enter/return again.)
Out!!!” ten times. Try out her code for Emma’s Room—Keep Out!!! Emma’s Room—Keep Out!!!
Emma’s Room—Keep Out!!! Emma’s Room—Keep Out!!!
yourself in the shell. (After typing the Emma’s Room—Keep Out!!! Emma’s Room—Keep Out!!!
code and hitting enter/return, press
backspace to remove the indent and
This is the loop variable. Emma’s Room—Keep Out!!! Emma’s Room—Keep Out!!!
The loop runs 10 times. Emma’s Room—Keep Out!!! Emma’s Room—Keep Out!!!
>>> for counter in range(1, 11):
print('Emma\'s Room - Keep Out!!!') ▽ Loop variable
Emma’s Room—Keep Out!!! The line that gets repeated
is called the loop body.
EXPERT TIPS
Indent the commands in
the body 4 spaces.
The loop variable keeps track of how many times we’ve gone around the loop so far. The first
time round it’s equal to the first number in the list specified by range(1, 11). The second time
around it’s equal to the second number in the list, and so on. When we’ve used all the numbers
in the list, we stop looping.
First loop Second loop Third loop Loop variable = 1 Loop variable = 2 Loop variable = 3
Range
In Python code, the word “range” followed by two numbers within brackets stands for
“all the numbers from the first number to one less than the second number”. So
range(1, 4) means the numbers 1, 2, and 3—but not 4. In Emma’s “Keep Out”
program, range(1, 11) is the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
What happens if you don’t know how many
times
you want to repeat the code? Do you need a
EXPERT TIPS crystal ball or some other way of seeing into
Escape character (\) the
future? No, it’s okay! You can use a while
The backslash in Emma\'s Room tells Python loop.
to ignore the apostrophe so that it doesn’t treat it
as the quotation mark that closes the whole
string. A backslash used like this is called an ▷ Loop condition
escape character. It tells Python not to count the I can see the future, and it’s completely loopy!
next character when working out if the line makes
sense or contains errors.
While loops
LOOPY LOOPS 33 I’m off!
A while loop doesn’t have a loop This variable stores the
variable that’s set to a range of number of hippos.
values. Instead it has a loop
condition. This is a Boolean
This variable stores
?!?
expression that can be either True
or False. It’s a bit like a bouncer
at a disco asking you if you’ve got
a ticket. If you have one (True),
head straight for the dance floor; if
you don’t (False), the bouncer
won’t let you in. In programming,
if the loop condition isn’t True, you
won’t get into the loop!
▽ Balancing act
In this example, Ahmed has
written a program to keep track of
how many of his troupe of
acrobatic hippopotamuses have Loop condition
balanced on top of each other to You can’t come in—
make a tower. Read through the your loop condition
code and see if you can figure out isn’t true!
how it works.
“Add another hippo?”
>>> hippos = 0
>>> answer = 'y'
Ahmed's reply becomes the
>>> while answer == 'y': new value of answer.
hippos = hippos + 1
▷ How it works
The loop condition in Ahmed’s
program is answer == 'y'.
This means that the user
wants to add a hippo. In the Hmm... maybe
body of the loop we add one to I’ll add just one
the number of hippos more hippo?
balanced, then ask the user if
they want to add another. If
they answer by typing “y” (for
yes), the loop condition is True
so we go around the loop
again. If they answer “n” (no),
the loop condition is False and
the program leaves the loop.
There is no False option to escape
the loop.
Infinite loops
Sometimes you may >>> while True:
want a while loop to
If you don’t want an infinite loop, it’s important to
make sure that the body of a while loop does
program is running. This kind of loop is something that could make the loop condition
called an infinite loop. Lots of video-game False. But don’t worry—if you accidentally code
programs use an infinite loop known as a an infinite loop, you can escape from it by
main loop. pressing the C key while holding down the Ctrl
(control) key. You may have to press Ctrl-C
several times before you quit the loop.
EXPERT TIPS
Stopping the loop
program.
△ Into infinity
You make an infinite loop by setting the loop condition
to a constant value: True. Because this value never
changes, the loop will never exit. Try this while l oop
in the shell. It has no False option, so the loop will print
“This is an infinite loop!” nonstop until you quit the
print('How rude!') breaktriggers the break command.
The False condition ('y')
EXPERT TIPS
Indent the
body
The code in the body of a loop should be
SyntaxError
indented four spaces. If it isn’t, Python will show
an error message and the code won’t run. With
nested loops (one loop inside another), the body unexpected indent
of the inner loop must be indented an extra four
spaces. Python automatically indents new lines
in loops, but you should always check that each OK
line is indented by the correct number of spaces.
range(1, 3): print('Hip') hip_counter.
The body of the inner loop is indented
print('Hooray!')
another 4 spaces.
The body of
▷ One loop inside another In this
the outer
example, Emma has changed her loop is indented 4 spaces.
“Keep Out” program into a “Three
◁ How it works
Cheers” program that prints “Hip,
Hip, Hooray!” three times. Because she uses a nested loop to print it. Hip
each cheer includes the word “Hip”
twice,
hooray_counter = 1 hip_counter
= 1 Hip
What happens
The program asks the player some
questions about animals. They get three
chances to answer each question—you
don’t want to make the quiz too difficult!
Each correct answer will score one point.
At the end of the quiz, the program
reveals the player’s final score.
This is how the game looks—it all happens in the shell
window.
Python 3.5.2 Shell
giraffe Sorry, wrong answer. Try
again. elephant Sorry, wrong
answer. Try again. rhinoceros The
correct answer is blue whale
Type in your
answer here.
▽ Animal
Quiz
flowchart
The
program
keeps
checking
whether
there are
any
questions
left to ask
Animal Quiz, it doesn’t matter if
the player answers “bear”
or “Bear”—both will be
LINGO recognized as correct.
Ignore the case! Check answer
When comparing the player’s
guess to the
correct answer, it shouldn’t
matter if the player types
capital letters or lower-case
letters—all that matters is Is answer
that the words are the same. correct?
This isn’t true for all
programs. For example, if a Y
program that checks
passwords ignores case, the Add 1 to score
passwords might become
easier to guess, Y
and less secure. However, in
Are there more questions?
Display score End
N
Are there any
chances left?
N
that gives the player three attempts
38 FIRST STEPS to answer each question.
Putting it together
It’s now time to build your quiz! First
you’ll create the questions and the I hope I’m not
mechanism for checking the venomous—I’ve just bitten my tongue!
answers. Then you’ll add the code
and set its starting value keep track of the player’s
to 0. score.
score = 0 score = 0
1 3
Create a new file
Open IDLE. Under the Introduce the game
File menu, select New Next, create a message
File. Save the file as to introduce
“animal_quiz.py”. File
Save
This phrase will appear in
Save As the shell window.
2
Create the score
variable
Type in the code shown
here to create a variable
called score You’ll use this variable to
45
89
Add some more questions guess1 = input('Which bear Guess the Animal!
lives at the North Pole? ') Which bear lives at the North
check_guess(guess1, 'polar Pole? polar bear Correct
bear') answer
Correct answer
animal? ') check_guess(guess3, 'blue
whale')
It takes more than one question to make a quiz! Let me add
Add two more questions to the program, following some more.
the same steps as before. We’ll store the player’s
answers in the variables guess2 and guess3.
score = 0
First question
print('Guess the Animal!')
guess1 = input('Which bear lives at the
This tells the program
North Pole? ') check_guess(guess1, 'polar to check guess1.
bear')
40 FIRST STEPS
reveal the player’s score
in a message when the
10 quiz ends. Add it to the
bottom of the file, under
Display the score the last question.
The next line of code will
11 12
Ignore case
What happens if the player types
“Lion” instead of “lion”? Will they still
get a point? No, the code will tell
them it’s the wrong answer! To fix
this, you need to make your code
smarter. Python has a lower()
function, which
changes words into all lower-case
characters. In your code, replace
if guess == answer: with the
line shown on the right in bold.
Your score is 3 The case is ignored when deciding whether an answer is correct or not.
13
Give the player more chances
The player currently has only one chance
to get the answer right. You can make it
a bit easier for them by giving them three
chances to answer a question. Change the
check_guess() function to look like this.
def check_guess(guess, score = score + 1 player gets the answer correct—
answer): whichever comes first.
still_guessing = False
global score
else:
Make sure each line of
still_guessing = True
if attempt < 2: code has the correct indent.
attempt = 0 This variable will hold one of only
while still_guessing and two values: True or False.
The else variable asks the
attempt < 3: if guess.lower() == player to enter another answer
if they get it wrong.
answer.lower(): print('Correct
Don’t forget to save your work.
answer') A while loop runs the check
code three times or until the
guess = input('Sorry wrong answer. Try again. ')
attempt = attempt + 1 To know if the player has gotten the
right answer, you need to create a
Add 1 to the number of
if attempt == 3: guesses the player has had.
print('The correct answer is ' + answer)
score = 0
This code displays the correct answer after three
wrong guesses.
△ How it works
set the variable to True to
show that the right answer
hasn’t been found. It’s set to
False when the player gets the
right answer.
Largest animal?
variable called I don’t know.
still_guessing. You then Give me three guesses!
Hacks and tweaks
Mix up your quiz! Make it longer or harder, use
different types of questions, or even change the
subject of the
quiz. You can try any or all of these hacks and tweaks,
but remember to save each one as a separate Python
file so that you don’t mess up the original game.
◁ Make it longer
Add more questions to the quiz. Some
examples could be “Which animal has a long
trunk?” (elephant) or “What kind of mammal
can fly?” (bat). Or, a bit harder: “How many
hearts does an octopus have?” (three).
it would be...
if attempt == 3:
print('The correct answer is ' + answer)
Built-in functions
This shows the content of the
Python has a number of built-in variable greeting on the screen.
△ upper()
I just love
the shell!
Variables The
keyword def tells Python that
this block of code is a function. seconds = minutes * 60 86400
print(seconds)
The lines after the name must be
indented 4 spaces, to show Python
print_seconds_per_day()
that they are part of the function.
This line prints the value of the
variable seconds.
This command calls the function.
parameters
2 Add
If you want to give your function any values to work
with, you put them inside the brackets as parameters.
For example, to find out the total number of seconds in
a particular number of days, change your code to look
like this. The function now has the parameter days.
You can specify the number of days when you call the
function. Try it out yourself.
Top advice
It’s important to define your functions before
FUNCTIONS 47
3 Return a value def convert_days_to_seconds(days):
Finding bugs
This line tells you it’s a type error (see
page 50). Whenan error message
appears in the shell, right-click
it and choose “Go to file/line” line 21 Cut
I’ll find those on the drop-down menu. The
pesky bugs!
IDLE editor jumps straight to Copy
that line of code so you can Paste
EXPERT TIPS The error is on line 21.
Go to file/line
start debugging.
incorrectly. Perhaps your fingers
slipped and hit a wrong letter? Don’t
worry— these are the easiest errors to
Syntax errors fix. Check through your code carefully
When you get a syntax error message, and try to spot what went wrong.
it’s a hint that you’ve typed something
▷ Things to look out for
Are you missing a bracket or
quotation mark? Do your pairs of
brackets and
quotation marks match? Have you
FIXING BUGS 49
The closing bracket is missing—it
needs another curved bracket here.
if weekday == True:
print('Go to school')
if weekday == True:
In your Python programs, you’ll often have one
block of code within another block, such as a
loop that sits inside a function. Every line in a
particular block must be indented by the same
amount. Although Python helps by The indents tell Python which lines
automatically indenting after colons, you still of code belong to which block.
need to check that each block is indented
correctly.
Block 1 Four
spaces
Block 2
print('Go to school') Ow!
That must be what they call
Block 3 an
indentation error!
Block 2, continuation
You need to indent the code on the
second line like this to fix the error.
Block 1, continuation
50 FIRST STEPS
Type errors
A type error isn’t a typing error—it means
your code has mixed up one type of data
with another, such as confusing numbers
with strings. It’s like trying to bake a cake in
your refrigerator—it won’t work, because
the refrigerator isn’t meant for baking! If you
ask Python to do something impossible,
don’t be surprised if it won’t cooperate!
I thought they
were taking a long
time to cook!
REFRIGERATOR
give it a list of
numbers, but
you’ve
given it a list of
letters instead!
Name
errors
◁ Examples of
type errors
Type errors
occur when you
ask Python to
do something
that doesn’t
make sense to
it, such as
multiplying with
strings,
comparing two
completely
different types
of data, or
telling it to find
a number in a
list of letters.
You can’t do
multiplication
with strings!
list = ['a','b','c']
find_biggest_number(list)
lives = lives – 1
EXPERT TIPS
◁ Line by line
Logic errors can be tricky to find, but as you get more
experienced you’ll get good at tracking them down. Try
to identify logic errors by
checking your code slowly, line by line. Be
A good password is easy
Password
to remember but hard for
a person or a password
cracker to guess.
Picker
Passwords stop other people from
accessing our computers,
personal emails, and website login
details. In this project, you’ll build
a tool that makes secure,
memorable passwords to help
keep your private information safe.
This password looks complicated, but it could take a cracker
less than 2 seconds to guess.
▷ Password tips
1,000 years to crack, but it’s hardly to remember. Just think
memorable. of two tired dinosaurs
Alice going to bed! It could
A name is easy to take a cracker over a
remember, but it million years to guess
wouldn’t be this password correctly.
difficult to guess. Fym5
This password could take a hacker over This is secure but easy
GH7pqZ2!?
Sleepydinosaur2! LINGO
What happens
Password Picker will enable you to create strong passwords by combining
words, numbers, and characters.
When you run the program, it will
PASSWORD PICKER 53
create a new password and show it on
the screen. You can ask it to keep How it works
creating new passwords until you find This project will show you how to use
one you like. Python’s random module. The program
Password cracker uses random choices from groups of
adjectives, nouns, numbers, and
A cracker is a program used by hackers to punctuation characters to assemble each
guess passwords. Some crackers can make password. You’ll soon be making crazy,
millions of guesses every second. A cracker
usually starts by guessing commonly used
hard-to-forget passwords, such as
words and names. An unusual password “fluffyapple14(“ or “smellygoat&”!
made up of several different parts will help
protect against crackers.
A random number
Start
A describing word from 0 to 99
54 FIRST STEPS
Try out the code window.
Run your code. The
4 welcome message
should appear in the shell
Welcome to Password
Picker!
EXPERT TIPS
you can keep a group of related
things together as a list. First create
the
6
Make a noun list
variable adjectives to store your
list by typing this new block of code Next create a variable that holds a
between the print() command and list of nouns. Put it under the
the import statements. Put the adjective list and above the print()
whole list in square brackets, and command. Remember to use
separate each item with a comma. commas and square brackets, like
you did in Step 5.
'orange', 'yellow', 'green',
'blue', 'purple', 'fluffy', 'white',
'proud', 'brave']
print('Welcome to Password
Picker!')
print('Welcome to Password
Picker!')
The list is in
square brackets.
7
Rolling a dice, picking a card from Pick the words
a deck, or tossing a coin are all To create the password, you’ll need to pick a random
things you can simulate by adjective and a random noun. You do this using the
generating a choice() function from the random module. Type
random number. You can read this code below the print() command. (You can
use this function any time you want to select a containing the items.)
random item from a list. Just give it the variable
random.choice(string.punctuation) This is a
constant
constant.
This changes the
PASSWORD PICKER 55
Create the new secure
password
Your secure password will be
To avoid this error, use the str() function to >>> print('route '+str(66))
change
TypeError: Can't convert 'int' object to str
The number goes inside the
the number into a string first. route 66 brackets of the str() function.
56 FIRST STEPS
11 12
Another one?
You can use a while loop to
generate another password if the
user says they want a different one.
Add this code to your program. It asks
the user if they require a new
password, then stores
the reply in a variable called
response.
Your
new Your random password
will probably be different.
special_char = random.choice(string.punctuation)
break
The while loop the user to enter a
ends here. response into the shell.
If the answer’s “yes” (y),
the loop returns to the
Pick a perfect start. If it’s “no” (n), the
password program exits the loop.
13 The input() function asks
greenpanda13*
That’s it – you’ve finished. Now you can
create hard-to-crack passwords that are Would you like another password?
Type y or n: n
fun to remember!
Hacks and
more cracker-proof?
PASSWORD PICKER 57
while True:
special_char =
random.choice(string.punctuation)
response = input('Would you like more
passwords? Type y or n: ')
blue potatoes!
Mmm! Hairy,
Modules
Modules are bundles of code that help you deal
with common coding challenges. Modules provide
the less exciting bits of code, letting you focus on
the fun stuff. Also, because modules are used by a
lot of people, they are likely to work well and be
free of bugs.
Built-in modules
There are lots of useful modules included
with Python. This collection of modules is
known as the Standard Library. Here are
some interesting modules from the library
that you might want to experiment with.
get today’s Tuesday
338 85 This 4th
module lets date, or Monday My
479 24 you work work out Sunday2n 3rd Birthday
235 with dates. how long it 1st
1
is until a d
▷
791 datetime You can Wednesday
special day.
element of chance to browser with this module,
a game or program. allowing you to open web
△ statistics pages directly from your
code.
Use statistics to
calculate averages or find ▷ s
ocket
the most common value in a The socket module allows
list of numbers. It’s handy if programs to communicate
you need to work out an across networks and the
average score in a game. Internet. It could be used to
create an online game.
▷ random
You used this module to
make random selections ▷ webbrowser You can This is the
in Password Picker. It’s control the computer’s web best one so far!
great for adding an
MODULES 59
Using a module
To use a module in your code, you have to tell Python
that you would like to include it. You instruct Python
which modules to include using import statements.
There are a few different ways that you can do this,
depending on what you need from the module.
This line imports the whole
webbrowser module.
▷ import...
Typing the keyword import allows you to use all the
contents of a module. However, you need to put the
module’s name before any function you use. This
code imports all the webbrowser() module and
uses its
open() function to open the Python website in the
computer’s browser.
▷ from... import...
If you only want to use a particular part of a module,
you can import just that part
Nine
word as question marks.
1478092571.003539
enter the correct word or have no lives left. ['?', 'i', '?', '?', 'a']
Lives left:
Each correct letter guessed Guess a letter or the whole word: p ['p', 'i', '?',
reveals one or more letters
'?', 'a']
in the secret word.
Lives left:
Guess a letter or the whole word: t Incorrect.
Each wrong guess makes
a heart disappear. You lose a life
Lives left:
Guess a letter or the whole word: i ['?', 'i', '?', '?',
'a']
i? z az
Lives left:
Guess a letter or the whole word: y Incorrect.
is slowly revealed.
NINE LIVES 61
How it works ◁ Nine Lives flowchart
The flowchart looks complicated, but
First you’ll create two lists: Start the code for this game is relatively
one to store the secret words short. The main body of the program
and one to store the clue, is a loop that checks the guessed
letters to see if they are part of the
which is made up of question secret word, and if the player has
marks. Then, using the Set lives to 9
any lives left.
random module, you’ll
make a random selection
from the list of secret words. Randomly select secret word
Next you’ll build a loop to I’ve already got
nine lives!
check the player’s guesses,
and also create a function to
update the clue as the word Guess a letter or word
Y
are known as
characters. There
are characters for
End most of the
world’s languages
Lose a life and special
N characters for
simple pictures,
including emoji.
Characters come
in sets. For
example, the ASCII
(American Standard
N Code for
Information
Interchange)
Is it a letter? Y
Y
character set is
used for the
English language.
Is letter in
For the hearts
You win secret word?
in this project you’ll
Does the
word match the secret
use the
word? Y Unicode character
set, which
Insert letter in secret contains lots of
word different symbols,
including the ones
below.
N
Lives left?
EXPERT TIPS numbers,
punctuation, and
Unicode symbols that
N characters can be displayed on
a computer
Game over The letters,
Setting up
You’ll build Nine Lives in two stages.
First you’ll import the module you need
for the program and create several
variables. Then you’ll write the main
code for the program.
File
lives = 9
Save
4
Save As Make a list
The program will only know
the words
import random
that you give it. You’ll need to put these Pick any card
words in a list, then store the list in a at random.
variable called words. Add this line words = ['pizza', 'fairy', 'teeth', 'shirt',
beneath your lives variable.
'otter', 'plane']
6
Store the clue
Now create another list to hold the clue. Unknown
letters are stored as question marks. These will
be replaced when the player guesses a letter
correctly. At the start of the game, the whole list
is question marks. You could write it as clue =
list['?', '?', '?', '?', '?'], typing one question
mark for each letter in the secret word, but the
code below is a faster way to write it. Add this
line after the secret_word variable.
NINE LIVES 63
EXPERT TIPS
Word length
Be careful to only add words that are
five letters long. The list that stores
the clue only has room for five
characters. If you add words of more
than five letters, you’ll see an error
message when the program tries to
enter any letters past the fifth one in
the clue.
secret_word =
random.choice(words)
clue = list('?????')
7 heart_symbol = u'\u2764'
guessed_word_correctly =
Show the lives left
This project uses the Unicode heart character to False
display how many lives are left. To make your
program easier to read and write, add the next This is a Boolean (True or False) value.
line of code to store the character in a variable. The player could never win, because
the last two question marks would
remain no matter what letter they
clue = list('?????')
guessed!
heart_symbol = u'\u2764'
64 FIRST STEPS
Index error: list assignment
index out of range The main code
The main part of the code is a loop that
If you try to add words that are less than gets a letter from the player and checks
five letters long, the program will work, if it’s in the secret word. If it is, the code
but the player will still see five question uses a function to update the clue. You’ll
marks. They’ll think that the answer has make that function, then create the main
to be five letters long. For example, if loop.
you used “car”, the program would look
like this.
▷ How it works
8 The function contains a while loop that works
Remember the result through the secret word one letter at a time, checking
Now make a variable to store whether or not the whether each letter matches the guessed
player has guessed the word correctly. The variable is guessed_word_correctly = False
set as False to begin with because the player doesn’t
know the word when the game starts. Type this line
below the code for the heart symbol.
['c', 'a', 'r', '?', '?']
def update_clue(guessed_letter, secret_word,
Lives left: clue): len() returns how
Guess a letter or the whole word:
letter. The index variable keeps count
while index < len(secret_word): many letters are in a word—in this case
of the current letter as the program
five.
index = 0
scans through the word. secret_word[index]:
if guessed_letter ==
find the right position in the list of index = index + 1
If a letter matches, the program question marks.
inserts it into the clue, using index to clue[index] = guessed_letter Add 1 to the index value.
is what the main loop does. Add this code below the
update_clue() function.
print('Lives left: ' + heart_symbol * lives) This gets the guessed
guess = input('Guess a letter or the whole
if guess in secret_word:
update_clue(guess,
secret_word, clue) else:
EXPERT TIPS
Repeating a string
The code print('Livesleft:'+heart_
symbol*lives) uses a neat trick to
display a heart for each remaining life. You
can tell Python to repeat a string a specific
number of times by multiplying it by a
number. For example,
print(heart_symbol*10) would
display ten hearts. Try this code out in the
shell.
NINE LIVES
65
>>>
the player has won. If the
guessed_word_correctly
variable is True, you know the
loop ended before the player
ran out of lives—so they’ve won
the game. Otherwise (else),
they’ve lost. Add this code to
the end of your program.
11
Did you win? Yay, I won!
When the game ends,
you need to figure out if
lives = lives – 1
if
guessed_word_correctly: This is shorthand for “if
guessed_word_ correctly
= True”
secret_word)
words = ['pizza', 'fairy', 'teeth', 'shirt', 'otter', 'plane', 'brush', 'horse', 'light']
▽ Change the number of lives You Mississippi
can make it easier or harder for the
player by giving them more or fewer ◁ Use longer words
lives. To do this, simply change the If you think using only five-letter
lives variable that you created in words makes the game too easy,
Step 3. switch to words that are a bit
longer—but remember to keep them
all the same length. To make the
game fiendishly difficult, search a
More lives? dictionary for the longest and most
Yes please! unusual words you can find!
Add difficulty
levels
To make the game more interesting, let the
player choose the difficulty level at the start of
the game. The easier setting gives the player
more lives.
I wish I’d chosen
program, just above the while loop.
1 It asks the player to choose a level.
Get the level an easier route!
Put this code at the start of your main
3 Hard
2
Test the code
Run the program to check if this change works. You
should see this message appear in the shell window.
if difficulty == 1:
lives = 12
elif difficulty == 2:
lives = 9
else:
lives = 6
1
Use an empty list
68 FIRST STEPS
index = 0
clue = []
Edit function
Next change the update_clue() function as
shown below. Each time the player guesses a letter
Make the ending smarter correctly, the program will now take away the number
At the moment, the game doesn’t end until of times that letter appears in the secret word from
unknown_letters.
you type out the word in full. Let’s make
the code smarter so the game ends when unknown_letters = len(secret_word)
you guess the last letter.
1
Make another variable _ss_s_
First create a variable to keep count of how many
letters are unknown. Add this code above the
update_clue function.
2
def update_clue(guessed_letter, secret_word, The code subtracts 1 from unknown_letters each time a
guessed letter appears in the word.
clue, unknown_letters): index = 0
return unknown_letters
NINE LIVES 69
◁ How it works
if guess in secret_word:
Why do you have to update unknown_letters in because the function checks every letter in the secret
the update_clue () function? Why can’t you just word to see if it matches the guessed letter.
subtract 1 when you know that the guessed letter is in
the secret word? This would work if each letter only
appeared once in the secret word. But if the letter
appears multiple times, it would make your count Hello, can you
wrong. By updating the variable in the function, the please connect me
code will subtract 1 from unknown_letters every to the function?
time the letter appears in the secret word. This is
print('Incorrect. You lose a life') at the end of the main loop. Now the game will
lives = lives – 1
automatically announce you as the winner
when you’ve guessed all the letters.
This line assigns the new value to
the unknown_letters variable. lives = lives - 1
4 if unknown_letters == 0:
Woohoo! I guessed
Turtl
e
graphics
Robot Builder
Creating graphics in Python is easy.
Python’s turtle module lets you
move a robot “turtle” around the
screen, drawing pictures with a pen
as it goes. In this project, you’ll
program the turtle to build more
robots—or at least pictures of
robots!
You can change the robot’s color scheme to
What happens whatever
you fancy.
When you run the program, Python’s turtle
sets off, scuttling around the screen as it
draws
a friendly robot. Watch as it assembles the
robot piece by piece, using different colors.
3 t.pendown()
4
2
EXPERT TIPS
Turtle mode
This block draws the
rectangle.
R 75
EXPERT TIPS 4
background color of the window. You need the turtle
to start with its pen up so that it doesn’t draw lines
until you want it to. It will only begin to draw when it
Turtle speed reaches the robot’s feet (Step 5). Type the following
code under the code you added in Step 3.
You can control how fast the turtle draws by
using the t.speed() command to set its speed Pull the turtle’s pen up.
to one of these values: “slowest”, “slow”,
“normal”, “fast”, and “fastest”. Set the turtle’s
Next get the turtle ready to start drawing, and set the
Building the robot
t.penup()
t.speed('slow')
t.bgcolor('Dodger blue')
speed to slow.
5
Draw the feet
You need to move the turtle to where you want to
# feet
understand. Python knows that it
should ignore them.
t.goto(–100, –150)
rectangle(50, 20, 'blue') 76 TURTLE GRAPHICS
t.goto(–30, –150)
r
y
(0,0)
be. This means that
i
t
y=0 b
i s
parentheses,
shows how far up or down from the (–200, –200) (200, –200) x=0
center it is. Coordinates are written in
like this: (x, y). x getting bigger
with the x coordinate first, x getting smaller
6 # legs
Draw the legs
The next bit of the program makes
7
the turtle move to where it
will start drawing the legs.
Type these lines under the
code you added in Step 5.
Now run the code again.
ROBOT BUILDER 77
8 # arms
t.goto(–150, 110)
9 # neck
Draw the neck
Time to give your robot a
10
neck. Type these # head
neck-drawing commands t.goto(–85, 170)
below the code you added
in Step 8. rectangle(80, 50, 'red')
78 TURTLE GRAPHICS
the
11 Draw
12
Draw the eyes where it’s going. To do this, squares inside it (for draw squares, since a
Let’s add some eyes so you’ll draw a large white pupils). You don’t have to square is a rectangle with
that the robot can see rectangle with two smaller write a new function to all its sides the same
length. Insert these 11.
commands under the code
you added in Step 10. # eyes
t.goto(–60, 160)
rectangle(30, 10,
'white') t.goto(–55, 155)
# mouth
rectangle(5, 5, 'black')
t.goto(-65, 135)
t.goto(–40, 155)
rectangle(40, 5, 'black')
rectangle(5, 5, 'black')
I need a
vacation!
13 t.hideturtle()
Hide the turtle
Finally, hide the turtle so it doesn’t look odd
sitting on the robot’s face. Type this line after
the code you added in Step 12. Run the
program to see the whole robot being built.