100% (1) 100% found this document useful (1 vote) 390 views 112 pages Python Projects
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Python Projects For Later = 9 ° Ge
root.withdraw() 0 5 *# 1 @< / = @
0: < % OB x ( =] se HM YT
yas eelel ite
lw, oN
iu, a
) 8 nate ae:
i)
% < score=score+1 % x = 0 1 7 &
i
ae ee ae ee ee
A STEP-BY-STEP VISUAL GUIDEPenguin:
DIK) | Rancom
\ House
DKUK
Senior editors Sen Morgan, Steve Setford
Senior art editor Fetes Radcife
Consultant editor Craia steele
Jacket design development manager Sophia IT
Jacket editor Claire Gell
Producer, pre-production Raber
Producer Aina Valarinc
nn, Nadine King
‘Managing art editor Ovren
Pul
er Andrew Macinty
Design director Pil Ormerod
Publishing director Jonathan Metcal
DKINDIA
Project editor Suefs Le=
[art editor Sanjay Chauhan
Assistant editor Isha Sh
Assistant art editors Yashashvi Choudhary
‘mar Dhami, Sonakshi Singh
Jackat designer Juhi Sheth
Jackets editorial coordinator Prive"
Managing jackets editor Sreshih Bhattacharya
DTP designer Sachin Gupts
Senior DTP designer Harish Agar
Senior managing editor fihan Si!
Deputy managing art editor Anjana Nai
Pre-production manager Saiwant Sing
Fist published in Great Briain a2
by Dorling Kindersley
80 Strand, London WC2R ORL
yg toting Kindersley Limited
’A Penguin Random House Company
2468109753
99420 hune/2017
Aight eserved
No part ofthis publication may be reproduced, stored
aretieval sytem, or tansmited in any orm or by any means, electron
nechanieal, photocopying, ecarding or otheraise, without the pri
‘witen permission ofthe copyright owner
ACIP catalogue record for this book
from the Bish Libra
0-2412-86869
AWORLD OF IDEAS:
SEE ALL THERE IS TO KNOW
vn dk.com
‘m4
2
mts
~6
m8] my
CAROL VORDERMAN MBE is one of Britain's best-loved TV presenters and
is renowned for her mathematical skills. She has hosted numerous TV shows
on science and technology, from Tomorrow's World to How 2, and was co-host
of Channel 4's Countdown for 26 years. A Cambridge University engineering
graduate, she has a passion for communicating science and technology
and has a keen interest in co
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 2X Spectrum.
DR CLAIRE QUIGLEY studied Computing Science at Glasgow University,
where she obtained a BSc 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 McCAFFERTY holds a degree in Computer Science from the University
of Strathclyde, He has worked as a software engineer for companies big and
small in industries from banking to broadcasting. Daniel lives in Glasgow with
his wife and daughter and when not teaching young people to code, he enjoys
cycling 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‘ bestselling Computer Coding
Games for Kids and has written or contributed to six other DK coding books.60
FOREWORD
“© STARTING WITH PYTHON
What is coding?
Meet Python
Installing Python
Using IDLE
« FIRST STEPS
Your first program
Variables
Making decisions
Loopy loops
Animal Quiz
Functions
Fixing bugs
Password Picker
Modules
Nine Lives
— 7
Os
TURTLE GRAPHICS
Robot Builder
Kaleido-spiral
Starry Night
Mutant Rainbow
PLAYFUL APPS
Countdown Calendar
Ask the Expert
Secret Messages
Screen Pet
GAMES IN PYTHON
Caterpillar
Snap
Matchmaker
Egg Catcher
REFERENCE
Project reference
Glossary
Index
Acknowledgments
Find out more at:
www.dk.com/computercoding
a
=e
nn
p
i
|
eee
Lotssss get
sssstarted!
cae = |
aWe 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 films, 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 so
many people know how to write the code that makes them work. Becoming a coder
allows you to look under the bonnet 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™ 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 of moving up
from a simple language like Scratch.
The best way to learn to code is to get stuck in, 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.
CAROL VORDERMA\
Have fun coding!Starting
| with Python
: ad
| | | i=STARTING 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 sums, make music, move
a robot across a room, or fly a rocket to Mars.
A Performing pet
‘Acomputer can't do anything of its own accord ~ it just By learning how to code, you'll be able
to write your own programs and make
sits there like a dumb box until it's told exactly what to the computer do what you want. It’ a
do. Because computers can't think for themselves and can _bitlike having an electronic pet that
only doas they're told, coders have to do the thinking for you can teach to perform tricks!
them and write their instructions carefully.
Dumb boxes
Programming languages
In order to tell a computer what to do, you need
toleam a programming language. Visual languages am
are easy for beginners to learn, while professional a F, ,
coders use text-based languages. This book is based | a |
on the popular text-based language Python. something?
V Scratch V Python
Scratch is a visual programming language. Python is a text-based programming
It's great for creating games, animations, and language. In Python, programmers write
interactive stories. You write code in Scratch code using words, abbreviations, numbers,
by snapping together blocks of instructions. and symbols. Instructions are typed in using
the computer's keyboard.
when AM clicked
Both these bits of code p> 343
do the same thing, 4
The answer to the sum XN You hit the enter/return key
Is shown in the screen to see the result
ina"thinks’ bubble,
WHAT IS CODING?
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 on
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.
Y Pay attention to detail
IFyou'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
Y 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 trousers on before your pants, would you!
= a to improve your coding powers,
Vine yo gt
” - —
‘exromeace3 : bt
Keep those eyes
pected! .
—
LINGO
Bugs 7
9 Get coding
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!
Coding may sound daunting, but learning how
to do it is easy. The secret is to get stuck 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.
ve
2,
ity
e . fo, a Y
*
Wu SS
TES ap
¥TARTING WITH PYTHON
Meet Python
Why Python?
Python is a great language for getting started
with computer programming. Many schools
and universities use it to teach coding. Here
are some of the reasons that Python's so useful.
It easy to read
and write!
A) Easy to read and write
Python isa text-based computer programming
language. You write the instructions using a
mixture of English words, punctuation characters,
symbols, and numbers. This makes Python code
simple to read, write, and understand,
ee
4 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 machines, and Raspberry Pi computers. The
programs behave the same way on each machine.
Python is one of the most popular computer
programming languages in the world. It was
first released in the 1990s and is now used to
build millions of apps, games, and websites.
oe LINGO
Why Python?
Python isn't named after the type of
snake, It's actually named after a
British comedy group called “Monty
Python's Flying Circus” The creator of,
Python, Guido van Rossum, was a big
fan of the group and their quirky
humour. Python programmers often
use the group's jokes and famous
quotes in their code as a tribute.
V Batteries included
Programmers say Python has "batt.
included”. This is because it comes
everything you need to get coding
straight away.
J Handy tools
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.
> Great support
Python has well-written
documentation. It has a
guide to getting started, a
reference section for looking
up what things mean, and
a bunch of example code.
Python in aci
Python isn’t just an educational tool.
It’s such a powerful program it’s used
for many interesting and exciting tasks
in business, medicine, science, and the
media. It can even be used to control
the lights and heating in your home.
V Crawling the web
Python is widely used on the Internet.
Parts of Google's search engine are
written in Python. Much of YouTube
is also built using Python code. .
Python? Isa serious
business! ae)
Fe
A Serious business
Python helps banks to keep track of the
money in their accounts, and big store chains
to set the prices of the goods they sell
We've been
expecting you!
A Out of this world
Software engineers used Python to create tools for
NASA's Mission Control Centre, These tools help the crew
Prepare for and monitor the progress of each mission.
Pmamighty
powerful program!
EXPERT TIPS —
Some programming languages use an interpreter.
The interpreter is a program that can translate from
one programming language into another. Every time
you run a Python program, the interpreter translates
each line of Python code into a special code that the
computer can understand, known as machine code.
‘Don't worry, this won't
hurt — much!
A Medical marvels
Python can be used to program robots to perform
tticky operations. A Python-programmed robot
surgeon can work more quickly than a human one,
and be more accurate and less likely to make errors,
Action!
4 Inthe 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.16 STARTING WITH PYTHON
Installing Python
All the projects in this book use Python 3, so
make sure you download the correct version
from the website. Follow the instructions
that match your computer.
Python on Windows
Before you install Python 3 ona Windows PC, find out
IDLE (short for Integrated
Development Environment) is
a free app that you get when
you install Python. Designed for
beginners, IDLE includes a basic
text editor that allows you to write
and edit Python code.
Python ona 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.
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.
INSTALLING PYTHON
§ Download Python
From the downloads options, click on the
latest version of Python 3 that matches your
operating system. The Python.pkg file will
if it uses the 32-bit or 64-bit version of windows. Click
start’, right-click "Computer", and left-click “Properties”
Then choose’System’ if the option appears.
Download Python
fH Click on the latest version of Python for Windows,
beginning with the number 3. The installer file will
download autornatically. Of the different installer
options, select “executable installer
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/ + Python 3.6.0a4- 2016-08-15 |
_> + Windows x86 executable installer
Te + Windows x86-64 executable installer |
h
Bi Run the installer /
Double-click the installer file to install Python. |ityounave a 32-bit —ityouhave a 64-bit
version of Windows,
Choose “install for all users" and click“next” at each
use this installer,
prompt, without changing the default settings.
version of Windows,
se this installer.
lickthe Open IDLE
installer. When the installation is finished, check that it was
successful by opening the IDLE program. Go to the
"Start" menu, choose “All Apps’, then select “IDLE”
A window like the one below should open up.
Python 3.6.0a4 Shell
dit Shell. Debug Window Help
[IDLE File
python 3.6.0a4 (v3.6.0a4:017cf260936, Aug 15 2016, 00:4:
0) [MSC v.1900 32
bit (ntel)] on win32
Type "copyright", “credits” or “License()" for more information
__ download to your Mac automatically.
https://www.python.org/
+ Python 3.6.0a4 - 2016-08-15
Download macOS x 64-bit/32-bit installer
{
XX The version number might not be
‘exactly the same as this one just
make sure you download the one
that hasa 3 at the beginning.
Install Python
You'll find the .pkg file in the “Downloads’ folder, Its
icon looks like an opened parcel. Double-click it to
start the installation. At the prompts, click “Continue”
and then “Install” to accept the default settings.
Click the package to
run the installer
<<
Never install Python or any other
program unless you have permission
to do so from the computer's owner.
You may also need to ask the owner
to provide an administration password
Open IDLE
4, When the intallation is finished, check that it was
during installation.
successful by opening the IDLE program. Open the
"Applications" folder, and then the “Python folder.
Double-click “IDLE” and a window like this should appear.
Python 3.6.0a4 Shell
IDLE file Edit Shell Debug Window Help. mee
Python 3.6.0a4 (v3.6.0a4:017¢f260936b, 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.i f - a 8
L * i .
i: STARTING WITH PYTHON
do
Using IDLE
IDLE has two different windows in which you can
work. The editor window can be used to write
and save programs, while the shell window runs
| Python instructions immediately. , ne
The shell window V Wer M aaeuttaves
f . code you type can be run straight away,
When you open IDLE, the shell window pops up. ned an reostages orbugs" errors) are
} This is the best place to get started in Python, as displayed. You can use the shell window like a
you don’t have to create a new file first. You just notepad, to test out snippets of code before
type the code directly into the shell window. you add them into a bigger program.
Youshould come
out of your shell,
more!
Thisline Python 3.6.0a4 Shell m |
showswhich IDE File Edit Shell Debug Window Help |
version of
Prthonyeu | python 3.6.0a4 (v3.6.094:017¢f260936b, Aug 15 2016, 13:38:16) igure
ave, will dey
{GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin onwhich
erat
Type "copyright", “credits” or “LicenseQ” for more information. | soe
Youtype | ->>>from turtle import * | have
incode at
hee >>>forward (200)
promt verlete G0) These four lines of code are
>>>forward (300) a simple drawing program
= try it out for yourself.
'V Give the shell a test run
‘Type each of these code snippets into the shell window
and press the enter/return key after each one. The first
line displays a message and the second line does a
calculation, Can you work out what the third line does?
oTTh EXPERT TIPS
To help you know which window you
should type your code in, we've given
| each window in IDLE a different colour.
>>> print('I am 10 years old")
>> +456*7/8
Shell window ee
Editor window
>>> 1 join (reversed (‘Time to code'))
The editor window
The shell can't save your code, so when you close the
shell window the code you typed is lost forever. 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.
Thenane oft
You type the code in file is shown here.
here. This program
sncansaee LO
veiw,
eT
ee
IDLE
File Edit Format Run Window
for counter in range(10) :
] if (counter % 2) == 0):
| print (counter)
print (‘is even‘)
| else:
| print (counter)
| print (‘is odd")
Anything you tell
Python to print
gets displayed in
the shell window.
>
Check Module Hello, orlal
Run Module
The message will
% appear in the shell
© EXPERT TIPS
Keyboard shortcut
Ahandy shortcut to run a program from
the editor window is simply to press F5 on
your keyboard. This is a lot quicker than
af selecting “Run’ and then “Run Module’.
2
ih
Da
print (‘Hello, World!")
person = input (‘What's your name?")
print (‘Hello,", person)
to print a new greeting. You can change it to a different
greeting if you prefer — as polite or as rude as you like!
Final task
Run the code again to check it, When you type in your
name and hit the enter/return key, the shell should show
a personalized message. Congratulations on completing
‘This line asks for the user's name and
stores it in a variable called "person’
Hello, World!
User's
What's your name?Josh meee
Hello, Josh
your first Python program! You've taken your first steps
towards becoming a powerful programmer.Variables
If you want to write useful code, you'll need to be able
to store and label pieces of information. That's what
variables do. Variables are great for all sorts of thi
from tracking your score in a game to performing
calculations and holding lists of items.
ble A Storage box
AA variable is like a box with a
name label. You can store data
in the box and then use the
name to find the data again
when you need to use it.
How to create a va
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 in the variable. This is the variable’ value. Type
the name, followed by an equals sign, followed by the
value. We call this “assigning a value” to the variable.
oT ‘This value will be stored in the variable.
>>> age = 12
\ichtneett name
Assign a value
In the shell window, type this line of code to
create the variable age and assign a value
to it. Use your own age if you want.
| Print the value
: | Now type the line of code shown on the right >>> print (age)
into the shell window. Hit the enter/return 2
key to see what happens. 4 Xe
The value of age The print © function prints the value
of the variable between the brackets
a EXPERT TIPS
Dos and don'ts
+ Start the variable’s name with a letter.
Choosing good names for your variables
will make your program easier to
understand, For example, a variable
tracking a player’ 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.
+ Any letter or number can be used in the name. |
+ Symbols such as -, /, #, or @ aren't allowed,
+ Spaces can't be used.
+ An underscore (_) can be used instead of a space.
« Uppercase (capitals) and lowercase letters are different.
Python will treat “Score” and “score” as two different variables.
+ Avoid words Python uses as commands, such as “print’
In coding, whole numbers are called integers,
while numbers with a decimal point in them
are known as floats. Programs usually count
= ee 7
wv.
a
VARIABLES
things using integers. Floats are more often onan
used for measurements. QS \ 0.5 sheep
1 sheep (an integer) {a float)
Using numbers Symbol Maaning
Variables can be used to store numbers and do sums. + [ada
You can use them with symbols to do calculations, =f subtract
just like you do in maths. Some of these symbols will =| rtply
be familiar, but watch out for the symbols meaning 7 divide
“multiply” and "divide" - they're slightly different from X
the ones you use in class.
A simple calculation
Type this code in a shell window. It uses
numbers stored in two variables, named x
and y, to carry outa simple multiplication
Hit the enter/return key to get the answer.
The result of the calculation value of y,
Change a value
To change the value of a variable, you just
assign a new value to it. In your code, change
the value of x to 10 and run the calculation,
again. What do you expect the result to be?
I Update the value
Ba ‘The value of y needs to be updated to get the
correct result. Type these lines. Now the code
assigns the new value to y after x has been
changed. If you update the value of one
variable in your own programs, always check
10 see if you need to update any others.
\ A. some ofthe Python maths symbols
Create a new variable, x, and give it the value 6.
7
v
p> x= 6
poo yex+7<
>>> print)
a
y\
~ Print the
\ Muttiply x by 7 and
store the result in y.
_ Change the value of x
>>> x = 10
>>> print (y)
42
\ The result hasn't changed ~
next welll find out why, Update the value of y
p> x = 10
pry exe7
>>> print (y)
70Working with strings
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. Almost all programs use
strings at some point. Every character that
you can type on your keyboard, and even
those you can't, can be stored in a string.
4 Strings in variables
Strings can be put into variables. Type this.
code into the shell window. It assigns the
string ‘Ally Alien’ to the variable name
and then displays it. Strings must always have
quotation marks at the beginning and end.
a Combining strings
Variables become really useful when you
combine them to make new variables. If you
add two strings together, you can store the
combination in a new variable. Try this out.
EXPERT TIPS
You can use a handy trick, len, to
| count the number of characters in a string
(including the spaces). The command
| Ten isan 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 ‘Welcome toEarth, Ally
ALien’, type the line below into the
shell once you've created the string, then
hit enter/return.
>>> Len (message)
28
a
\
~ The number of
characters counted
ne — _l
mer
Astring is simply a
sequence of characters,
The quote marks show that
_- the variable contains a string.
/
>>> mame = "Ally Alien’
>>> print (name)
Ally Alien
A
— Hit the enter/return Remember the
Keyto print thesting, quotes
>>> name = ‘Ally Alien" \
>>> greeting = ‘Welcome to Earth, *
>>> message = greeting + name
>>> print (message) \
\
Welcome to Earth, Ally Alien
A
\ The + symbol
joins one string
‘The quote marks to another.
aren't shown when
you printa string.
Take meto your
leader.
Lists
When you want to store a lot of data, or
perhaps the order of the data is important,
you may need to use alist. 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.
Multiple variables
Imagine you're writing a multiplayer game
and want to store the names of the players
in each team. You could create a variable for
each player, which might look like this...
With three players per team,
you'd need six variables.
By Put a list ina variable
but what if there were six players per team?
Managing and updating so many variables
would be difficult. t 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.
By Getting items from a list
Once your data is in a list, it's easy to work with.
To get an item out ofa lst, first type the name
of the list. Then add the item's position in the
list, putting it inside square brackets. Be careful:
Python starts counting list items 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 player is at position 5.
7
me
>>> rockets player_l = ‘Rory’
=
Ex
>>> rockets_player_3 = ‘Rachel’
>>> rockets_player_2 = ‘Rav’
planets_player_1 = ‘Peter’
planets_player_2 = ‘Pablo’
>>> planets_player_3 = ‘Polly’
>>> rockets_players = ['Rory’, ‘Rav’,
"Rachel", ‘Renata’, ‘Ryan', 'Ruby"]
>>> planets_players = ['Peter', ‘Pablo’,
‘Polly’, ‘Penny’, ‘Paula’, 'Patrick']
Kw
\
J 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" ty
A \
\ °SN this line gets the last item
\ in the list, from position 5.
~ Hit enter/return to
retrieve the item,Making decisions =
Questions that compare
The questions that computers ask themselves usually
involve comparing one thing with another. For example,
a computer might ask if one number is bigger than
another. If it is, the computer might then decide to
run a block of code that would otherwise be skipped.
Every day you make decisions about what to do
next, based on the answers to questions you ask
yourself. For example, “Is it raining?”, “Have I done
my homework?" “Am | a horse?” Computers also
make decisions by asking questions.
a ,
Are you sue you
want todo that?
D> Boolean values ~ Variable
The answers to the questions computers ask a
EEE, 216 only two possible values: True or False.
Python calls these two values Boolean values,
>>> answer_one = True
>>> answer_to = False
and they must always start with a capital letter. x
You can store a Boolean value in a variable.
Boolean value 7
V Logical operators
These symbols tell computers to make
comparisons. Programmers call them
logical operators. You may have used
some of them in maths. The words
“and” and “or” can also be used as
logical operators in computer code.
In Python you can use a single equals sign or a double equals
sign. They mean slightly different things. Use a single equals
ign when 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 when you want to compare two
| values, asin the example below. Symbol Meaning
equalto
This sets the value of the variable. not equal tO
Za E —|testtan |
o>> age = 10 ——_this compares your 5 greater than
10: age with the variable.
greater
than you!
>>> if age
print (‘You are ten years old. *)
The code prints the message if the two match.
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.
This varlable stores the
>>> pineapples = 5
number of pineapples.
>>> zebras = 2
rK
— This variable stores the number of zebras.
V D> Make comparisons
Now try typing the following lines of code to compare
the values of the two variables. After you've typed 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.
oO
>>> pineapples > zebras
True
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.
Variable — i
Vv
Logical operator
>>> pineapples != zebras
True
4“
N Boolean value XN Variable
a
MAKING DECISIONS
>>> zebras < pineapples
True ae
Stecnamieribontonss ig
than the number of pineapples.
The number of pineapples and the
number of zebras aren't equal.
>>> pineapples == zebras
False
V Multiple comparisons
You can use and and or to 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
False
None part (pineapples == 3)is
Incorrect, so the statement is False.
>>> (pineapples == 3) or (zebras == 2)
True
One partiscorrect (zebras == 2),
So the statements Tve,Ride the rollercoaster
Assign at the theme park says you must be over 8 years
old and taller than 1.4 metres to ride the rollercoaster.
Mia is 10 years old and 1.5 metres tall. Let’s use the
shell to check whether she can go for a ride. Type the
following lines of code to create variables for Mia’s age
and height and assign the correct values to them. Type
the rules for going on the rollercoaster as a Boolean
expression, then hit the enter/return key.
>>> age = 10
[>>> height = 1.5
These two lines /
assign values to
the variables, >>> (age > 8) and (height > 1.4) <
True
A
Mia can go on the
rollercoaster!
You cant ride
you'etoo small!
But im 100
yeas old!
This isa Boolean
// expression meaning
“older than 8 and more
than 1.4 metres tal”
Branching
Computers often need to make decisions about
which parts of a program to run. This is because
most programs are designed to do different
things in different situations. The route through
the program splits like a path branching off into
| side paths, each leading to a different place.
D> School or park?
Imagine you have to decide what route
‘to walk each day based on the answer
to the question "ls today a weekday?" If
it’s a weekday, you take the route to
school if it's not, you take the route to
the park. In Python, the different routes
through a program lead to different
blocks of code. A block can be one
statement or several, all indented by
four spaces. The computer uses a test
called a condition to figure out which
blocks it should run next,
A condition is a Boolean
expression (a True-or-
False comparison) that
helps a computer decide
which route to take
when it reaches a branch
in the code.
D> One branch Thi
The simplest branching command is an 1f
statement. It only has one branch, which
the computer takes if the condition is True.
This program asks the user to say if it's
dark outside. If itis, the program pretends
that the computer is going to sleep! If it's
not dark, is_dark == 'y' is False, so the
"Goodnight!" message isn't displayed.
[> Two branches
Do you want a program to do one thing if
a condition’s True and another thing ifit’s
False? If so, you need a command with two
branches, called an if-else statement.
This program asks if the user has tentacles.
If they answer"Yes’, it decides they must
be an octopus! if they answer No’, it
decides they're human. Each decision
prints a different message.
> Multiple branches
When there are more than
two possible paths, the
statement ei f (short for
“else-if") comes in handy. This
weather =
if weather
program asks the user to type print (
in the weather forecast: either elif weath
“rain’, ‘snow’, or’sun’ It then
chooses one of three branches Beet
and weather conditions. else:
print¢
cond
This block runs if both —
a
MAKING DECISIONS
is line asks the user to reply"“y" (yes) or *n” (no),
is dark = input('Is it dark outside? y/n)")
if is_dark
y :
print (‘Goodnight! Zzzzzzzzzzzzzzz....')
A A
Condition
This branch is taken if
the condition is True,
— The code shows this message
in the shell window.
This line asks for input from the user. —_ Condition
Ni /
tentacles = input (‘Do you have tentacles? (n/y)') /
ey
if tentacles = 'y
print (‘I never knew octopuses could type!')
else: /
{ print (Greetings, human!")
A
this block runs ifthe
condition is False.
\ this block runs ifthe
condition isTrve.
‘input (What is the forecast for today? (rain/snow/sun)")
First condition This block runs if the
train': first condition is True.
"Remember your umbrella!') <
jer == ‘snow < Si
"Remember your woolly gloves!') < ~ Second
condition
"Remember your sunglasses!)
| This block runs ifthe
second condition is True,
tions are False.
A How it works
An e1 if statement must always come after 1 and
before e1se. In this code, e1if checks for snow only
when the condition set by the 4 f statement is False.
You could insert additional e11f statements 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 Out!!! ten times.
Try out her code for yourself in the shell. (After typing
the code and hitting enter/return, press backspace to
remove the indent and then hit enter/return again.)
Keep Ott
Keep Out! “"
veep Out
Emma's Root
Emma Room —
Emma's ROOT
Emma's Room ~
Thisis the loop The loop runs 10 times
7 variable. (
v
>>> for counter in range(1, 11)
print (‘Emma\'s Room - Keep Out!!!")
K K
—
\ thetine that gets peated
Indent the commands
is called the loop body.
in the body 4 spaces,
V Loop variable
‘The loop variable keeps track of how many times we've gone
round 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
| Inython code, the word"range” |
round it’s equal to the second number in the list, and so on. | followed by two numbers within
When we've used all the numbers in the list, we stop looping. | brackets stands for“all the
numbers from the first number to
First loop Satopiiloop: Third loop 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) isthe numbers
| 1,2,3,4,5,6,7,8,9, and 10, |
Loop variable = 3 LW
Loop variable = 1 Loop variable = 2
va a* EXPERT TIPS
Ss EXPER TALLEST
Escape character (\)
ter (
| The backslash in Emma\ 's Room tells Python 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
escape character. It tells Python not to count the next character
when working out if the line makes sense or contains errors.
While loops
What happens if you don’t know how many times
you want to repeat the code? Do you need a
crystal ball or some other way of seeing into the
future? No, it’s okay! You can use a whi Le loop.
lean see the future,
and it’s completely
loopy!
[> Loop condition
Ahi Le loop doesn’t have a loop variable that's set to a
range of values. Instead it has a loop condition. This is a
Boolean 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 wor't let you in. In programming,
ifthe loop condition isn't True, you won't get into the loop!
Youcantcomein- ff
your loop condition
isnttruel
V Balancing act
In this example, Ahmed has written a program to keep track
of how many of his troupe of acrobatic hippopotamuses
have balanced on top of each other to make a tower. Read
through the code and see if you can figure out how it works.
_— This variable stores the
ruber ofhppos
This variable stores b
the answer to the
, Loop condition
>>> hippos = 0
question “Add This line displays a message
another hippo?" >>> answer = 'y showing the total number
Y y of balancing hippos.
>>> while answer 2 Fe Pose NO Ahmed's reply
f / becomes the new
Z pos = hippos + 1 t value of answer.
fo print (str(hippos) + * balancing hippos!')
Add another / answer = input('Add another hippo? (y/n)') <___—
hippo to the
number balanced,= o
7
FIRST STEPS
[> How it works
The loop condition in Ahmed'’s program is
answer == 'y". This means that the user
wants to adda hippo. In the body of the
loop we add one to the number of hippos
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 round the loop again. If they answer"n”
(no), the loop condition is False and the
program leaves the loop.
Infinite loops
Sometimes you may want a while
loop to keep going for as long as the
program is running. This kind of loop
is called an infinite loop. Lots of
video-game programs use an infinite
loop known as a main loop.
Fah EXPERT TIPS
If you don’t want an infinite loop, it's
important to make sure that the body
of a whi Le loop does something that
could make the loop condition False.
But don't worry - if you accidentally
code an infinite loop, you can escape
from it by 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.
Hmm...maybe
‘Madd just one
‘more hippo?
vt
There isn False option
L to escape the loop.
>>> while True:
print (‘This is an infinite loop!')
A Inte infinity
You make an infinite loop by setting the loop condition toa
constant value: True. Because this value never changes, the
loop will never exit. Try this whi Le loop in the shell. It has no.
False option, so the loop will print “This is an infinite loop!”
nonstop until you quit the program.
Y 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'te rude and uses the
break command to leave the loop!
The True condition is that the
(Gain
>>> while True:
answer =
if answer
print (‘How rude!
input ("Are you bored yet? (y/n)')
yt: con
) _\TheFalse condition
('y') triggers the
break break command,
Loops inside loops
Can the body of a loop have another loop
within it? Yes! This is called a 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.
ike Russian dos —
but they'ealvaysso full
of themselves!
SB ae a
The loop variable ofthe outer
loop ishooray_counter. —
~\
de another }
[> One loop
In this example, Emma has
changed her “keep Out" program
into a"Three Cheers" program
that prints “Hip, Hip, Hooray!”
three times. Because each cheer
includes the word "Hip" twice,
she uses a nested loop to print
oT EXPERT TIPS
SyntaxError
for hip_counter in range(1,
print (Hip') <—
print (‘Hooray!")
The loop variable of the inner
loop is hip_counter.
Hip —
hooray_counter=1__ | ip hip_countey
—_
a
L Hooray!
Hip <<
Hip aa
hip_counter=2
hooray_counter = 2
Hooray!
hooray counter =3
Hooray!
Hip ——
itp —~ hip_counte
hip_counter =2
\ hip_counter=2
™~ hip_counter =1
5 a
LOOPY LOOPS
The code in the body of a loop should be 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 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 line is
indented by the correct number of spaces.
x] unexpected indent
>>> for hooray counter in range(l, 4):
The body of
D2) Stree
— loop is indented
4 spaces,
‘The body of the inner loop is
indented another 4 spaces.
<1 How it works
The whole of the inner for loop
is inside the body of the outer
for loop. Each time we do one
repeat of the outer loop, we
have to do two repeats of the
inner loop. This means the body
of the outer loop is run three
times in total, but the body of
the inner loop is run six times.Animal Quiz
Are you a fan of quizzes? Fancy making one yourself? Sad
In 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.
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.
- —— -
Python 3.5.2 Shell Le
This is how the game
looks - itall happens
in the shell window.
Guess the Animal!
Which bear lives at the North Pole? polar bear
Correct answer
Which is the fastest land animal? cheetah
Type in your
Correct answer neater
Which is the largest animal? giratte
jou guess incorrectly,
ry, wrong answer. Try again. elephant X____ lf youguess Cl
ee od = you get another go.
Sorry, wrong answer. Try again. rhinoceros
Wiel dae After three wrong guesses,
the program shows you the
correct answer.
The correct answer is blue whale
Your score is 2
This is your score out of.
a possible 3 points.
How it works
This project makes use of a function - a
block of code with a name that performs
a specific task. A function lets you use the
same code repeatedly, without having to
type it all in every time. Python has lots
of built-in functions, but it also lets you
create functions of your own.
[> Calling functions
When you want to use a
function, you “call it” by typing
its name in your code. In
Animal Quiz, you'll make a
function that compares the
player's quess to the true
answer to see if it's correct.
Youll call it for each question
in the quiz.
eh UINGo
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 that the words are the same.
| This isn’t true for all programs. For example, if
a program that checks passwords ignores case,
| the passwords might become easier to guess,
and less secure. However, in Animal Quiz, it
doesn't matter if the player answers "bear”
or “Bear” - both will be recognized as correct.
V Animal Quiz flowchart
The program keeps checking whether there are any
questions left to ask and whether the player has used
up all of their chances. The score is stored in a variable
during the game. Once all the questions have been
answered, the game ends.ey
Bp ga
ens
FIRST STEPS
=
noe
ANIMAL QUIZ
Putting it together
It’s now time to build your quiz! First you'll create
the questions and the mechanism for checking the
answers. Then you'll add the code that gives the
player three attempts to answer each question.
Create a new file
Open IDLE. Under the File menu,
select New File. Save the file as
“animal_quiz.py’.
Create the score variable
Type in the code shown here to
create a variable called score
and set its starting value to 0.
Introduce the game
Next create a message to introduce
the game to the player. This will be
tthe first thing that the player sees,
on the screen.
Run the code
Now try running the code. From
the Run menu, choose Run Module.
What happens next? You should
see the welcome message in the
shell window.
Ask a question (user input)
The next line of code asks a
question and waits for the player's
response. The answer (the user
input) is saved in the variable
guess1.Run the code to make
sure the question appears.
{hope tm not
‘venomous ~ I've ust
bitten my tonguet
File
ieee
players scofs, ‘This phrase will appear
in the shell window.
print (‘Guess the Animal!)
Run
Python Shell
Check Module
print (‘Guess the Animal!")
guessl = input (‘Which bear Lives at the North Pole? ') |
XS The variable guess1
stores whatever the
user types in,
=
* |
Build a check function
The next taskis to check f the player’s
‘guess is correct. Type this code at the
top of your script, before score =0.
‘The code creates a function, called
check_guess (), that will checkif
the player's guess matches the correct
answer. The two words in brackets
are parameters’ - bits of information
the function needs. When you call
a function, you assign (give) values
to its parameters.
Wa 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.
By Test the code
Try running the code again and
type in the correct answer. The
shell window should look like thi
9 ‘Add some more questions
It takes more than one question to make a quiz!
‘Add two more questions to the program, following
The first line gives
<< the function a name
global score and parameters.
if guess ae
print (‘Correct answer") Eee
a global variable,
Itensures that
def check_guess (guess, answer)
score = score +1
enor changes to the
variable can be
‘Add 1 to the Don't forget seen throughout
player's score. the brackets. the whole program.
guess1 = input('Which bear lives at the North Pole? ")
check_guess (guess1, ‘polar beat
NO Correct answer
Guess the Animal!
Which bear lives at the North Pole? polar bear
Correct answer
Letme add
some more.
the same steps as before. We'll store the player's
answersin the variables guess2 and guess3.
score = 0
print(‘Guess the Animal!')
guess1 = input("Which bear lives at the North Pole? ')
check_guess(guess1, ‘polar bear’) <_—=——— ~~ tocheck guess.
guess2 = input(‘Hhich is the fastest land animal? *)
check_guess (guess2, 'cheetah')
guess3 = input (‘Which is the Large:
-check_guess(guess3, ‘blue whale")
st animal? ')
Soke
First question
‘This tells the program
This tells the program
to check guess3.. i
RST STEPS
Display the score
The next line of code will reveal the player's score
in a message when the quiz ends. Add it to the
bottom of the file, under the last question
ANIMAL
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.
= input (‘Which is tl
blue whale’)
+ str(score))
A Howit works
For this step, you have to use the str () function
to change a number into a string. This is because
Python shows an error if you try to add a string
and an integer (whole number) together.
n
print (Your score is *
Ignore case
What happens if the player types
‘Lion’ instead of “Iion"? 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.
Test the code again
Run your code for a third time. Try typing the
correct answers using a mixture of capitals and
lower-case letters and see what happens.
Guess the animal!
Which bear lives at the North Pole? polar bea
Correct answer
Wich is the fastest land animal? Cheetah
Correct answer
Which is the largest animal? BLUE WHALE
Correct answer
Your score is 3
def
e largest animal? ')
the player's scor
iton the screen,
heck_gi
__This creates a message giving
re and displays
or
s (guess, answer)
global score
if guess. Lower ()
print(
score
\ change this
answer .lower Q :
Correct answer’)
= score +1
se A How it works
Both the guess and the answer
will be converted into lower-case
characters before being checked.
This ensures that the code works
whether the player uses all
capital letters, all lower-case
letters, or a mixture of the two.
___ The case is ignored when deciding
whether an answer is correct or not.
def check_guess(guess, answer)
global score
5 Awhile loop runs the check
still_guessing = True <— code three times or until the
atte a0 player gets the answer correct,
whichever comes first.
while still_guessing and attempt < 3:
if guess.lower() == answer. lower Q: > Make sure each line of
nerWetcoreeca secre code has the correct indent
score = score + 1
ride nue ie Rese The else variable asks the
ae e _— player to enter another answer
eT sere i eee ifthey get it wrong,
if attempt <2
guess = input (‘Sorry wrong answer. Try again. ')
Deca eeree eal eater tae __- Add 1 to the number of
guesses the player has had.
if attempt
print (‘The correct answer is ' + answer)
\ this code alisplays the correct
score = 0 answer after three wrong guesses.
4. How it works
To know if the player has got the
right answer, you need to create a
variable called sti11_guessing.
You then 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.
Don't forget to save
This variable will hold one of only
your work.
, two values: True or False
Largest animal?
| don't know.
Giveme three guesses!a
FIRST STEPS
Display the score
bottom of the file, under the last question.
guess3 = input('Wnich is the largest anima
check guess (guess3, ‘blue whale’)
print (‘Your score is ' + str(score))
A. How it works —_
For this step, you have to use the str Q function
to change a number into a string. This is because
Python shows an error if you try to add a string
and an integer (whole number) together.
1 Ignore case
What happens if the player types
‘Lion’ instead of “lion”? Will they stil
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 hasa 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.
2) Test the code again
Run your code for a third time. Try typing the
lower-case letters and see what happens.
Guess the animal!
Which bear lives at the North Pole? polar
Correct answer
Which is the fastest Land animal? Cheetah
Correct answer
Which is the largest animal? BLUE WHALE
Correct answer
Your score is 3
The next line of code will reveal the player’s score
in a message when the quiz ends. Add itto the
correct answers using a mixture of capitals and
_ This creates a message giving
the player's score and displays
iton the screen.
or
def check_guess(guess. answer)
global score
if guess.lower() == answer. lower 0
7 print(‘Correct answer’)
{score
Both the guess and the answer
will be converted into lower-case
characters before being checked.
This ensures that the code works
whether the player uses all
capital letters, all lower-case
letters, or a mixture of the two.
bear
——_____ The case is ignored when deciding
whether an answer is correct of not,
ANIMAL Qu
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.
This variable will hold one of only Don't forget to save
two values: True or False. your work.
def check_guess(guess, answer)
global score
— Awhi Le loop runs the check
code three times or until the
player gets the answer correct ~
whichever comes first.
still_guessing = True <—
attempt = 0
while still_guessing and attempt <
if guess.lower() == answer. lower (: Make sure each ine of
print (‘Correct answer’) code has the correct indent.
score = score +1
_ The else variable asks the
still_guessing = False
player to enter another answer
else:
es
if attempt < 2:
guess = input('Sorry wrong answer. Try again. *)
attempt = attempt + 1
if attempt == 3
print('The correct answer is ' + answer)
\
\___ This code displays the correct
score = 0 ~~ answer after three wrong guesses.
A How it works
To know if the player has got the
right answer, you need to create a a,
variable called st 111_guess ing. Largest animal?
You then set the variable to True Idon'thnow.
to show that the right answer hasn't yeme thre qusses!
been found. It’s set to False when the ",
player gets the right answer.a
FIRST STEPS
| 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
Hl file so that you don’t mess up the original game.
7
fl Make a true-or-false quiz
This code shows how to create
true-or-false questions, which
have only two possible answers.
> Change the difficulty
To make the quiz harder, give the
player fewer chances to get the right
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 ifi’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?
it would be.
ean!
| Notas easy asl thought
> Choose another topic
Create a quiz on a different subject, such as
general knowledge, sports, movies, or musi
You could even make a quiz about your family
or friends and include some cheeky questions,
like “Who has the most annoying laugh?”
answer . lower ()
5 a
ANIMAL QUIZ
<1 Better score for fewer attempts.
Reward the player for getting the answer right with
Fewer guesses. Give 3 points if they get it in one go,
2 points for needing two attempts, and 1 point for
using all three chances. Make this change to the line
that updates the score. Now it will give 3 points minus
the number of unsuccessful attempts. If the player
gets the answer right first time, 3 - 0 = 3 points are
replaces added to their score; on the second guess, its 3 - 1=2
score + 1. points; and on the third guess, it’s 3- 2=1 point.
guess = input (‘Mice are mammals. True or False? ')
check_guess (guess, 'True")
def check_guess (guess, answer)
global score
still_guessing = True
oo this number,
while still_guessing and attempt < 3:
attempt = 0
if guess.lower() == answer. 1ower():
print(‘Correct Answer’)
score = score +1
still_guessing = False
ali
if attenpt < elena
guess = input (‘Sorry wrong answer.Try again. ')
Change this number.
attempt = attempt +1
Sola ape
print(’The correct answer is ' + answer)
Change this number.
if attempt =oe
FIRST STEPS
Functions
Programmers love shortcuts that make writing
code easier. One of the most common shortcuts
is to give a name to a block of code that does an
especially useful job. Then, instead of having to
type out the whole block each time you need it,
you simply type its name. These named blocks
of code are called functions.
There are a number of special
words that coders use when
talking about functions,
Call To use a function.
Define When you use the def
keyword and write the code
for a function, coders say you
“define” the function. You also
define a variable when you first,
set its value.
How to use a function
Using a function is also known as “calling" it. To call a
function, you just type the function's name, followed
by a set of brackets that contain any parameters you
want the function to work with. Parameters are a bit like
variables that belong to the function, and they allow you
to pass data between different parts of your program.
When a function doesn't need any parameters, the
brackets are left empty.
Parameter A piece of data
(information) that you give
toa function to use.
Return value Data that you
pass from a function back
to the main code. You get it
using the keyword return.
Built-in functions Pe eae ile
Python has a number of built-in C
functions that you can use in your code. >>> name = input (‘What is your name?*)
These are helpful tools that let you do
lots of tasks, from inputting information
and showing messages on the screen to
converting one type of data into another.
You've already used some of Python's
built-in functions, such as print Q and
input (). Have a look at these examples.
Why not try them out in the shell?
What is your name? Sara
>>> greeting = ‘Hello’ + nane
>>> print (greeting)
wetto sara
‘This shows the content of the
variable greet ing on the screen,
A input Q and print 0
“These two functions are like opposites. The input () function
lets the user give instructions or data to the program by typing
them in.The print Q function sends output to the user by
displaying messages or results on the screen.
V maxQ
The max © function selects the maximum value from
the parameters you give it. Hit the enter/return key to
see the value on the screen. This function takes multiple
parameters, which must be separated by commas.
>>> max(10, 16, 30, 21, 25, 28)
30 t
hk
\\ the maximum
values the
highest number
in the brackets.
\ Always separate multiple
parameters with commas.
V minO
‘The function min () does the opposite of max). It
selects the minimum value from the parameters you
put inside its brackets. Experiment for yourself with
the max and min) functions.
>>> min(A0, 16, 30, 21, 25, 28)
10
\ when you hit the enter/return key, the
code shows you the lowest number.
Another way of calling
Some of the different types of data we've
come across so far, such as integers, strings,
and lists, have their own functions. These
functions must be called in a special way.
You type the data or the name of the
variable holding the data, followed by a dot,
the function's name, and finally brackets.
Test out these code snippets in the shell.
ie
‘The function has two parameters.
\
>>> message = "Python makes me happy’ /
>>> message. replace (‘happy", °:D'
S
happy with =D.
"Python makes me
A replaced
Two parameters are needed for this function: the first is
the part of a string you want to replace, while the second
isthe string you want to put nits place. The function
returns a new string withthe replacements made.
Don't forget Empty brackets mean
the dot. that no parameters:
\ are needed
>>> ‘bang’ :upper ()
“BANG’
\
A upper Q
The upper () function takes an existing string and
returns a new string in which all the lower-case
characters are changed to upper-case (capitals)
This is the new string, all in capitals.
The list of numbers
_— stored in the variable
v
>>> countdown = [1, 2, 3]
>>> countdown.reverse() The list isnow
>>> print (countdown) aie
(ayien alice ee
A reverse()
Use this function when you want to reverse the order of
the items in a list. Here, its used to reverse a list of numbers
stored in the variable countdown. Instead of printing the
list as [1, 2, 3], the function makes it print [3, 2, 1]
"a
FUNCTIONSRST STEPS
Making a function
The best functions have a clear purpose
and a good name that explains what
they do - think of the check_guess()_ =
function you used in Animal Quiz.
Follow these instructions to create, or es
Define the function
Create a new file in IDLE. Save it as"functions.py”
Type these lines into the editor window. An indent is
added at the start of each line in the function. Save
the file again, then run the code to see what happens.
The name of There are no
the function — parameters yet
‘define’, a function that calculates the y fo
number of seconds in a day and then ERR ao.
prints the answer on the screen. fee
minutes = hours + 60
“Ti Ceara det eile Fythion that! seconds = minutes + 60 \ Variables
this block of code is a function,
print (seconds) <— aw
This line prints
the value of the
variable seconds.
‘The lines after the name must be
Indented 4 spaces, to show Python that,
print_seconds_per_day 0
they are part of the function.
86400
K
This command calls the function. /
\ x the numberof secondsin day appears inthe shel
Add parameters
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
It's important to define
your functions before
Jet print_seconds_per_ day (days) :<—
you use them in your
hours = days * 24 <~ The function's
main code. When you're Bee ea ces ay parameter
learning to code with fe This ine uses the
Python, it’s helpful to put seconds = minutes * 60 parameter days,
your functions at the top
of your file, after any
import statements. By
doing this, you won't
make the mistake of
trying to call a function
before you've defined it.
print(seconds)
—~ Gives a value (7) to
the parameter days
print_seconds_per_day(7)
Ne Existing lines of code
are shown in grey and
new lines of cade in bold,
604800
‘
\ tne nuber seconds in? ds
Return a value
Once you have a function that does something
useful, you'll want to use the results from that
function in the rest of your code. You can get
values out of a function by “returning” them,
Change your code as shown here to get the
return value from your function. You should
rename the function to match its new purpose.
Don't try to run the code just yet.
a Store and use the return value
You can store the return value from a function
ina variable to use later in your code. Add this
code under your function. it stores the return
value and uses it to calculate the number of
milliseconds (thousandths of a second). Try it
out and experiment with the number of days.
The return value is stored in the yn
variable total_seconds,
So
THis Ine prints the value
of milliseconds.
i
‘This is the number of
milliseconds in 7 days.
"EXPERT TIPS
In Step 3, you changed the name of your
function from print_seconds_per_day() to
convert_days_to_seconds (). Just like with
variables, it’s important that the name you use
accurately explains what the function does. This
makes your code much easier to understand.
a
FUNCTIONS
def convert_days_to_seconds (days) :
hours = days * 24
minutes = hours * 60
i i — The function's
seconds = minutes * 60 Renae
return seconds
»
The keyword return gives the D NN The line that called the function
value of the variable seconds.
is deleted, as the function now
has anew name and purpose.
This calls the function and gives a
value (7) to the parameter days.
def convert_days_to_seconds (days)
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
return seconds |
y
total_seconds = convert_days_to_seconds (7)
milliseconds = total_seconds » 1000
print (milliseconds)
604800000
‘The total number of seconds /
is converted into
milliseconds and stored in
the variable mi 11 i seconds,
The rules for naming functions are similar to
those for variables. Function names can contain
letters, numbers, and underscores, but they
should begin with a letter. If there are several
words in the name, the words should be
separated by underscores.