Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
33% found this document useful (3 votes)
2K views

Coding Projects in Python

Coding Projects

Uploaded by

tonet entea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
33% found this document useful (3 votes)
2K views

Coding Projects in Python

Coding Projects

Uploaded by

tonet entea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 144

G

P​ ro​J​ec​T​s
IN ​ PYTHON
®
R
!​
H e l l o W, o r l ​ d
G
P​ ro​J​ec​T​s
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

First American Edition, 2017


Published in the United States by DK Publishing
345 Hudson Street, New York, New York 10014
Copyright © 2017 Dorling Kindersley Limited
DK, a Division of Penguin Random House LLC
17 18 19 20 21 10 9 8 7 6 5 4 3 2 1
001–299420–June/2017
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-6188-9
DK books are available at special discounts when purchased in bulk for sales promotions,
premiums, fund-raising, or educational use. For details, contact: DK Publishing Special
Markets, 345 Hudson Street, New York, New York 10014 or SpecialSales@dk.com
Printed in China
A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW
www.dk.com
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 t​ o ​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 has a keen interest in coding.

CRAIG STEELE ​is a specialist in Computing Science education. He is Project


Manager for CoderDojo Scotland, which runs free coding clubs for young
people. Craig has previously worked for the Raspberry Pi Foundation,
Glasgow Science Centre, 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 earned a BS and PhD. 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.

DR. MARTIN GOODFELLOW ​has a PhD in computer science and


experience of teaching coding up to university level. He has developed
educational content and workshops for CoderDojo Scotland, Skills
Development Scotland, Glasgow Life, and Highlands and Islands
Enterprises, and has consulted on digital content for the BBC. He is
currently the Scottish Ambassador for National Coding Week.

DANIEL M​c​CAFFERTY ​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 daughter and when not teaching young
people to code, he enjoys bicycling and spending time with family.

DR. JON WOODCOCK ​studied physics at Oxford University and


computational astrophysics at the University of London. An avid coder
since the age of eight, he has programmed all kinds of computers from
single-chip microcontrollers to world-class supercomputers. He is author of
DK’s bestselling ​Coding Games in Scratch a ​ nd has written or contributed
to six other DK coding books.
8 ​FOREWORD

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

60 ​Nine Lives Expert


130 ​Secret Messages
142 ​Screen Pet
Let’ssss
s get
sssstarted!

GAMES IN PYTHON

158 ​Caterpillar
168 ​Snap
180 ​Matchmaker
190 ​Egg Catcher

REFERENCE

202 ​Project reference


220 ​Glossary
222 ​Index
224 ​Acknowledgments

Find out more at:


www.dk.com/computercoding
ord

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 Scratch​TM​ ​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.

Have fun coding!


Startin
g
with Python
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
△ ​Performing pet
addition, make music, move a
By learning how to code, you’ll be able to write your
robot across a room, or fly a rocket own programs and make the computer do what you
to Mars. want. It’s a
bit like having an electronic pet that you can teach to
perform tricks!
Dumb boxes
A computer can’t do anything of its own
accord—it just sits there like a dumb box
until it’s told exactly what to do. Because
computers can’t think for themselves and
can only do as they’re told, coders have to
do the thinking for them and write their
instructions carefully. Why don’t you say
something?

Programming languages ▽ ​Python


In order to tell a computer what to do, you Scratch is a visual programming language.
It’s great for creating games, animations,
need to learn a programming language. and interactive stories. You write code in
Visual languages are easy for beginners to Scratch by snapping together blocks of
learn, while professional coders use instructions.
text-based languages. This book is based Python is a text-based programming
language. In Python, programmers write
on the popular text-based language Python. code using words, abbreviations,
numbers, and symbols. Instructions are
typed in using the computer’s keyboard.
▽ ​Scratch

when clicked The answer to the sum


is shown on the screen
think ​3 ​+ ​3 in a “thinks” bubble.

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!

I knew you’d get


that wrong!

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.

Keep those eyes


peeled!

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.

It’s easy to read


and write!
△ ​Works everywhere
Python is portable. This means you can write and
run Python code on lots of different computers. The
same Python code will work on PCs, Macs, Linux
△ ​Easy to read and write machines, and Raspberry Pi computers. The
Python is a text-based computer programming programs behave the same way on each machine.
language. You write the instructions using a
mixture of English words, punctuation characters, △ ​Handy tools
symbols, and numbers. This makes Python code Python is packed with lots of useful tools and
preprogrammed code that you can use in your
programs. This is called the Standard Library.
Using these tools makes it easier and quicker for
you to build your own programs.
LINGO
Python
Python isn’t named after the type of snake. It’s ▷ ​Great support
actually named after a British comedy group called Python has well-written
“Monty Python’s Flying Circus.” The creator of documentation. It has a
Python, Guido van Rossum, was a big fan of the guide to getting started, a
group and their quirky humor. Python programmers reference section for looking
often use the group’s jokes and famous quotes in up what things mean, and
their code as a tribute. a bunch of example code.

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

▽ ​Crawling the web


written in Python. Much of YouTube Don’t worry, this won’t
is also built using Python code. hurt—much!

Python? It’s a serious


business! △ ​Medical marvels
Python can be used to program
robots to perform tricky
operations. A
△ ​Serious business Python-programmed robot
Python helps banks keep track of the surgeon can work more quickly
money in their accounts, and big than a human one, and be
store chains to set the prices of the more accurate and less likely to
goods they sell. make errors.

We’ve been
expecting you!

powerful program!
Action!

△ ​Out of this world


Software engineers used Python to create tools for
NASA’s Mission Control Center. These tools help the
crew prepare for and monitor the progress of each
mission.
△ ​In the movies
Disney uses Python to automate repetitive parts of
the animation process. Rather than animators
carrying out the same steps over and over, they
use a Python program to repeat the steps
automatically. This saves work, shortening the time
it takes to make a film.
allows you to write and edit Python code.

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 Windows • https://www.python.org/


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 3
Run the installer
choose “System” if the option appears. Download Python
Click on the latest version of Python for
Windows, beginning with the number 3. The
installer file will download automatically. Of the
LINGO different installer options, select “executable
installer”.
IDLE
• Python 3.6.0a4 - 2016-08-15
IDLE (short for Integrated • Windows x86 executable installer •
Development Environment) is a free app that you Windows x86-64 executable installer
get when you install Python. Designed for
beginners, IDLE includes a basic text editor that
all users” and click “next” at each Windows, use this installer.
prompt, without changing the If you have a 64-bit version of
Double-click the installer file to default settings. Windows, use this installer.
install Python. Choose “install for If you have a 32-bit version of
that it was successful by opening the
Click the installer.
IDLE program. Go to the “Start” menu,
choose “All Apps”, then select “IDLE”.
4 A window like the one below should
open up.
Open IDLE
When the installation is finished, check

Python 3.6.0a4 Shell


IDLE File Edit Shell Debug Window Help
Python 3.6.0a4 (v3.6.0a4:017cf260936b, Aug 15 2016, 00:45:10) [MSC v.1900
32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more
information. >>>

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.

Click the package


to run the installer.

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

IDLE File Edit Shell Debug Window Help ​Python 3.6.0a4


(v3.6.0a4:017cf260936b, Aug 15 2016, 13:38:16) [GCC 4.2.1
(Apple Inc. build 5666) (dot 3)] on darwin Type "copyright",
"credits" or "license()" for more information. >>>

18 ​STARTING WITH PYTHON be used to write and save


programs, while the shell
window runs Python
Using IDLE instructions immediately.

IDLE has two different


windows in which you can
work. The editor window can You should come out of your shell more!
Python because you don’t have to create a
new file first. Just type the code directly into
the shell window.
▽ ​Working in the shell
The code you type can be run straight away, and any
messages or "bugs" (errors) are displayed. You can use
The shell window the shell window like a notepad, to test out snippets of
code before you add them into a bigger program.
When you open IDLE, the shell window pops
up. This is the best place to get started in
Python 3.6.0a4 Shell darwin Type 'copyright',
IDLE File Edit Shell Debug Window 'credits' or 'license()' for more
This line
shows which version of Python you Help ​Python 3.6.0a4 information. >>>from turtle
have. import *
(v3.6.0a4:017cf260936b, Aug 15
2016, 13:38:16) [GCC 4.2.1 (Apple >>>forward(200)

You type Inc. build 5666) (dot 3)] on


in code at the ​>>>
operating
system you have.

The text here will depend on which


try it out for yourself. run
prompt.
>>>left(90)
>>>forward(300) >>>

These four lines of code are


a simple drawing program; ▽ ​Give the shell a test
EXPERT TIPS
Different windows >>> ''.join(reversed('Time to code'))

To help you know which window you should type


your code in, we’ve given each window in IDLE a
different color.
The editor window
The shell can’t save your code, so
Shell window when you close the shell window
the code you typed is lost forever.
Editor window That’s why you should use IDLE’s
editor window when you work on a
project. This window lets you save
your code. It also has built-in tools
to help you write your programs
and to trouble-shoot any errors.

The name of the

USING IDLE ​ 19

▽ ​The editor window


To open the editor window in IDLE, click on
the File menu at the top and choose New
File. An empty
Type each of these code snippets into the shell editor window will then appear.
window and press the enter/return key after each one. You’ll use the editor window to
The first line displays a message and the second line
write and run programs for the
does a calculation. Can you work out what the third
projects in this book.
line does?

You can run your


>>> print('I am 10 years old')

>>> 123 + 456 * 7 / 8


You type the code in file is shown here. The menu bar for the editor window is
here. This program different to the one for the shell.
prints a list that tells are even and which
you which numbers ones are odd.
programs from this menu.
if (counter
% 2) == 0):

Anything you tell


Python to print
gets displayed in
the shell window.

EXPERT TIPS

EvensandOdds.py Help print(counter)


IDLE File Edit Format Run Window print('is even')
for counter in range(10):
else: different parts of the code.
print(counter) The colors make it easier to
print('is odd') understand the code, and ◁ ​Errors
they’re useful when you’re Python uses red to
trying to spot mistakes. alert you to any errors
in your code.
I love idling!

◁ ​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

▷ ​Hello World flowchart


1 Launch IDLE

A shell window appears when you start


IDLE. Ignore it and click on File in the
IDLE menu. Choose New File to create an
How it works empty editor window where you can write
your program.
The program first displays the message
“Hello, World!” and then asks your name.
New File
Once you’ve typed in your name, it says
hello again, but this time it includes your Open
name in the greeting. The
Open Module
program uses something called a variable
to remember your name. A variable is Recent Files
used in coding to store information.
Programmers use diagrams
called flowcharts to plan
their programs and to show
Ask user to type their name
how they work. Each step
is shown in a box, with an
arrow leading to the next Hello, World!
step. Sometimes the steps Start
2
are questions and have Say hello, adding user’s
more than one arrow name
leading onward, depending
on the answer to the
question. Say hello

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!”

Class Browser print('Hello, World!')

YOUR FIRST PROGRAM ​ 23


4 LINGO
Save the file .py files
A pop-up box will appear. Type in a name for
your program, such as “helloworld.py”, and Python programs usually have
click Save. a name ending with “.py”,
which makes them easy to
Type the
Save As: Where:​
helloworld.py recognize. When you save a
Tags:
Check it works name of your
Documents program here.
program, Python
automatically adds
Cancel Save “.py” at the end, so >>>
you don’t need to
type it in.
5 Python Shell
mistakes, and finding these
“bugs” is vital if you want to Hello, World!
become an expert at
>>>
coding. Go back and check
your code for typing errors.
Did you include the The message will
appear in the shell.
brackets? Did you spell the

67 word “print” correctly? Fix


any mistakes, then try EXPERT TIPS
running the code again.
Keyboard
Add more lines
shortcut
A handy
Check Module Run Module shortcut to run
a program from
the editor
window is
Now run the first line of the simply to press
program to see if it works. F5 on your
Open the Run menu and keyboard. This
choose Run Module. You
is a lot quicker
should see the message
“Hello, World!” in the shell than selecting
window. “Run” and then
“Run Module”.

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

Variables >>> age = 12

If you want to write useful code,


to it. Use your own age if you want.
you’ll need to be able to store and
label pieces of information. That’s
what variables do. Variables are 2
great for all sorts of things— from Print the value
tracking your score in a game to Now type the line of code shown on the right
into the shell window. Hit the enter/return
performing calculations and key to see what happens.
holding lists of items. The value of ​age

EXPERT TIPS
How to create a variable This is the variable’s name.

A variable needs a name. Think of a name


that will remind you what’s inside the
variable. Then decide what you want to store >>> print(age)
in the variable. This is the variable’s value. 12
Type the name, followed by an equals sign,
The ​print() ​function prints the value
followed by the value. We call this “assigning of the variable between the brackets.
a value” to the variable.

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.

Dos and don’ts


△​Storage box • Start the variable’s name with a letter.
A variable is like a box with a name label. You can store • Any letter or number can be used in the name. •
data in the box and then use the name to find the data
Symbols such as -, /, #, or @ aren’t allowed.
again when you need to use it.
• Spaces can’t be used.
• An underscore ( _ ) can be used instead of a space. •
This value will be stored in the variable. Uppercase (capitals) and lowercase letters are different.
Python will treat “Score” and “score” as two different

1 Assign a value variables. • Avoid words Python uses as commands,
such as “print”.
In the shell window, type this line of code to
LINGO In coding, whole numbers are known as “floats”. Programs
called “integers”, while numbers usually count things using
Integers and floats with a decimal point in them are integers. Floats are more often
used for measurements.
VARIABLES ​ 25

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

symbols will subtract multiply divide

from the ones you use in class. ​Some of the Python math symbols Create a new variable, ​x​, and give it the

value 6.

1 A​ simple calculation >>> x = 6

Type this code in a shell window. >>> y = x * 7


It uses >>> print(y)
numbers stored in two variables,
named ​x ​and ​y​, to carry out a 42
simple multiplication. Hit the
Print the
enter/return key to get the answer. value of ​y​.
Multiply ​x ​by 7 and store the result in
y​.

The result of the calculation


again. What do you expect the result to be?
Change the value of ​x​.


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

26 ​FIRST STEPS The quote marks show that


the variable contains a string.

Working with strings


Combining strings key to print the string.
Variables become really useful when
1 you combine them to make new
variables. If you add two strings >>> name = 'Ally Alien'
Strings in variables together, you can store the >>> greeting = 'Welcome to
Strings can be put into variables. combination in a new variable. Try
Type this code into the shell window. this out. Earth, ' >>> message = greeting
It assigns the string ​'Ally Alien' ​to + name >>> print(message)
the variable ​name
and then displays it. Strings must Welcome to Earth, Ally Alien
EXPERT TIPS
always have quotation marks at the
beginning and end. >>> name = 'Ally Alien'
>>> print(name)
Ally Alien

2 Hit the enter/return


Remember the quote marks.

You can use a handy trick, ​len()​, to


count the number of characters in 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 there are in
'We​l​come to Earth, Ally Alien'​,
Length of a string type the line below into the shell once
you’ve created the string, then hit
enter/return. The quote marks ​
to another. aren’t shown
when
>>> len(message) you print a string.
28

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.

The list items must be


separated by commas.
>>> planets_players = ['Peter',
'Pablo', 'Polly', 'Penny', 'Paula',
'Patrick']

This list is stored in the


variable ​planets_players​.

This line gets the first item


in the list, from position 0.

>>> rockets_players[0]
'Rory'
>>> planets_players[5]
'Patrick'

This line gets the last item


in the list, from position 5.

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'

>>> rockets_players = ['Rory', 'Rav',


'Rachel', 'Renata', 'Ryan', 'Ruby']
Computers also make decisions

Making by asking questions.

decisions Questions that compare

Every day you make decisions


about what to do next, based on Err...
the answers to questions you ask
yourself. For example, “Is it Am I a
raining?”, “Have I done my horse?
homework?”, “Am I a horse?”
otherwise be skipped. Equals signs
have only two possible values:
▷ ​Boolean values True or False. Python calls
The answers to the questions these two values Boolean
computers ask values, and they must always
start with a capital letter. You
can store a Boolean value in a
variable.
Are you sure you want to do that? >>> answer_one = True
The questions that >>> answer_two = False
computers ask
themselves usually Boolean value
involve comparing one Variable
thing with another. For ▽ ​Logical operators
example, a computer These symbols tell computers to
might ask if one number is make comparisons.
bigger than another. If it Programmers call them
is, the computer might
then decide to run a
block of code that would EXPERT TIPS
In Python, you can use a single equals sign, =, or example below.
a double equals sign, ==. They mean slightly logical operators. You may have used some of them in
math. The words “and” and ”or” can also be used as
different things. Use a single equals sign when logical operators in computer code.
you want to set the value of a variable. Typing
age = 10​, for example, sets the value of the
variable ​age ​to 10. Use a double equals sign Symbol Meaning
when you want to compare two values, as in the
variable. This compares == != <
This sets the value of the >
equal to
your
>>> age = 10 not equal to less than
greater than
age with the variable.
>>> if age == 10:
print('You are ten years old.') ​The code I'm greater than you!

prints the message if the two match.

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 =

This variable stores the number of zebras.


>>> zebras < pineapples

▽ ▷ ​Make comparisons True


Now try typing the following lines of code to compare
the values of the two variables. After you’ve typed The number of zebras is less
than the number of pineapples.
each line, press the return key and Python will tell
you if the statements are True or False.

The number of pineapples is

greater than the number of zebras. The


​ number of pineapples and the number of zebras aren’t
equal.

>>> pineapples > zebras


True

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.

>>> (pineapples == 3) and (zebras


== 2) False

>>> pineapples ​==


True
One part is correct (​zebras == 2​),
Variable
Logical operator Boolean value
One part (​pineapples == 3​) is Variable
incorrect, so the statement is False. >>> (pineapples == 3) or
(zebras == 2) True
>>> pineapples != zebras so the statement is True.
Boolean expression, then hit the
Ride the rollercoaster enter/return key.
A sign at the theme park says you must be
over 8 years old and taller than 4 feet 7
inches to ride the rollercoaster. Mia is 10
years old and 5 feet tall. Let’s use the shell You can’t ride –
you’re too small!
to check whether she can go for a ride.
Type the following lines of code to create
But I’m 100
variables for Mia’s age and height and years old!
assign the correct values to them. Type
the rules for going on the rollercoaster as a
assign values to
>>> height = 1.5
the variables.
>>> (age > 8) and (height > 53

Mia can go on the rollercoaster! inches) True


This is a Boolean
expression meaning “older than 8 and
more than 4 ft 7 in tall”.

Branching
These two lines >>> age = 10

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.
Imagine you have to decide what
route to walk each day based on the
answer to the question “Is today a
LINGO weekday?” If it’s a weekday, you
Condition take the route to school; if it’s not,
you take the route to the park. In
Python, the different routes through
A condition is a Boolean
a program lead to different blocks of
expression (a True-or False code. A block can be one statement
comparison) that helps a or several, all indented by four
computer decide which route to spaces. The computer uses a test
take when it reaches a branch called a condition to figure out which
in the code. blocks it should run next.
▷ ​School or park?
MAKING DECISIONS ​ 31
▷ ​One branch This line asks the user to reply “y” (yes) or “n” (no).
The simplest branching command is an ​if ​statement. It
only has one branch, which the computer takes if the
is_dark = input('Is it dark outside? y/n)')
condition is True. This program asks the user to say if
it’s if is_dark == 'y':
dark outside. If it is, the program The code shows this message in the shell
pretends that the computer is going window.
to sleep! If it’s
print('Goodnight! ▷ ​Two branches
Zzzzzzzzzzzzzzz....') Do you want a program to do one
Condition thing if Condition

not dark, ​is_dark == 'y' ​is False, This branch is taken if


the condition is True.
so the “Goodnight!” message isn’t
displayed.

This line asks for input from the user.


tentacles = input('Do you have tentacles?
a condition’s True and another thing if it’s False? (n/y)') if tentacles == 'y':
If so, you need a command with two branches,
called an ​if-else ​statement. This program asks if print('I never knew octopuses could type!')
the user has tentacles. If they answer “Yes”, it else:
decides they must be an octopus! If they answer
print('Greetings, human!')
“No”, it decides they’re human. Each decision
prints a different message. This block runs if the condition is This block runs if the condition is
True. False.
weather = input ('What is the forecast for
today? (rain/snow/sun)')

▷ ​Multiple branches ​When there are more than


condition is True.
two possible paths, the First condition
statement ​elif ​(short for if weather == 'rain': This block runs if the first
“else-if”) comes in handy. This
program asks the user to type in the
weather forecast: either “rain”,
“snow”, or “sun”. It then
chooses one of three branches and
weather conditions.
sunglasses!')

This block runs if both


conditions are False.

△ ​How it works

Second
condition

print('Remember your print('Remember your wooly


umbrella!') elif weather == gloves!') else:
This block runs if the second condition is
'snow': print('Remember your True.

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 s​ tatements
to check for more types of weather.
Loopy loops
Computers are great at doing boring tasks without
complaining. Programmers aren’t, but they are
good at getting computers to do repetitive work for
them—by using loops. A loop runs the same block
of code over and over again. There are several
different types of loop.

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

This line displays a message


showing the total number of
balancing hippos.
the answer to the question
print(str(hippos) + ' balancing
hippos!') answer = input('Add
Add another
hippo to the another hippo? (y/n)')
number balanced.
keep going for as long
34 ​FIRST STEPS as the

▷ ​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.

Ctrl-C ▽ ​Escaping infinity


You can deliberately use an infinite loop
to get input from the user. This
(annoying) program asks if the user is
bored. As long as they type “n”, it keeps
asking the question. If they get fed up
and type “y”, it tells them they’re rude
and uses the ​break ​command to
leave the loop!

The True condition is that the


user is not bored yet (​'n'​).

>>> while True:


answer = input('Are you bored
yet? (y/n)') if answer == 'y':

print('This is an infinite loop!')

△ ​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

Loops inside loops Can the body of a loop have another


loop within it? Yes! This is called a
LOOPY LOOPS ​ 35 nested loop. It’s like Russian dolls,
where each doll fits
inside a larger doll. In a nested loop,
an inner loop runs inside an outer
loop.

I like Russian dolls—but


they’re always so full
of themselves!

The loop variable of the outer


loop is ​hooray_counter​.

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,

>>> for hooray_counter in


range(1, 4): for hip_counter in T​he loop variable of the inner loop is

hooray_counter ​= 1 hip_counter
​ ​= 1 ​Hip

The whole of the inner ​for ​loop


outer ​for ​loop. Each time
Hooray! Hip
we do one repeat of the
Hip hip_counter ​= 1 outer loop, we have to do
hooray_counter ​= 2
hip_counter ​= 2 two repeats of the inner
Hooray! Hip
loop. This means the body
Hip of the outer loop is run three
hip_counter ​= 1 times in total, but the body
hooray_counter ​= 3 Hooray!
hip_counter ​= 2
of the inner loop is run six
hip_counter ​= 2 times.

is inside the body of the


Animal Quiz
Guess the Animal!
Which bear lives at the North Pole? ​polar
bear

Are you a fan of quizzes? Would Correct answer


you like to make one yourself? In Which is the fastest land animal? ​cheetah
this project, you’ll build an animal
quiz. Even though the questions
are about animals, this project
can be easily modified to be
about any other topic. I thought I was the
largest animal.

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.

If you guess incorrectly, you get another go.


Correct answer
Which is the largest animal?

Your score is 2 After


​ three wrong guesses, the program shows you the
correct answer.

This is your score out of


a possible 3 points.
This project makes use of a function—a
block of code with a name that performs
a specific task. A function lets you use
How it works the same code repeatedly, without
having to type it all in every time. and whether the player has used up all of their
chances. The score is stored in a variable during
Python has lots of built-in functions, but the game. Once all the questions have been
it also lets you create functions of your answered, the game ends.
own.
Start
▷ ​Calling functions
When you want to use a
function, you “call it” by typing Set score to 0
its name in your code. In
Animal Quiz, you’ll make a
function that compares the
player’s guess to the true Display “Guess
the Animal!”
answer to see if it’s correct.
You’ll call it for each question
in the quiz.
ANIMAL Ask question and

QUIZ ​ 37 get user’s answer

▽ ​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

the game to the player. This will be


the first thing that the player sees
on the screen.

Run the code


Now try running the code. From
the Run menu, choose Run print('Guess the Animal!') The variable ​guess1
Module. What happens next? You stores whatever the
should see the welcome message user types in.
in the shell window.

Ask a question (user input) ​The


Run
next line of code asks a question
and waits for the player’s Python Shell
response. The answer (the user
input) is saved in the variable Check Module
guess1​. Run the code to make
sure the question appears. Run Module

print('Guess the Animal!')


guess1 = input('Which bear
lives at the North Pole? ')

ANIMAL QUIZ ​39


the top of your script, answer. The two words in answer): global score
before ​score = 0​. brackets are
6 The code creates a
function, called
“parameters”—bits of
information the function
if guess == answer:
print('Correct answer')
Build a check function
check_guess()​, that will needs. When you call score = score + 1
The next task is to check if check if the player’s guess
the player’s guess is matches the correct def check_guess(guess, score = 0
correct. Type this code at
The first line gives the function changes to the variable can be Add 1 to the player’s score.
a name and parameters. Don’t forget the brackets.
(run) a function, you assign
This line says the ​score seen throughout the whole
(give) values to its program.
variable is a global variable. It
ensures that
parameters.

89

Call the function


Now add a line at the end of the
script to call (run) the
check_guess() ​function. This
code tells the function to use the
player’s guess as the first
parameter and the phrase “polar
bear” as the second parameter.

Test the code


Try running the code again and
type in the correct answer. The
shell window should look like this.

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')

guess2 = input('Which is the fastest land


This tells the program
animal? ') check_guess(guess2, 'cheetah') to check ​guess3.

guess3 = input('Which is the largest

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

guess3 = input('Which is the largest animal?


') check_guess(guess3, 'blue whale')

print('Your score is ' + str(score))


string. This is because Python shows
an error if you try to add a string and an
△ ​How it works integer (whole number) together.
For this step, you have to use the ​str() This creates a message giving the player’s
function to change a number into a score and displays it on the screen.
will
be

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.

def check_guess(guess, converted into lower-case


Test the code again answer): characters before being checked.
Run your code for a third time. Try global score This ensures that the code works
typing the whether the player uses all
if guess.lower() ==
capital letters, all lower-case
answer.lower():
print('Correct answer')
score = score + 1

Change this line. ​


​ ow it works
△H

Both the guess and the answer


correct answers using a mixture of capitals and Which is the fastest land animal? ​Cheetah
lower-case letters and see what happens. Correct answer

Which is the largest animal? ​BLUE WHALE


Guess the animal!
Correct answer
Which bear lives at the North Pole? ​polar bear
letters, or a mixture of the two.
Correct answer

Your score is 3 ​The case is ignored when deciding whether an answer is correct or not.

ANIMAL QUIZ ​41

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).

Use a backslash character if you need to


split a long line of code over two lines.
Multiple-choice questions are easier to
guess = input('Which one of these is a fish? \ understand if the question and possible answers
appear on different lines. To show the fish
A) Whale B) Dolphin C) Shark D) Squid. Type A,
question as a list of options, type it like this.
B, C, or D') check_guess(guess, 'C')
guess = input('Which one of these is a fish?\n \
A) Whale\n B) Dolphin\n C) Shark\n D) Squid\n \

REMEMBER Type A, B, C, or D ')

Breaking the line check_guess(guess, 'C')

◁ ​Make a multiple-choice quiz ​This code shows how


to create multiple-choice questions, which give the Which one of these is a fish?
player several possible answers to choose from.
A) Whale
B) Dolphin

You can use ​\n ​to make a new line anywhere.


This is how the question appears
C) Shark
in the shell window.
D) Squid
Type A, B, C, or D
print('Correct Answer') ​score = score + 3
– attempt ​still_guessing = False

​while still_guessing and attempt < 3: if


ANIMAL QUIZ ​ 43
guess.lower() == answer.lower():
◁ ​Better score for fewer attempts
Reward the player for getting the answer right with line that updates the score. Now it will give 3 points
fewer guesses. Give 3 points if they get it in one try, minus the number of unsuccessful attempts. If the
2 points for needing two attempts, and 1 point for player
using all three chances. Make this change to the
This line = 3 points are added to their score;
else:
replaces on the second guess, it’s 3 – 1 = 2
if attempt < 2: score + 1​. points; and on the third guess, it’s 3 –
gets the answer right first time, 3 – 0 2 = 1 point.
chances to get the right
guess = input('Mice are mammals. True
▷ ​Make a true-or-false quiz ​This code shows or False? ') check_guess(guess, 'True')
how to create true-or-false questions, which
have only two possible answers.

def check_guess(guess, answer):


▷ ​Change the difficulty
To make the quiz harder, give the player fewer global score
answer. If you make a true-or-false
quiz, you’ll only want the player to
have one guess per question, and
perhaps no more than two guesses
per question if it’s a multiple-choice
quiz. Can you figure out what you’d
need to change the highlighted
numbers to for true-or-false or
multiple-choice questions?

Not as easy as I thought

still_guessing = True print('Correct Answer') score =


attempt = 0 score + 1

while still_guessing and still_guessing = False else:


attempt < ​3:​ ​if guess.lower() if attempt < ​2​:
== answer.lower():
Change this number.Change this number.

it would be...

Change this number.

if attempt == ​3​:
​print('The correct answer is ' + answer)

▷ ​Choose another topic


​guess = input('Sorry wrong answer.Try again.
')
attempt = attempt + 1

Create a quiz on a different subject, such as


general knowledge, sports, movies, or
music. You could even make a quiz about
your family or friends and include some
cheeky questions, like “Who has the most
annoying laugh?”
Define ​When you use the ​def ​keyword and write
Functions the code for a function, coders say you “define”
the function. You also define a variable when you
first set its value.
Programmers love shortcuts that
make writing code easier. One of Parameter ​A piece of data (information) that you
the most common shortcuts is to give to a function to use.
give a name to a block of code that Return value ​Data that you pass from a function
does an especially useful job. back to the main code. You get it using the
Then, instead of having to type keyword ​return​.

out the whole block each time you


need it,
you simply type its name. These This asks the user to
named blocks of code are called type in their name.
functions.
functions that you can use in your code.
These are helpful tools that let you do
lots of tasks, from inputting information
How to use a function and showing messages on the screen
to converting one type of data into
Using a function is also known as “calling” it.
another. You’ve already used some of
To call a function, you just type the
Python’s built-in functions, such as
function’s name, followed by a set of
print() ​and ​input()​. Have a look at
brackets that contain any parameters you
these examples. Why not try them out
want the function to work with. Parameters
in the shell?
are a bit like variables that belong to the
>>> name = input('What is your
function, and they allow you to pass data
between different parts of your program. name?') What is your name? Sara
When a function doesn’t need any >>> greeting = 'Hello' + name
parameters, the brackets are left empty. >>> print(greeting)
Hello Sara

Built-in functions
This shows the content of the
Python has a number of built-in variable ​greeting ​on the screen.

△ ​input() and print()


These two functions are like opposites. The ​input()
LINGO function lets the user give instructions or data to the
program by typing them in. The ​print() f​ unction sends
Function terms output to the user by displaying messages or results on the
screen.
There are a number of special words that coders
use when talking about functions.

Call ​To use a function.


FUNCTIONS ​ 45
▽ ​max() ▽ ​min()
30
The function ​min() ​does the opposite of m
​ ax()​.
The ​max() ​function selects the maximum value from It selects the minimum value from the parameters
the parameters you give it. Hit the enter/return key to you put inside its brackets. Experiment for
see the value on the screen. This function takes yourself with the ​max() ​and m​ in() ​functions.
multiple parameters, which must be separated by
commas.
>>> min(10, 16, 30, 21, 25, 28)
10
>>> max(10, 16, 30, 21, 25, 28)
Some of the different
The maximum value is the types of data we’ve Don’t forget
highest number in the brackets.
Always separate multiple
come across so far, the dot.
parameters with commas. such as integers,
When you hit the enter/return key, strings, and lists, have >>> 'bang'.upper() 'BANG'
the code shows you the lowest
number.
their own functions.
These functions must Empty brackets mean that no
be called in a special parameters are needed.

way. You type the data


or the name of the
Another way of variable holding the
calling data, followed by a dot,

the function’s name, and finally


brackets. Test out these code snippets
in the shell.
This is the new string, all in capitals.

△ ​upper()

I just love
the shell!

The function has two parameters.

>>> message = 'Python makes me happy'

The ​upper() f​ unction takes an existing


string and returns a new string in which all
the lower-case characters are changed to
upper-case (capitals).

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

The list of numbers


stored in the variable
happy ​with :​ D​.
>>> message.replace('happy',
':D') 'Python makes me :D' △ ​replace() △ ​reverse()
>>> countdown.reverse() >>>
The list is now reversed.
The new string replaces print(countdown) [3, 2, 1]

purpose and a good name that


explains what they do—think of the
check_guess() ​function you used
in Animal Quiz. Follow these
Two parameters are needed for this function: the first instructions to create, or
is the part of a string you want to replace, while the
second is the string you want to put in its place. The
function returns a new string with the replacements
made.
Use this function when you want to reverse the order of
the items in a list. Here, it’s used to reverse a list of
numbers stored in the variable ​countdown​. Instead of

1 Define the function

Create a new file in IDLE. Save it as


printing the list as ​[1, 2, 3]​, the function makes it print
“functions.py”. Type these lines into the editor
[3, 2, 1]​.
window. An indent is added at the start of each
46 ​FIRST STEPS line in the function. Save the file again, then run
the code to see what happens.

Making a function The name of


There are no

The best functions have a clear


screen. hours = 24
“define”, a function that the function minutes = hours * 60
calculates the number of parameters yet.
seconds in a day and then def print_seconds_per_day():
prints the answer on the

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.

EXPERT TIPS def print_seconds_per_day​(​days​):

Top advice
It’s important to define your functions before

The number of seconds in a day appears in the shell.


you use them in your main code. function The function’s
parameter
When you’re learning to code hours = ​days * ​24 minutes =
with Python, it’s helpful to put This line uses the
hours * 60 seconds = minutes
parameter ​days​.
your functions at the top of your * 60 print(seconds)
file, after any import statements.
By doing this, you won’t make Gives a value (​7​) to the parameter
days
the mistake of trying to call a print_seconds_per_day(​7​)
before you’ve defined it. Existing
​ lines of code

604800 are shown in grey and new


lines of code in bold.
The number of seconds in 7
days

FUNCTIONS ​ 47


3 Return a value def convert_days_to_seconds(days):

Once you have a function that does ​hours = days * 24


something useful, you’ll want to use the minutes = hours * 60
results from that function in the rest of your
code. You can get
values out of a function by rename the function to match its
“returning” them. Change your new purpose. Don’t try to run the seconds = minutes * 60
code as shown here to get the code just yet. return seconds
return value from your function.
You should The function’s new name
The line that called the function
is deleted, as the function now
has a new name and purpose.

This calls the function and gives a


The keyword ​return ​gives the value of value (​7​) to the parameter ​days​.
the variable ​seconds​.
This is the number of
4 milliseconds in 7 days.
Store and use the return value
You can store the return value from a
function in a variable to use later in your EXPERT TIPS
code. Add this code under your function. It
stores the return def
value and uses it to calculate the number convert_days_to_seconds(days)
of milliseconds (thousandths of a second).
: hours = days * 24
Try it out and experiment with the number
of days. minutes = hours * 60
seconds = minutes * 60
return seconds
The return value is stored in the
variable ​total_seconds​.
total_seconds =

This line prints the value convert_days_to_seconds(7)


of ​milliseconds​.
milliseconds = total_seconds * 1000
print(milliseconds) convert_days_to_seconds()​. Just
like with variables, it’s important that the
name you use accurately explains what the
604800000 function does. This makes your code much
The total number of seconds
easier to understand.
is converted into milliseconds
and stored in the variable
milliseconds​.
The rules for naming functions are similar
to those for variables. Function names can
contain letters, numbers, and underscores,
Naming your functions but they should begin with a letter. If there
are several words in the name, the words
In Step 3, you changed the name of your should be separated by underscores.
function from
print_seconds_per_day() ​to
Fixing bugs
If something’s wrong with your code, Python will try to
help by showing an error message. These messages
can seem a bit puzzling at first, but they’ll give you
clues about why your program isn’t working and how
to fix it.
look in your code.
▽ ​Messages in the IDLE editor
Error messages A pop-up box warns you there’s an error. Click OK to
Both the IDLE editor and the shell window return to your program. There will be a red highlight on
can show error messages if mistakes are or near the error.
detected. An error message tells you what
type of error has occurred and where to SyntaxError
the error to happen. typing mistake.

▽ ​Messages in the shell invalid syntax ​OK


Python displays error messages >>>
in red text in the shell window.
Traceback (most recent
The program stops working call last):
when an error message
appears. The message tells This pop-up box tells you there’s a
you which line of code caused syntax error, which means there’s a

File "Users/Craig/Developments/top-secret-python-book/age.py", line 21, in


module> print('I am'+ age + 'years old')

TypeError: Can't convert 'int' object to str implicitly

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.

input('What is your name?'

The first quotation mark is missing.


It needs to be a single quote to match.

print(It is your turn')

This is a spelling mistake—it


should be ​short_shots​.

made a spelling mistake? All these things can cause


syntax errors. Python uses indentation to understand
where blocks of code start and stop. An
indentation error means something is wrong
Indentation errors with the way you’ve structured the code.
total_score = (long_shots * 3) + (shoort_shots *
Remember: if a line of code ends with a
colon (​:​), the next line must be indented.
Press the space bar four times to manually
2) ​▽ ​Indent each new block indent a line.

if weekday == True:
print('Go to school')

This line of code would trigger an


indentation error message.

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!

budget = 'Fifty' * 'Five'

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!

You can multiply two numbers


in Python, but you can’t do
multiplication with strings.

hot_day = '20 degrees' > 15

Python can’t check to see if


a string is greater than a
number, because they are
different data types.

list = ['a','b','c']
find_biggest_number(list)

This function is expecting you to


A name error message appears if your code uses the name
of a variable or function that hasn’t yet been created. To
avoid this, always define your variables and functions
before you write code to use them. It’s good practice
to define all your functions at the top of your program.
The ​print() ​instruction needs
to come after the variable.
▷ ​Name errors
A name error in this code stops Python
print('I live in ' + hometown)
from displaying the message “I live in
Moscow”. You need to create the hometown = 'Moscow'
variable ​hometown
first, before you use the ​print() f​ unction.

FIXING BUGS ​51


Logic errors
Sometimes you can tell something have typed in the code correctly, but
has gone wrong even if Python if you missed an important line or put
hasn’t given you an error message, the instructions in the wrong order it
because your program isn’t doing won’t run properly.
Logic error! Does not compute...
what you expected. It could be that
you’ve got a logic error. You may

print('Oh no! You've lost a life!') print(lives)

lives = lives – 1
EXPERT TIPS

All the lines of code are correct,


Bug-busting checklist
but two are in the wrong order.
patient and take your time—you’ll find the problem in
the end.

Sometimes you might think that you’ll never get


a program to work, but don’t give up! If you
follow the tips in this handy checklist, you’ll be
able to identify most errors.
Ask yourself...
• If you build one of the projects in this book and it
doesn’t work, check that the code you’ve typed
matches the book exactly.
• Is everything spelled correctly?
• Do you have unnecessary spaces at the start of a
line? • Have you confused any numbers for letters,
such as 0 and O? • Have you used upper-case and
lower-case letters in the right places? • Do all open
parentheses have a matching closing parenthesis? ( )
[ ] { } • Do all single and double quotes have a
matching closing quote? ‘ ‘ “ ” • Have you asked
someone else to check your code against the book? •
Have you saved your code since you last made
changes?

◁ ​Can you spot the bug?


This code will run with no error messages, but there’s
a logic error in it. The value of ​lives ​is shown on the
screen before the number of lives is reduced by one.
The player of this game will see the wrong number of
lives remaining! To fix it, move the instruction
print(lives) ​to the end.

◁ ​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.

▽ ​Password Picker flowchart ​The program randomly


selects each of the password’s four parts, puts them
together, and displays the password in the shell
window. If you want another password, it repeats those
steps again. If you don’t, the program ends.

A random number
Start
A describing word from 0 to 99

adjective + noun + number + punctuation


Choose a random
adjective
simple!
The name of a thing
Choose a random noun
A character such as “!” or
Clever yet “?”
between 0 and 100 long to make.
The program does clever That string is totally random!
things with passwords,
but there isn’t a lot of
Choose a random number
code in it, so it won’t take
File. Save the file as
12 “password_picker.py”.
Create the secure
password
Add the modules
Choose a
random punctuation
Create a new file
character
Open IDLE. Under the
File menu, select New
The ​random m
​ odule
helps you make choices.

Display the secure


password

Want another password?


3
Import the ​string ​and
N random ​modules from
the Python library. Type
End these two lines at the top
Y of your file, so you can
use the modules later.
import random This line shows a message
to welcome the user.
import string

Welcome the user import random


The ​string m ​ odule lets
First create a message you do useful import string
to welcome the user to things with strings, like print('Welcome to
the program. splitting them Password Picker!')
apart or changing the way
they appear.

54 ​FIRST STEPS
Try out the code window.
Run your code. The
4 welcome message
should appear in the shell
Welcome to Password
Picker!

Make an adjective list


You’ll need adjectives and import string
nouns to generate new Each item is a string.
passwords. In Python, Put a comma after each item.
The list is stored in the
5 variable ​adjectives​.

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!')

​'white', 'proud', 'brave']

nouns = ['apple', 'dinosaur',


'ball', 'toaster', 'goat', 'dragon',
'hammer', 'duck', 'panda']

print('Welcome to Password
Picker!')

The list is in
square brackets.

Use commas and square brackets.

adjectives = ['sleepy', 'slow', 'smelly', 'wet', 'fat', 'red',

more about how to use Python’s


Random numbers random module in the “Docs”
section of the “Help” menu.

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

print('Welcome to Password Picker!')


Help ​This variable holds
Search One of the nouns from the list is
adjective = chosen and stored in this variable.
IDLE Help Python Docs a word chosen randomly from the
random.choice(adjectives)
adjectives list.
noun = random.choice(nouns)
Now use the ​randrange() ​function from the random
8 module to select a random number from 0 to 99. Put
Select a number this line at the bottom of your code.
noun = random.choice(nouns) EXPERT TIPS
number = random.randrange(0, 100)
Constants
A constant is a special type of variable whose
contents can’t be changed. The constant
9 string.punctuation ​holds a string of
characters used for punctuation. To see what it
Select a special character
Using the ​random.choice() ​function again, add this
holds, type ​import string ​into the shell,
line to pick a random punctuation character. This will followed by ​print(string.punctuation)​.
make your password even harder to crack!

>>> import string


number = random.randrange(0, 100)
>>> print(string.punctuation)
special_char =
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ​Characters in this

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

10 stored in this variable.


random number into a string.
password = adjective + noun + str(number) +
special_char print('Your new password is: %s'
It’s time to assemble all the different parts to create the
% password)
new secure
password. Type these two lines of code at the end of
your program.

This displays the new


EXPERT TIPS password in the shell.
Strings and integers
function, Python shows an error1, in <module> print('route
when you try to add an integer '+66)
to a string. Test it: type
>>> print('route '+66)
The ​str() ​function turns a
whole number (an integer) into Traceback (most recent call
a string. If you don’t use this last): File '<pyshell#0>', line Error message
implicitly

print('route '+66​) into the shell window.

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

Test the program


This is a good point to test your code.
Run it and look in the shell to see the
result. If you have errors, don’t worry.
Look back over your code carefully to
spot any mistakes.

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.

Don’t forget to save


your work.

Welcome to Password Picker! password is: bluegoat92=

print('Welcome to Password Picker!') while True:


​adjective = random.choice(adjectives) You need to
indent these
noun = random.choice(nouns) existing lines
number = random.randrange(0, 100) to make sure
they’re in the
The ​while ​loop while ​loop.
starts here.

special_char = random.choice(string.punctuation)

password = adjective + noun + str(number) +


special_char print('Your new password is: %s' %
password)

​response = input('Would you like another password? Type y or n: ')


if response == 'n':

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!

Welcome to Password Picker!


Your new password is: Type “​y​”at this prompt to get a new password.
yellowapple42} Would you like
another password? Type y or n: y Type “​n​” at this prompt to quit the program.
Your new password is:

these extra features. Can you think


of any other ways to make it even

Hacks and
more cracker-proof?
PASSWORD PICKER ​ 57

tweaks I’ll never find


the right key!

Try remixing your program to add


unusual or silly words that will stick in
your mind if they appear in a password.

while True:

nouns = ['apple', 'dinosaur', 'ball',

▷ ​Add more words 'toaster', 'goat', 'dragon', 'hammer',


To increase the number of possible 'duck', 'panda', ​'telephone', 'banana',
passwords, add more words to the lists
'teacher']
of nouns and adjectives. Think of
The ​for l​ oop runs 3 times,
and selects 3 different
passwords.

​for num in range(3):

​adjective = random.choice(adjectives) password = adjective + noun + str(number)


noun = random.choice(nouns) + special_char print('Your new password

number = random.randrange(0, 100) is: %s' % password)

special_char =
random.choice(string.punctuation)
response = input('Would you like more
passwords? Type y or n: ')
blue potatoes!

△ ​Get multiple passwords


Change the code so your program will
create and display three passwords at
once. You will need to use a ​for ​loop.
Put it inside the ​while ​loop. ▷ ​Make it longer
Make the password longer and more secure
Keep these by adding another word into each password.
lines indented. You could create a list of colors, then select a
random color to add to each password.
Add a random colour.

Your new password is: hairybluepotato33%

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 Sunda​y​2n 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

>>> import webbrowser


>>>
webbrowser.open('https://docs.python.org/3/li
brary')

The name of the


module comes
before the function.
Only the ​choice >>> direction = choice([‘N’, ‘S’, ‘E’, ‘W’])
function is imported from
the ​random ​module.

>>> from random import choice


by adding the ​from ​keyword. Now it. is needed.
you can just use the function name >>> print(direction) W
on its own. This code imports the
random ​module’s ​choice() The code prints a
function. The function picks a random direction. This line imports and renames the
random item from any list you give time() ​function.
No module name
>>> now = time_now()
▷ ​from... import... a... ​Sometimes you may
>>> print(now)
want to change the name of an imported module This variable uses the
or function, perhaps because you’ve already used
that name or maybe it isn’t clear enough.
>>> from time import time as time_now

To do this, use the ​as ​keyword game, you have to


followed by the new name. In the
example shown here, the ​time() guess the secret word
function, which we’ve renamed
You’re exactly
one letter at
time_now()​, gives us the 1478092571.003539
current time. The time given is the seconds late!
exact number of seconds since
00:00 on January 1, 1970—a date
used by most computers as the
60 ​
FIRST STEPS
The clue shows the mystery
start of their clock.

Nine
word as question marks.
1478092571.003539

['?', '?', '?', '?', '?'] Lives left:


The number of seconds since 00:00 on
January 1, 1970
function’s new name. Lives
The number of lives you have left is
In this shown by hearts.
nerve-shredding
a time. If your guess is wrong, you What happens
lose a life. Choose your letters The program shows you a mystery word
carefully, because you only have with its letters replaced by question marks.
nine lives. Lose all your lives, and If you guess a letter correctly, the program
it’s game over! replaces
the question mark with the correct letter.
When you think you know what the word is,
type it out in full. The game ends once you You lose a life

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

['p', 'i', '?', '?', 'a']


Lives left:
Guess a letter or the whole word: ​pizza ​You
I guess “P”! ​
You have seven lives
won! The secret word was pizza
remaining. What’s your
next guess?
If you know the word, type
Guess a letter or the whole word: ​a ​['?', '?', '?', it in to win the game.
'?', 'a']

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.

12 Import the module


This project uses Python’s ​random ​module, so
Create a new file
start by typing the line of code shown here to
Open IDLE and create a new file. import it.
Save it as “nine_lives.py”.

File

lives = 9

Save
4
Save As Make a list
The program will only know
the words
import random

3 The player starts with nine lives.


Make a variable
Below the import line, create
a variable called ​lives ​to
keep track of the number of
lives (guesses) the player import random ​lives = 9
has left.

variable called ​secret_word​. Add a


line to create this new variable.

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']

Each item in the list is a string

5 made up of five characters.

Choose a secret word


words = ['pizza', 'fairy', 'teeth', 'shirt',
At the start of each game, the program
will randomly pick the word that the 'otter', 'plane']
player has to guess and store it in a
secret_word = random.choice(words)
This variable uses the
random ​module’s
choice() ​function.

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('?????')

The five question marks are stored


as a list in the variable ​clue​.

I’ve stored all


the clues.
The last two question marks don’t represent any letters, so
they never disappear.

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.

['?', '?', '?', '?', '?']


Lives left:
9 Is​ the letter in the secret word?
If the guessed letter is in the secret
Guess a letter or the whole word: word, you must update the clue. To do
c ​['c', '?', '?', '?', '?']
this, you’ll use a function called
update_clue()​. The function has
Lives left: three parameters: the letter being
Guess a letter or the whole word: guessed, the secret word, and the clue.
Add this code after the
a ​['c', 'a', '?', '?', '?'] guessed_word_correctly
Lives left: variable.
Guess a letter or the whole word: ​r

▷ ​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.

10 ​The loop keeps


Guess a letter or word ​Your This
print(clue)
program should keep asking the
user to guess a letter or the whole ​index = index + 1
word until they either get the running while there are lives left.
correct answer or run out of lives. while lives > 0:
word: ')

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

This shows the clue and how many


lives the player has left.

If the guessed letter is in the secret


word, the clue is updated.

If the guess is incorrect


(​else​), the number of lives is reduced
by 1.

if guess == secret_word: When the word is guessed correctly,


this line breaks the loop.
guessed_word_correctly =
True break

if guess in secret_word:
update_clue(guess,
secret_word, clue) else:

print('Incorrect. You lose a


life') lives = lives - 1
letter or word from the player.
heart_symbol = u'\u2764'
*​
>>> print(heart_symbol ​ 10)

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)

print('You won! The secret word was ' +


Don’t forget to save your work.
secret_word) else:

print('You lost! The secret word was ' +


to start playing!
the word length, or
66 ​FIRST STEPS make it easier or
harder.
12
Test your code
Try the game to make sure it
Hacks
and
runs OK. If there’s a problem,
carefully check your code for b
bugs. When it’s working, invite
your friends to take the Nine iy
tweaks
Lives challenge!
r
u
I’d like to take it
for a test drive.
s
['?', '?', '?', '?', '?']
t
Lives left:
f ee
Guess a letter or the whole
word: a
There are lots of
ways you can remix
and adapt this
game. You can add
Just type a letter new words, change
s
h
i
r
t
▽ ​Add more words
Try adding more words to the program’s word list. You
h
can add as many as you want, but remember to only
use words that are five letters long.

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

difficulty = input('Choose difficulty (type 1, 2 or 3):\n 1 Easy\n 2 Normal\n 3 Hard\n')


difficulty = int(difficulty) difficulty ​is currently a string.
This line changes it to an
integer.
while lives > 0:

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.

3 I’ll try a harder

Now use ​if​, ​elif​, and ​else ​statements to set the


Set the levels number of lives for each level. Try using 12 lives for
NINE LIVES ​ 67 easy, 9 for normal, and 6 for hard. If you’re not happy
with how easy or hard the levels are, you can change
the number of lives after you’ve tested them out. Add
this code after the lines that asks the player to choose a
Choose difficulty (type 1, 2, or 3): level.
workout today!
1 Easy
2 Normal
difficulty = input('Choose difficulty (type 1, 2 or 3):\n 1 Easy\n 2 Normal\n 3 Hard\n')
difficulty = int(difficulty)

if difficulty == 1:
lives = 12
elif difficulty == 2:
lives = 9
else:
lives = 6

Words of varying length


What if you want to play a game you won’t know how long to make
with varying word lengths? If you the list to hold the clue. There’s a
don’t know the length of the secret clever fix you can use to solve this
word before the program is run, problem.
When you create the list that holds the clue, don’t
HIPPOPOTAMUS HIPPO
​ fill it with question marks—just leave the list empty.
Make this change to the ​clue ​list.
clue = []

There’s nothing inside


the brackets.

1
Use an empty list

68 ​FIRST STEPS
index = 0

2 while index < len(secret_word):

Add a new loop clue.append('?')


To make the clue the correct length once the index = index + 1
secret word has been selected, use this simple
loop. It counts how many letters are in the The ​append() f​ unction simply adds an item to the
word and adds a question mark for each letter. end of the list.

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.

Look, I guessed the


correct letter!

At first all the letters are unknown.

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

while index < len(secret_word):


if guessed_letter == secret_word[index]:
clue[index] = guessed_letter
unknown_letters = unknown_letters – 1
index = index + 1

return unknown_letters

This line makes the function return the


number of unknown letters.

Add this new parameter to the ​update_clue ​function.

NINE LIVES ​ 69
◁ ​How it works

I guess the word


is “assist”.
3
Calling the function
You’ll also need to change the
update_clue()​function to pass the
unknown_letters ​variable and store the new
_ss_st value.

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

unknown_letters = ​update_clue(guess, secret_word, clue​,


unknown_letters​) else:

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:

Winning the game guessed_word_correctly = True


When ​unknown_letters ​reaches 0, the user break
has guessed the word correctly. Add this code
the last letter!
The ​break ​statement exits the loop when
the player guesses the correct word.
This passes the
unknown_letters ​variable.

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.

Python Turtle Graphics


Customize
your robot
by altering
the size of the rectangles that make up its
body parts.

Can you give me


a hand?
How it You’ll start by writing a function that draws
rectangles. Then you’ll put the rectangles
works
together to build the robot. You can change The flowchart shows how the code for this project
the size and color of the rectangles by fits together. First the program sets the
background color and how fast the turtle moves.
altering the parameters you pass to the Then it draws the robot one part at a time,
function. So you can have long, thin blocks starting from its feet and moving up to its head.
for the legs, square ones for the eyes, and
so on.
Start

▽ ​Don’t call me turtle!


Be careful never to name any of your ​turtle
programs “turtle.py”. If you do that, Python will Set the background
get really confused and give you lots of error color and the turtle’s speed
messages​.

Draw the feet

I’m not a turtle! Don’t


call me that!
Draw the legs

Draw the body

Draw the arms

▽ ​Drawing with the turtle


The ​turtle ​module allows you to control a pen-carrying Draw the neck
robot turtle. By giving the turtle instructions on how it
should move around the screen, you can draw different
pictures and designs. You can also tell the turtle when
to put the pen down and start drawing, or when to pull Draw the head
it up so it can move to a different part of the screen
without leaving an untidy trail.

The turtle moves forward 100 Draw the eyes


pixels, turns left 90 degrees,
then moves forward 50 pixels.

Draw the mouth


t.forward(100)
t.left(90)
t.forward(50)
End
ROBOT BUILDER ​ 73
▽ ​Robot Builder flowchart

74 ​TURTLE GRAPHICS rectangles


Drawing
functions from the ​turtle ​module
without having to type “turtle” in
full each time. It’s like calling
someone whose name is
1 Close Benjamin “Ben” for short.

Let’s begin by importing Save import turtle as t


the ​turtle ​module and
Save As...
using it to create a function
that draws rectangles. Save Copy As...

Like all programming languages,


2 Python uses the US spelling “color”.
Create a new file ​Open IDLE and Import the Turtle module
create a new file. Save it as Type this line at the top of your
“robot_builder.py”. program. The command ​importThis gives the Turtle module the
turtle as t ​lets you use nickname “t”.
Now make the function to draw the
blocks that you’re going to use to build
your robot.

def rectangle(horizontal, vertical, color):

3 t.pendown()

Create a rectangle function


The function has three parameters: Put the turtle’s pen down to start
t.pensize(1) drawing.
the length of the horizontal side;
the length of the vertical side; and t.color(color)
color. You’ll use a loop that draws
t.begin_fill()
one horizontal side and one
vertical side each time it runs, and for counter in range(1, 3):
you’ll make it run twice. Put this t.forward(horizontal)
rectangle function under the code
t.right(90) Using ​range(1, 3)
you added in Step 2.
1

4
2

EXPERT TIPS
Turtle mode
This block draws the
rectangle.

The turtle draws the sides in


the order shown here.
t.penup()
makes the loop
run twice.

Pull the turtle’s pen back up


to stop drawing.

t.forward(vertical) t.right(90) t.end_fill()

This means the turtle starts off facing the


right
side of the screen. If you set the heading
You’ll be using the turtle in its standard (another
The turtle normally looks like an arrowhead. This line
mode.
changes it to a turtle shape.
90
makes it point to the bottom
word for direction) to 0, it will t.shape('turtle')
of the screen.
face right. Setting the
t.setheading(0)
heading to 90 makes it point 180 0 270
to the top of the screen, 180 t.forward(80)
points it to the left, and 270
Set the background
ROBOTBUILDE

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.

Make the background of the window “Dodger blue”.


start drawing the first foot, and then use your
rectangle function to draw it. You’ll need to do the
same for the second foot. Type these lines under
the code you added in Step 4, then run the
Now you’re ready to start building the program to see your robot’s feet appear.
robot. You’re going to make it piece by
piece, starting with the feet and working This comment indicates which
part of the robot you’re drawing.
your way up. The whole robot will be
made using rectangles of different sizes
and colors, each drawn from a different
starting point in the Turtle window.
I’m going to build such a cool robot!
EXPERT TIPS
Comments
You’ll notice that there are several

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)

rectangle(50, 20, 'blue') EXPERT TIPS


Move the turtle to position x = –100, y =
–150.
Turtle coordinates (–200, 200)

Python will adjust the Turtle g

window to fit your screen, but


Use the rectangle function to draw a let’s use an example that’s 400
blue rectangle 50 wide and 20 high.
pixels by 400 pixels. Python
lines in this program that start uses
with a # symbol. The words
following the # are a comment,
added to make the code easier
for users to read and (200, 200)
coordinate, shows how t

far to the left or right of g

r
y

coordinates to identify all the center the turtle is. e

the places in the window The second number, the g

where the turtle could y coordinate,


i

(0,0) ​
be. This means that
i

t
y=0 ​b

every place on the e


r

window can be found by g


y
e
l

using two numbers. The g


l

first number, the x n


m

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

The turtle moves to


position x = –25, y = –50.

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.

Draw the body


Type this code under the
code you added in Step 6.
Run the program and you
should see the body
appear.

t.goto(–25, –50) rectangle(15, 100, t.goto(–55, –50)


'grey')
rectangle(–15, 100,
'grey')
# body
t.goto(-90, 100)
rectangle(100, 150,
'red')

Draw the left leg.


Draw the right leg. Draw a red
rectangle 100 across and 150
down.
Draw the arms
Each arm is drawn in two parts:

ROBOT BUILDER ​ 77
8 #​ arms
t.goto(–150, 110)

rectangle(15, 40, 'grey')

first the upper arm, from the


t.goto(10, 70)
robot’s shoulder to its elbow; then
the lower arm, from the elbow rectangle(60, 15, 'grey')
to the wrist. Type this below the t.goto(55, 110)
code you added in Step 7, then
run it to see the arms appear. rectangle(15, 40, 'grey')
Upper right arm Lower right arm

Upper left arm


Lower left arm
t.goto(–150, 70)
rectangle(60, 15, 'grey')

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')

Draw the head


Oops—you’ve drawn a
headless robot! To give
your poor robot a head,
type these commands
below the code you added
in Step 9. Don’t forget to save your
work.

At last, we’ve built


t.goto(–50, 120)
rectangle(15, 20, 'grey')
the perfect robot! Err...
​ not quite.

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')

white part of the eyes.


Draw the
left pupil.

I’ve got eyes, but


I still keep walking
into things!!
Draw the mouth Draw the right pupil.
Now give the robot a
mouth. Type
these commands under the
code you added in Step
robots being built!

This makes the


turtle invisible.

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.

I love to watch these

You might also like