0% found this document useful (0 votes)
17 views

Python Projects

The document provides an overview of a coding book focused on teaching Python programming, highlighting its accessibility and relevance in today's digital world. It includes contributions from various experts in computing and outlines the structure of the book, which features practical projects and a foreword emphasizing the importance of coding skills. Additionally, it introduces Python as a popular programming language suitable for beginners and details the installation process for the software.

Uploaded by

myatkhant431
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Projects

The document provides an overview of a coding book focused on teaching Python programming, highlighting its accessibility and relevance in today's digital world. It includes contributions from various experts in computing and outlines the structure of the book, which features practical projects and a foreword emphasizing the importance of coding skills. Additionally, it introduces Python as a popular programming language suitable for beginners and details the installation process for the software.

Uploaded by

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

codin G

ProJecTs
PYTHON
®
R

IN
DK UK
Senior editors Ben Morgan, Steve Setford
Senior art editor Peter Radcliffe
US editors Jill Hamilton, Margaret Parrish
Consultant editor Craig Steele
Jacket design development manager Sophia MTT
Jacket editor Claire Gell
Producer, pre-production Robert Dunn, Nadine King
Producer Anna Vallarino
Managing editor Lisa Gillespie
Managing art editor Owen Peyton Jones
Publisher Andrew Macintyre
Associate publishing director Liz Wheeler
Art director Karen Self
Design director Phil Ormerod
Publishing director Jonathan Metcalf

DK INDIA
Project editor Suefa Lee
Art editor Sanjay Chauhan
Assistant editor Isha Sharma
Assistant art editors Yashashvi Choudhary,
Simar Dhamija, Sonakshi Singh
Jacket designer Juhi Sheth
Jackets editorial coordinator Priyanka Sharma
Managing jackets editor Sreshtha Bhattacharya
DTP designer Sachin Gupta
Senior DTP designer Harish Aggarwal
Senior managing editor Rohan Sinha
Deputy managing art editor Anjana Nair
Pre-production manager Balwant Singh

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 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 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 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
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 and has written or contributed to six other DK coding books.
Contents
8 FOREWORD

STARTING WITH PYTHON

12 What is coding?
14 Meet Python
16 Installing Python
18 Using IDLE TURTLE GRAPHICS

72 Robot Builder
FIRST STEPS 82 Kaleido-spiral
90 Starry Night
98 Mutant Rainbow
22 Your first program
24 Variables
28 Making decisions
32 Loopy loops PLAYFUL APPS
36 Animal Quiz
44 Functions
48 Fixing bugs 110 Countdown Calendar
52 Password Picker 120 Ask the Expert
58 Modules 130 Secret Messages
60 Nine Lives 142 Screen Pet
Let’sssss get
sssstarted!

GAMES IN PYTHON

158 Caterpillar
168 Snap
180 Matchmaker
190 Egg Catcher

REFERENCE

202 Project reference


220 Glossary
222 Index
224 Acknowledgments

Find out more at:


www.dk.com/computercoding
Foreword

We live in a digital world, and computers are part of almost everything we do. Not so
long ago, computers were bulky, noisy machines that lived mainly on desks, but now
they are tiny, silent devices hidden inside our phones, cars, TVs, and even watches.
We use them to work, play games, watch movies, go shopping, and keep in touch with
our friends and family.

Today’s computers are so simple to use that anyone can operate them. But not as
many people know how to write the code that makes them work. Becoming a coder
allows you to look under the hood and see how a computer really works. With a bit
of practice, you can build your own apps, write your own games, or just tinker with
other people’s programs and customize your own ingenious creations.

As well as being an addictive hobby, coding is a skill that’s in huge demand all over
the world. Learn how to code and it will set you in good stead wherever your life
leads, whether you’re interested in science, art, music, sport, or business.

Today, there are hundreds of coding languages you can learn, from simple, drag-and-
drop languages like ScratchTM to web-programming languages like JavaScript®. This
book is based on Python®, one of the world’s most widely used coding languages.
Equally popular with students and professionals, Python is easy to pick up yet powerful
and versatile. It’s a great language to learn whether you’re a beginner or moving up
from a simple language like Scratch.
The best way to learn to code is to get immersed, and that’s how this book is designed
to work. Just follow the numbered steps and you’ll be building apps, games, graphics,
and puzzles in no time. Learning to code is easier if you’re having fun, so we’ve tried
to make the projects as much fun as possible.

If you’re new to programming, start at the beginning and work your way through.
Don’t worry if you don’t understand every detail—it doesn’t matter. The more projects
you build, the better you’ll get. And don’t worry if your programs don’t work the first
time you run them. Even the pros have to debug their work.

Once you’ve finished building each project, there are tips on how to tweak and adapt
it. Feel free to try your own hacks. With a little bit of imagination and skill, there’s
no limit to what a coder can achieve.

Have fun coding!


Starting
with Python
12 S TA R T I N G W I T H PY T H O N

What is coding?
Computer programmers, or “coders,” are people
who write step-by-step instructions that can
make a computer perform a task. Coders can get
computers to do addition, make music, move a
robot across a room, or fly a rocket to Mars.

Dumb boxes △ Performing pet


A computer 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’s a
do. Because computers can’t think for themselves and can bit like having an electronic pet that
only do as they’re told, coders have to do the thinking for you can teach to perform tricks!
them and write their instructions carefully.

Programming languages
In order to tell a computer what to do, you need
to learn a programming language. Visual languages
are easy for beginners to learn, while professional
coders use text-based languages. This book is based Why don’t you say
on the popular text-based language Python. something?

▽ Scratch ▽ Python
Scratch is a visual programming language. Python is a text-based programming
It’s great for creating games, animations, and language. In Python, programmers write
interactive stories. You write code in Scratch code using words, abbreviations, numbers,
by snapping together blocks of instructions. and symbols. Instructions are typed in using
the computer’s keyboard.

when clicked Both these bits of code >>> 3 + 3


do the same thing.
think 3 + 3 6

The answer to the sum You hit the enter/return key


is shown on the screen to see the result.
in a “thinks” bubble.

6
W H AT I S C O D I N G ? 13
Anyone can code
To be a coder you just need to learn a few basic rules and
commands, and then you can start writing programs to
suit your skills and interests. If you’re into science, for
example, you could make an app that draws graphs from
the results of your experiments. Or you could use your art
skills to design an alien world for your own video game.

▽ Think logically ▽ Pay attention to detail


Coders need to think logically and carefully to write If you’re good at spot-the-difference puzzles, you’ll
good code. If the instructions aren’t quite right or the probably be a great coder. An important skill in
steps are in the wrong order, a program won’t work coding is spotting mistakes in your code. These
properly. Think through each step and make sure things mistakes are called bugs, and even tiny bugs can
happen in a logical order—after all, you wouldn’t put cause big problems. Eagle-eyed coders can pick out
your coat on before your sweater, would you! 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.
I knew you’d get
that wrong!

Keep those eyes


peeled!

LINGO
Bugs
Get coding
Bugs are errors in code that make Coding may sound daunting, but learning how
programs behave in unexpected ways.
to do it is easy. The secret is to just jump in. This
They are so-called because early
computers sometimes went wrong when book is designed to teach you how to code by
insects got stuck in their circuits! guiding you through simple projects. Just follow
the numbered steps and you’ll be creating
games, apps, and digital art in no time.

I’m on a
bug hunt!
14 S TA R T I N G W I T H PY T H O N

Meet Python LINGO


Python
Python is one of the most popular computer Python isn’t named after the type of
programming languages in the world. It was snake. It’s actually named after a
first released in the 1990s and is now used to British comedy group called “Monty
Python’s Flying Circus.” The creator of
build millions of apps, games, and websites. Python, Guido van Rossum, was a big
fan of the group and their quirky
humor. Python programmers often
Why Python? use the group’s jokes and famous
Python is a great language for getting started quotes in their code as a tribute.
with computer programming. Many schools
and universities use it to teach coding. Here
are some of the reasons that Python’s so useful.
▽ Batteries included
Programmers say Python has “batteries
included.” This is because it comes with
everything you need to start coding
It’s easy to read right away.
and write!

△ Easy to read and write


Python is a 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.
△ 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
△ Works everywhere Python has well-written
Python is portable. This means you can write and documentation. It has a
run Python code on lots of different computers. guide to getting started, a
The same Python code will work on PCs, Macs, reference section for looking
Linux machines, and Raspberry Pi computers. The up what things mean, and
programs behave the same way on each machine. a bunch of example code.
MEET PYTHON 15
Python in action EXPERT TIPS
Python isn’t just an educational tool. The interpreter
It’s such a powerful program it’s used
for many interesting and exciting tasks Some programming languages use an interpreter.
The interpreter is a program that can translate from
in business, medicine, science, and the
one programming language into another. Every time
media. It can even be used to control you run a Python program, the interpreter translates
the lights and heating in your home. each line of Python code into a special code that the
computer can understand, known as machine code.

▽ Crawling the web


Python is widely used on the Internet.
Parts of Google’s search engine are
written in Python. Much of YouTube I’m a mighty
powerful program! 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 Python-programmed robot
surgeon can work more quickly than a human one,
△ Serious business and be more accurate and less likely to make errors.
Python helps banks keep track of the money
in their accounts, and big store chains to set
the prices of the goods they sell.

Action!

We’ve been
expecting you!

△ In the movies
Disney uses Python to automate repetitive parts of
△ Out of this world the animation process. Rather than animators carrying
Software engineers used Python to create tools for out the same steps over and over, they use a Python
NASA’s Mission Control Center. These tools help the crew program to repeat the steps automatically. This saves
prepare for and monitor the progress of each mission. work, shortening the time it takes to make a film.
16 S TA R T I N G W I T H PY T H O N

Installing Python IDLE


LINGO

All the projects in this book use Python 3, so IDLE (short for Integrated
make sure you download the correct version Development Environment) is
from the website. Follow the instructions a free app that you get when
you install Python. Designed for
that match your computer. beginners, IDLE includes a basic
text editor that allows you to write
and edit Python code.
Python on Windows
Before you install Python 3 on a Windows PC, find out
if it uses the 32-bit or 64-bit version of windows. Click
“Start”, right-click “Computer”, and left-click “Properties”.
Then choose “System” if the option appears.

1 Go to the Python website


Type the address below into your web 2 Download Python
Click on the latest version of Python for Windows,
browser to go to the Python website. beginning with the number 3. The installer file will
Then click on “Downloads” to open the download automatically. Of the different installer
download page. options, select “executable installer”.

• https://www.python.org/ • Python 3.6.0a4 - 2016-08-15


• Windows x86 executable installer
• Windows x86-64 executable installer

3 Run the installer


Double-click the installer file to install Python. If you have a 32-bit If you have a 64-bit
Choose “install for all users” and click “next” at each version of Windows, version of Windows,
prompt, without changing the default settings. use this installer. use this installer.

Click the
installer.
4 Open IDLE
When the installation is finished, check that it was
successful by opening the IDLE program. Go to the
“Start” menu, choose “All Apps”, then select “IDLE”.
A window like the one below should open up.

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.
>>>
I N S TA L L I N G P Y T H O N 17
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.

1 Go to the Python website


Type the address below into your web browser 2 Download Python
From the downloads options, click on the
to go to the Python website. Then click on latest version of Python 3 that matches your
“Downloads” to open the download page. operating system. The Python.pkg file will
download to your Mac automatically.
https://www.python.org/

• Python 3.6.0a4 - 2016-08-15


• Download macOS X 64-bit/32-bit installer

3 Install Python
You’ll find the .pkg file in the “Downloads” folder. Its
The version number might not be
icon looks like an opened parcel. Double-click it to exactly the same as this one—just
start the installation. At the prompts, click “Continue” make sure you download the one
and then “Install” to accept the default settings. that has a 3 at the beginning.

Click the package


IMPORTANT!
to run the installer.
Ask permission
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
4 Open IDLE
When the intallation is finished, check that it was to provide an administration password
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
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 S TA R T I N G W I T H PY T H O N

Using IDLE You should come


out of your shell
more!
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.

The shell window ▽ Working in the shell


The code you type can be run straight away,
When you open IDLE, the shell window pops up.
and any messages or "bugs" (errors) are
This is the best place to get started in Python displayed. You can use the shell window like a
because you don’t have to create a new file first. notepad, to test out snippets of code before
Just type the code directly into the shell window. you add them into a bigger program.

This line Python 3.6.0a4 Shell


shows which
IDLE File Edit Shell Debug Window Help
version of
Python you Python 3.6.0a4 (v3.6.0a4:017cf260936b, Aug 15 2016, 13:38:16) The text here
have. will depend
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin on which
Type 'copyright', 'credits' or 'license()' for more information. operating
system you
You type >>>from turtle import * have.
in code at
the >>> >>>forward(200)
prompt. >>>left(90)
These four lines of code are
>>>forward(300) a simple drawing program;
try it out for yourself.
>>>

▽ Give the shell a test run


EXPERT TIPS Type each of these code snippets into the shell window
and press the enter/return key after each one. The first
Different windows line displays a message and the second line does a
calculation. Can you work out what the third line does?
To help you know which window you
should type your code in, we’ve given
>>> print('I am 10 years old')
each window in IDLE a different color.

>>> 123 + 456 * 7 / 8


Shell window
Editor window >>> ''.join(reversed('Time to code'))
USING IDLE 19
The editor window ▽ The editor window
The shell can’t save your code, so when you close the To open the editor window in IDLE,
shell window the code you typed is lost forever. That’s click on the File menu at the top
why you should use IDLE’s editor window when you and choose New File. An empty
editor window will then appear.
work on a project. This window lets you save your code. You’ll use the editor window to
It also has built-in tools to help you write your programs write and run programs for the
and to trouble-shoot any errors. projects in this book.

The name of the You can run your


You type the code in file is shown here. programs from The menu bar for
here. This program this menu. the editor window
prints a list that tells is different to the
you which numbers one for the shell.
are even and which EvensandOdds.py
ones are odd.
IDLE File Edit Format Run Window Help
for counter in range(10): I love idling!
if (counter % 2) == 0):
print(counter)
print('is even')
else:
print(counter)
Anything you tell print('is odd')
Python to print
gets displayed in
the shell window.

EXPERT TIPS
Colors in the code
IDLE automatically colors ◁ Symbols and names ◁ Keywords
the text to highlight Most code text is colored Certain words, such as
different parts of the code. black. “if” and “else”, are special
The colors make it easier to words that Python uses.
understand the code, and They are called keywords
they’re useful when you’re ◁ Output and are shown in orange.
trying to spot mistakes. Any text produced when
a program runs is blue.

◁ Text in quotes
◁ Built-in commands ◁ Errors Text in quote marks is
Python commands, Python uses red to green. A green bracket
such as “print”, are alert you to any errors around text shows you’re
shown in purple. in your code. missing a quote mark.
First
steps
22 FIRST STEPS

Your first program Hello Cedric!

Now that you’ve installed Python and IDLE, it’s


time to write your first program in Python.
Follow these steps to create a simple program
that greets the user with a cheery message.

How it works 1 Launch IDLE


A shell window appears when you start IDLE.
The program first displays the message “Hello, Ignore it and click on File in the IDLE menu.
World!” and then asks your name. Once you’ve Choose New File to create an empty editor
window where you can write your program.
typed in your name, it says hello again, but this
time it includes your name in the greeting. The
program uses something called a variable to New File
remember your name. A variable is used in Open
coding to store information.
Open Module

Recent Files
▷ Hello World flowchart
Programmers use diagrams Start Class Browser
called flowcharts to plan their
Path Browser
programs and to show how they
work. Each step is shown in a
box, with an arrow leading to
the next step. Sometimes the Say hello
steps are questions and have 2 Type the first line
In the editor window, type this line of text.
more than one arrow leading The word “print” is a Python instruction that
onward, depending on the tells the computer to display something on
answer to the question. Ask user to type the screen, such as the words “Hello, World!”
their name

print('Hello, World!')

Say hello, adding


user’s name
Hello, World!
3 Save your file
Before you can run the code, you must save
it. Go to the File menu and choose Save.

End Close

Save

Save As...
YO U R F I R S T P RO G R A M 23

4 Save the file


A pop-up box will appear. Type in a name for your
LINGO
program, such as “helloworld.py”, and click Save. .py files
Python programs usually have
Save As: helloworld.py
a name ending with “.py”,
Tags: which makes them easy to
Type the recognize. When you save a
Where: Documents name of program, Python automatically
your
program
adds “.py” at the end, so you
here. don’t need to type it in.
Cancel Save

5 Check it works
Now run the first line of the program
Python Shell >>>
to see if it works. Open the Run menu Check Module Hello, World!
and choose Run Module. You should
>>>
see the message “Hello, World!” in the Run Module
shell window.
The message will
appear in the shell.

6 Fix mistakes
If the code isn’t working, stay calm!
EXPERT TIPS
Every programmer makes mistakes, Keyboard shortcut
and finding these “bugs” is vital if you
want to become an expert at coding. A handy shortcut to run a program from
Go back and check your code for the editor window is simply to press F5 on
typing errors. Did you include the your keyboard. This is a lot quicker than
brackets? Did you spell the word selecting “Run” and then “Run Module”.
“print” correctly? Fix any mistakes,
then try running the code again.

7 Add more lines


Go back to the editor window and add two more lines to
print('Hello, World!')
your script. Now the middle line asks for your name and person = input('What’s your name?')
then stores it in a variable. The last line uses 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!
This line asks for the user’s name and
stores it in a variable called “person”.

8 Final task
Run the code again to check it. When you type in your Hello, World!
User’s
name and hit the enter/return key, the shell should show What's your name?Josh name
a personalized message. Congratulations on completing
Hello, Josh
your first Python program! You’ve taken your first steps
towards becoming a powerful programmer.
24 FIRST STEPS

Variables
If you want to write useful code, you’ll need to be able
to store and label pieces of information. That’s what
variables do. Variables are great for all sorts of things—
from tracking your score in a game to performing
calculations and holding lists of items.

How to create a variable △Storage box


A variable is like a box with a
A variable needs a name. Think of a name that will remind name label. You can store data
you what’s inside the variable. Then decide what you want in the box and then use the
to store in the variable. This is the variable’s value. Type name to find the data again
when you need to use it.
the name, followed by an equals sign, followed by the
value. We call this “assigning a value” to the variable.
This value will be stored in the variable.

1 Assign a value
In the shell window, type this line of code to
>>> age = 12

create the variable age and assign a value


to it. Use your own age if you want. This is the variable’s name.

2 Print the value


Now type the line of code shown on the right >>> print(age)
into the shell window. Hit the enter/return 12
key to see what happens.
The value of age The print() function prints the value
of the variable between the brackets.

EXPERT TIPS
Naming variables
Choosing good names for your variables Dos and don’ts
will make your program easier to • Start the variable’s name with a letter.
understand. For example, a variable • Any letter or number can be used in the name.
tracking a player’s lives in a game could • Symbols such as -, /, #, or @ aren’t allowed.
be called lives_remaining, rather
• Spaces can’t be used.
than just lives or lr. Variable names
can contain letters, numbers, and • An underscore ( _ ) can be used instead of a space.
underscores, but they should begin • Uppercase (capitals) and lowercase letters are different.
with a letter. Follow the rules shown Python will treat “Score” and “score” as two different variables.
here and you won’t go wrong. • Avoid words Python uses as commands, such as “print”.
VA R I A B L E S 25
LINGO
Integers and floats
In coding, whole numbers are called “integers”,
while numbers with a decimal point in them
are known as “floats”. Programs usually count
things using integers. Floats are more often
used for measurements. 0.5 sheep
1 sheep (an integer) (a float)

Using numbers Symbol Meaning


Variables can be used to store numbers and do sums. + add
You can use them with symbols to do calculations, – subtract
just like you do in maths. Some of these symbols will * multiply
be familiar, but watch out for the symbols meaning / divide
“multiply” and “divide”—they’re slightly different
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
Type this code in a shell window. It uses >>> x = 6
numbers stored in two variables, named x >>> y = x * 7
and y, to carry out a simple multiplication.
>>> print(y)
Hit the enter/return key to get the answer.
42

Print the Multiply x by 7 and


value of y. store the result in y.
The result of the calculation
Change the value of x.

2 Change a value
To change the value of a variable, you just >>> x = 10
assign a new value to it. In your code, change >>> print(y)
the value of x to 10 and run the calculation
42
again. What do you expect the result to be?

The result hasn’t changed;


next we’ll find out why. Update the value of y.

3 Update the value


The value of y needs to be updated to get the >>> x = 10
correct result. Type these lines. Now the code >>> y = x * 7
assigns the new value to y after x has been
>>> print(y)
changed. If you update the value of one
variable in your own programs, always check 70
to see if you need to update any others.
26 FIRST STEPS

Working with strings


Coders use the word “string” for any data
Y 0
made up of a sequence of letters or other P T H N
characters. Words and sentences are
stored as strings. Almost all programs use
strings at some point. Every character that A string is simply a
sequence of characters.
you can type on your keyboard, and even
those you can’t, can be stored in a string. The quote marks show that
the variable contains a string.

1 Strings in variables
Strings can be put into variables. Type this
>>> name = 'Ally Alien'

code into the shell window. It assigns the >>> print(name)


string 'Ally Alien' to the variable name Ally Alien
and then displays it. Strings must always have
quotation marks at the beginning and end.
Hit the enter/return
Remember the
key to print the string.
quote marks.

2 Combining strings
Variables become really useful when you
>>> name = 'Ally Alien'

combine them to make new variables. If you >>> greeting = 'Welcome to Earth, '
add two strings together, you can store the >>> message = greeting + name
combination in a new variable. Try this out.
>>> print(message)
Welcome to Earth, Ally Alien
EXPERT TIPS
Length of a string The + symbol
joins one string
The quote marks to another.
You can use a handy trick, len(), to aren’t shown when
count the number of characters in a string you print a string.
(including the spaces). The command
len() is an example of what coders call a
function. (You’ll use lots of functions in this
book.) To find out how many characters He doesn’t have
there are in 'Welcome to Earth, Ally a clue!
Alien', type the line below into the Take me to your
leader...
shell once you’ve created the string, then
hit enter/return.

>>> len(message)
28

The number of
characters counted
VA R I A B L E S 27
Lists
When you want to store a lot of data, or
perhaps the order of the data is important,
you may need to use a list. A list can hold
many items together and keep them in order.
Python gives each item a number that shows
its position in the list. You can change the
items in the list at any time.

1 Multiple variables
Imagine you’re writing a multiplayer game
>>> rockets_player_1 = 'Rory'
>>> rockets_player_2 = 'Rav'
and want to store the names of the players
in each team. You could create a variable for >>> rockets_player_3 = 'Rachel'
each player, which might look like this...
>>> planets_player_1 = 'Peter'
>>> planets_player_2 = 'Pablo'
With three players per team, >>> planets_player_3 = 'Polly'
you’d need six variables.

2 Put a list in a variable


...but what if there were six players per team?
>>> rockets_players = ['Rory', 'Rav',
Managing and updating so many variables 'Rachel', 'Renata', 'Ryan', 'Ruby']
would be difficult. It would be better to use a >>> planets_players = ['Peter', 'Pablo',
list. To create a list, you surround the items you
want to store with square brackets. Try out 'Polly', 'Penny', 'Paula', 'Patrick']
these lists in the shell.
This list is stored in the
variable planets_players.

The list items must be


separated by commas. This line gets the first item
in the list, from position 0.

3 Getting items from a list


Once your data is in a list, it’s easy to work with.
>>> rockets_players[0]

To get an item out of a list, first type the name 'Rory'


of the list. Then add the item’s position in the >>> planets_players[5]
list, putting it inside square brackets. Be careful:
Python starts counting list items from 0 rather 'Patrick'
than 1. Now try getting different players’ names
This line gets the last item
out of your team lists. The first player is at
in the list, from position 5.
position 0, while the last player is at position 5.

Hit enter/return to
retrieve the item.
28 FIRST STEPS

Making decisions Err...

Every day you make decisions about what to do Am I a


horse?
next, based on the answers to questions you ask
yourself. For example, “Is it raining?”, “Have I done
my homework?”, “Am I a horse?” Computers also
make decisions by asking questions.

Questions that compare


Are you sure you The questions that computers ask themselves usually
want to do that?
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.

▷ Boolean values Variable


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

EXPERT TIPS ▽ Logical operators


Equals signs These symbols tell computers to make
comparisons. Programmers call them
In Python, you can use a single equals sign, =, or a double logical operators. You may have used
some of them in math. The words “and”
equals sign, ==. They mean slightly different things. Use
and ”or” can also be used as logical
a single equals sign when you want to set the value of a
operators in computer code.
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, as in the example below. Symbol Meaning
== equal to
This sets the value of the variable. != not equal to
< less than
>>> age = 10 > greater than
This compares your
>>> if age == 10: age with the variable.

print('You are ten years old.')


I'm greater
than you!
The code 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.

>>> pineapples = 5 This variable stores the


number of pineapples.
>>> zebras = 2

This variable stores the number of zebras.

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

The number of pineapples is The number of pineapples and the


greater than the number of zebras. number of zebras aren’t equal.

>>> pineapples > zebras >>> pineapples == zebras


True False

LINGO ▽ Multiple comparisons


You can use and and or to combine more than one
Boolean expressions comparison. If you use and, both parts of the comparison
must be correct for the statement to be True. If you use
Statements about variables and values that use or, only one part needs to be correct.
the logical operators always give us a Boolean
value, such as True or False. Because of this,
these statements are called Boolean expressions. >>> (pineapples == 3) and (zebras == 2)
All of our statements about pineapples and False
zebras are Boolean expressions.
One part (pineapples == 3) is
Variable Logical operator incorrect, so the statement is False.

>>> pineapples != zebras


>>> (pineapples == 3) or (zebras == 2)
True
True

Boolean value Variable


One part is correct (zebras == 2),
so the statement is True.
30 FIRST STEPS

Ride the rollercoaster You can’t ride –


A sign at the theme park says you must be over 8 years you’re too small!
old and taller than 4 feet 7 inches to ride the
rollercoaster. Mia is 10 years old and 5 feet tall. Let’s use But I’m 100
years old!
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.

This is a Boolean
>>> age = 10 expression meaning
These two lines >>> height = 1.5 “older than 8 and more
assign values to than 4 ft 7 in tall”.
the variables. >>> (age > 8) and (height > 53 inches)
True
Mia can go on the
rollercoaster!

Branching
Computers often need to make decisions about
which parts of a program to run. This is because
most programs are designed to do different
things in different situations. The route through
the program splits like a path branching off into
side paths, each leading to a different place.

LINGO ▷ School or park?


Imagine you have to decide what route
Condition to walk each day based on the answer
to the question “Is today a weekday?” If
A condition is a Boolean
it’s a weekday, you take the route to
expression (a True-or- school; if it’s not, you take the route to
False comparison) that the park. In Python, the different routes
helps a computer decide through a program lead to different
which route to take blocks of code. A block can be one
when it reaches a branch statement or several, all indented by
in the code. four spaces. The computer uses a test
called a condition to figure out which
blocks it should run next.
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 is_dark = input('Is it dark outside? y/n)')
the computer takes if the condition is True.
This program asks the user to say if it’s if is_dark == 'y':
dark outside. If it is, the program pretends print('Goodnight! Zzzzzzzzzzzzzzz....') Condition
that the computer is going to sleep! If it’s
not dark, is_dark == 'y' is False, so the This branch is taken if The code shows this message
“Goodnight!” message isn’t displayed. the condition is True. in the shell window.

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

▷ Multiple branches
weather = input ('What is the forecast for today? (rain/snow/sun)')
When there are more than
two possible paths, the First condition This block runs if the
statement elif (short for if weather == 'rain': first condition is True.
“else-if”) comes in handy. This
program asks the user to type print('Remember your umbrella!')
in the weather forecast: either elif weather == 'snow':
“rain”, “snow”, or “sun”. It then Second
print('Remember your wooly gloves!')
chooses one of three branches condition
and weather conditions. else:
print('Remember your sunglasses!')

This block runs if the


This block runs if both second condition is True.
conditions are False.

△ How it works
An elif statement must always come after if and
before else. In this code, elif checks for snow only
when the condition set by the if statement is False.
You could insert additional elif statements to check
for more types of weather.

You might also like