Help Your Kids With Computer Coding - 2nd Edition - DK
Help Your Kids With Computer Coding - 2nd Edition - DK
DK INDIA
Senior editor Suefa Lee
Senior art editor Devika Dwarkadas
Project editor Tina Jindal
Project art editor Sanjay Chauhan
Editor Neha Pande
Art editors Rabia Ahmad, Simar Dhamija, Sonakshi Singh, Shreya Anand Virmani
Assistant art editor Vanya Mittal
Jacket designers Priyanka Bansal, Suhita Dharamjit
Jackets editorial coordinator Priyanka Sharma
Managing jackets editor Saloni Singh
DTP designers Jaypal Singh Chauhan, Sachin Gupta, Rakesh Kumar
Senior DTP designer Harish Aggarwal
Managing editor Rohan Sinha
Managing art editor Sudakshina Basu
Pre-production manager Balwant Singh
This American Edition, 2019
First American Edition, 2014
Published in the United States by DK Publishing
1450 Broadway, Suite 801, New York, NY 10018
Copyright © 2014, 2019 Dorling Kindersley Limited
DK, a Division of Penguin Random House LLC
19 20 21 22 23 10 9 8 7 6 5 4 3 2 1
001–308107–Aug/2019
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-7732-3
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,
1450 Broadway, Suite 801, New York, NY 10018
[email protected]
Printed and bound in China
A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW
www.dk.com
CAROL VORDERMAN, MA(CANTAB), 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 is
particularly interested in coding.
DR. JON WOODCOCK, MA(OXON) has a degree in Physics from the University of
Oxford and a PhD in Computational Astrophysics from the University of London.
He started coding at the age of 8 and has programmed all kinds of computers, from
single-chip microcontrollers to world-class supercomputers. His many projects
include giant space simulations, research in high-tech companies, and intelligent
robots made from junk. Jon has a passion for science and technology education,
giving talks on space and running computer programming clubs in schools. He has
worked on numerous science and technology books as a contributor and consultant.
Just a few years ago, computer coding seemed like a mysterious skill that
could only be practiced by specialists. To many people, the idea that coding
could be fun was a strange one. But then the world changed. In the space
of a few years, the internet, email, social networks, smartphones, and
apps hit us like a tornado, transforming the way we live.
Computers are a huge part of life that we all now take for granted. Instead
of calling someone on the phone, we send a text message or use social
media. From shopping and entertainment to news and games, we guzzle
everything computers have to offer. But we can do more than just use
this technology, we can create it. If we can learn to code, we can make our
own digital masterpieces.
Not only that, coding is a fantastic skill for life. It strengthens logical thinking
and problem-solving skills—vital in many different areas of life, from science
and engineering to medicine and law. The number of jobs that require coding
is set to increase dramatically in the future, and there’s already a shortage of
good coders. Learn to code, and the digital world is yours for the taking!
CAROL VORDERMAN
10
and understand. 11
This function calculates
the distance between two
objects. Add this bit of
from m
def di
code directly after the x1
code you wrote in step 9.
x2
Each topic is re
described in detail, “See also” boxes list
with examples other subjects that are
and exercises linked to the topic
Pop the bubbles
The player scores points by poppin
and fast bubbles are worth more po
42 S TA R T I N G F R O M S C R AT C H code works out when each bubble
radius (the distance from the cente
e between points 13
Now update the main game loop to use the
functions you have just created. Remember that Each line of
s useful to know the distance the order is important, so make sure you put
o use a well-known mathematical everything in the right place. Then run the code. code is clearly
k it out. Bubbles should burst when they hit the sub.
Check the shell window to see the score.
labeled so
Loads the “sqrt” function
from the Math library. you can’t
Gets the position of Sets the score to zero
math import sqrt the first object. when the game starts. go wrong
istance(id1, id2): Gets the position of score = 0
1, y1 = get_coords(id1) the second object.
#MAIN GAME LOOP
2, y2 = get_coords(id2)
while True:
eturn sqrt((x2 - x1)**2 + (y2 - y1)**2)
if randint(1, BUB_CHANCE) == 1: Creates new bubbles.
Gives back the distance create_bubble()
between them.
move_bubbles()
clean_up_bubs() Adds the bubble
score to the total.
score += collision()
ng bubbles. Big bubbles print(score)
oints. The next section of Shows the score in the shell
window.update() window—it will be displayed
is popped
H I D E by
A Nusing
D S Eits
EK 43 sleep(0.01) properly later.
er to the edge). ▷ Collision sensing
e of effect If the distance between This pauses the action for
rop-down
sh into each other, the the center
Change the of the sub and a very short time—try
“pixelate”
update the score. This numbers in the
the center of a bubble is less than their removing this and see
the sprite blocks to set what happens.
the code in step 11. radiuses added together, they have collided.
me blurred how strong
the effect is
s This loop goes through the entire list of bubbles (it EXPERT TIPS
red. goes backwards to avoid errors when deleting bubbles).
pixelate effect by 25 Python shortcut Don’t forget to
save your work This icon
The code “score += collision()” indicates that
Checks for collisions is a shortcut for writing
lor
1, -1, -1):
effect to 0
between the sub “score = score + collision()”. It adds the project
and any bubbles. the collision score to the total
_id[bub]) < (SHIP_R + bub_r[bub]):
Each color is
represented by a score, then updates the total score.
continues on
raphic effects
+ bub_speed[bub]) number. Change Code like this is common, so a the next page
the number to shortcut is useful. You can also do
ng graphic effects set the color
the same thing using the “–”
hic effects in Scratch can be symbol. For example, “score –= 10”
change a sprite’s appearance is the same as “score = score – 10”.
tthe
itsbubble.
shape. They’re fun toCalculates the number of
points this bubble is worth
ent with. and adds it to “points”.
ators” block
andom
When to save
This block
position selects a random
vertical position
Read on and
This save icon appears
get coding! on the project spreads. It
ck random -150 to 150
reminds you when to save
This block makes the the work you’ve done,
ghost move slowly,
hidden from view so that nothing is lost if
the computer crashes.
Always remember to save
Don’t forget to
your work frequently. save your work
What is
coding?
14 W H AT I S C O M P U T E R C O D I N G ?
◁ Games
Consoles are just another type of
computer, and all the games that
run on them are programs. All the
graphics, sounds, and controls
are written in computer code.
▷ Cars
In some cars, computer
programs monitor the
speed, temperature,
△ Washing machines and amount of fuel in
Washing machines are programmed the tank. Computer
to follow different cycles. Computer programs can even
code controls how hot the water is help control the brakes
and how long the wash takes. to keep people safe.
W H AT I S A C O M P U T E R P R O G R A M ? 15
How computer programs work
Computers might seem very smart, but they are actually just
boxes that follow instructions very quickly and accurately. As
intelligent humans, we can get them to carry out different tasks
by writing programs, or lists of instructions.
LINGO
Hardware and software
“Hardware” means the physical
parts of the computer that you
can see or touch (all the wires, the
‹ 14–15 What is a
computer program?
A programmer must learn to think like a computer. All
tasks must be broken down into small chunks so that
Becoming 18–19
a coder
›
they are easy to follow and impossible to get wrong.
Real-world example
The waiter robot might be imaginary, but algorithms like
this are in action all around us. For example, a computer-
controlled elevator faces the same sort of problems.
Should it go up or down? Which floor should it go to next?
Programming languages
There are a huge range of programming languages to choose
from. Each one can be used for different tasks. Here are some of
the most popular languages and what they are often used for:
What is Scratch? SCRATCH File Edit Tutorials Untitled Share See Project Page scratch-cat
Events
side of the screen
of code, instead of typing it out.
go to random position
Control go to x: 0 y: 0
glide 1 secs to x: 0 y: 0
when clicked
programming languages.
Show Size 100 Direction 90
forever
next costume
Backdrops
play sound bubbles until done
1
Sprite1 Sprite2
Backpack
A program written
in Python
Getting started
It’s time to start programming. All you need
is a computer with an internet connection.
This book starts with Scratch—the perfect
language to help you on your way to
becoming a coding expert. Get ready to jump
into the exciting world of computer coding.
EXPERT TIPS
Enjoy experimenting
As a programmer, you should
experiment with the code and
programs you make. One of the
best ways to learn programming
is to play around and see what
happens when you change
different parts of the code. By
tinkering and fiddling, you’ll
discover new ways of doing
things. You’ll learn much more
about computer programming
and have even more fun.
Starting
from Scratch
22 S TA R T I N G F R O M S C R AT C H
Understanding Scratch
Scratch is perfect for making games and animations.
It has large collections (or “libraries”) of cool graphics Blocks lock
together like
and sounds that you can play around with. jigsaw pieces
LINGO
Why is it called Scratch?
“Scratching” is a way of mixing
different sounds to make new
music. The Scratch programming
language enables you to mix
Make sprites move and speak pictures, sounds, and code blocks
3 Objects such as people, vehicles, Sprites like me can be
programmed to talk
to make new computer programs.
and animals can be added to a program. in speech bubbles.
These objects are called sprites. Code
blocks make them move and speak.
Sprites can be
programmed
to walk, run,
and dance
W H AT I S S C R AT C H ? 23
A typical Scratch program
Here is an example of a Scratch program. All of the action takes ▷ Running a program
place in an area on the screen called the “stage.” Background Starting a program is called
“running” it. To run a
images and sprites can be added to the stage, and you can
program in Scratch, click the
write code (sometimes called scripts) to make things happen. green flag above the stage.
Background image
▷ Getting started
The way Scratch is
set up depends on
whether it’s used over
the internet (online)
or from downloaded
software (offline).
When you’re logged in, Scratch The web version of Scratch 3.0 works
automatically saves work for you. To find well on Windows, Ubuntu, and Mac
your work, click your username at the top operating systems. This version will Ready?
right of the screen and click “My Stuff.” also work on tablets. Let’s go!
Click the “File” menu at the top of The offline version of Scratch works well on
the screen and choose “Save to your computers with Windows and Mac operating
computer.” Ask the person who owns systems. It doesn’t work well on computers
the computer where you should save that use Ubuntu. If a computer uses Ubuntu,
your work. try the online version instead.
26 S TA R T I N G F R O M S C R AT C H
Scratch interface
This is Scratch’s screen layout, or
“interface.” The stage is on the right and Change
language
Menu
options
Costumes
tab
programs are created in the middle.
B A C K PA C K S TA G E I N F O
Sound turn 15 degrees
Select different
△ Scratch map types of blocks
The stage is where programs run. Events go to random position
Sprites are managed in the sprite
list and code blocks can be found Control go to x: 0 y: 0
in the blocks palette. Build code in
the code area. glide 1 secs to random position
Sensing
glide 1 secs to x: 0 y: 0
Operators
EXPERT TIPS
point in direction 90
Menu options Variables
▽ Experiment
Click the buttons and tabs to explore
and experiment with the Scratch
Program interface. The projects that follow
name box explain how to use them.
Current sprite
selected Click for full
screen view
when clicked
forever
go to mouse-pointer
Click a sprite on the
move 10 steps stage or in the sprites
list to select it
forever
next costume
Stage
Sprite Owl x 20 y 80
Zoom in on Backdrops
code blocks
1
Owl Cat Turtle
‹ 26–27 Scratch
interface
Sprites are the basic components of Scratch. Every Scratch
program is made up of sprites and the code that controls
Costumes 40–41 ›
them. The “Escape the dragon!” program on pages 32–37
Hide and seek 42–43 ›
uses the cat, dragon, and donut sprites.
Motion
Motion
move 10 steps when clicked
forever
Looks
turn 15 degrees
Select different types go to mouse-pointer
move 10 steps
turn 15 degrees
of blocks by clicking
Sound
glide 1 secs to x: 0 y: 0
Operators
point in direction 90
Variables
Stage
point towards mouse-pointer Sprite Sprite1 x 0 y 0
My Blocks Select different
▷ Sprites and code sprites by clicking Show Size 100 Direction 90
Sprite Sprite3 x 20 y 80
Type the
sprite’s new Show Size 100 Direction 90
name here
Spike The sprite’s new
name appears in
Sprite1 Sprite2 Sprite3 the sprites list
30 S TA R T I N G F R O M S C R AT C H
‹ 26–27 Scratch
and code
interface
Escape the 32–37
dragon!
›
Blocks are color coded depending on what they do.
Putting them together builds code that runs in the
order in which they are placed.
This block
Control go to x: 0 y: 0 rotates the
turn 15 degrees sprite
glide 1 secs to random position
Sensing This block
glide 1 secs to x: 0 y: 0 think Hmm... for 2 seconds shows a
thought
Operators bubble
Flow of code
When a program runs, Scratch carries out the
instructions on the blocks. It starts at the top
of the code and works its way down.
wait 2 seconds
PROJECT 1
Click the blue “Motion” button in the blocks Click the “Events” button in the blocks palette.
3 palette. The blue “Motion” commands will 4 Drag the “when green flag clicked” block into
appear. Drag the “point towards” block the code area. Join it to the top of your code.
into the code area and drop it inside the This block snaps to
“forever” block. the top of the code
Click the “Motion” button again, and drag the The picture behind the sprites is called a backdrop.
6 “move 10 steps” block into the code area. Drop 7 To the right of the sprites list is a button to add a
it inside the “forever” block. Click the green flag backdrop from the library. Click it, select the “Space”
button so the cat chases the mouse-pointer! theme from the list, and then click the “Stars” image
to select this backdrop.
when clicked
forever
SCRATCH File Edit Tutorials Untitled Share See Project Page scratch-cat
◁ Cat in space
Code Costumes Sounds
The Scratch interface
Motion
now looks like this. Run
Motion
move 10 steps the program and the cat
Looks
turn 15 degrees chases the mouse-pointer
Sound turn 15 degrees
through space.
when clicked
Events go to random position
forever
go to x: 0 y: 0 go to mouse-pointer
Control
move 10 steps
glide 1 secs to random position
Sensing
glide 1 secs to x: 0 y: 0
Operators
point in direction 90
Variables
Stage
point towards mouse-pointer Sprite Sprite1 x 0 y 0
My Blocks
Show Size 100 Direction 90
Below the sprites list is a button to add a Add this code to the dragon sprite. Click the
8 sprite from the library. Click it, choose the 9 color-coded buttons in the blocks palette to
“Fantasy” category from the menu on top, select the blocks below, and then drag them into
and select “Dragon”. the code area. The dragon will now chase the cat.
The dragon is
highlighted in when clicked
Use the menu to
blue to show it’s make the dragon
your current sprite set size to 50 % point towards the
cat (“Sprite1”)
Add a forever
sprite from
the library point towards Sprite1
move 10 steps
Choose a Sprite
Dragon
Click the blue “Motion” button and drag the “go to With the dragon sprite highlighted, add this
10 x:0 y:0” block into the code. Click the number boxes 11 second bit of code to the code area. The “wait
in the block and change them to -200 and -150. until” block is found in the “Control” section, and
Click the purple “Looks” button and add the “switch the “touching” block is in the “Sensing” section. The
costume to” block to your code. dragon now breathes fire when it touches the cat.
Use the menu to
choose “Sprite1”
when clicked when clicked (the cat)
Place this block
set size to 50 % here to make the wait until touching Sprite1 ?
dragon start in
go to x: -200 y: -150 the corner
switch costume to dragon-c
switch costume to dragon-a
stop all Drag this
forever block inside
Use the menu to This “Control” block the “wait
choose “dragon-a”. stops the program until” block
point towards Sprite1 The dragon will start
in this costume
move 4 steps Costume
“dragon-c” makes
the dragon
Change 10 to 4 to make breathe fire
the dragon move slower
than the cat
ESCAPE THE DRAGON! 35
In coding, a “variable” is used to store information. Type in the variable name “Time” and make sure
12 This step uses a variable to create a timer to measure 13 the “For all sprites” button is selected underneath,
how long a player survives before getting toasted. then click “OK.” This means that the cat, dragon,
Click the “Variables” button and then click “Make and any other sprites can use the variable.
a Variable.”
New Variable
Variables
Click to
create
Make a Variable
a variable New variable name:
Select Time
my variable this option
then click
set my variable to 0 “OK” For all sprites For this sprite only
This is a
when clicked “Sensing”
block
Add a forever
sprite from Donut
the library wait until mouse down?
Select the cat in the sprites list so its code appears. Click the green flag button to run the program.
18 Click the arrow in the “point towards mouse-pointer” 19 Press the mouse button and the donut moves
block and choose “Donut”. Do this so that the cat to the mouse-pointer. The cat follows the
follows the donut instead of the mouse-pointer. donut, and the dragon chases the cat.
Dragon
Donut
Choose the
donut from
Move the
the drop-
donut using the
down menu
mouse-pointer
ESCAPE THE DRAGON! 37
Now add some music. Click the “Sounds” tab Search for the “Drip Drop” sound
20 above the blocks palette. Each sprite has its own 21 and select it. The sound is added to
sounds, and they are managed here. Click the the cat sprite, and appears in the
button on the bottom left to add a sound from “Sounds” area.
the library.
Add a Delete
sound from sounds here
the library Drip Drop
2.86
Choose a Sound
This is how long
the sound lasts
Choose “Drip
when clicked Drop” from the
drop-down menu
forever
REMEMBER
Achievements
This project has shown some of Made sprites move: You’ve made sprites
the things Scratch can do. Here’s chase each other.
what you’ve achieved. Used a variable: You’ve created a timer for
your game.
Created a program: By combining blocks of Used costumes: You’ve changed the dragon’s
code into code, you’ve put together a game. appearance using different costumes.
Added pictures: You’ve used both backdrops Added music: You’ve added a sound, and
and sprites. made it play when your program runs.
38 S TA R T I N G F R O M S C R AT C H
‹ 28–29 Sprites
Computer games are all about firing, dodging, catching, Coordinates 56–57 ›
and escaping. Characters might run, fly spaceships, or
drive fast cars. To create great games in Scratch, you first
need to learn how to make sprites move.
Motion blocks
The dark blue “Motion” blocks make sprites move. Start a new project
by clicking the “File” menu and choosing “New.” The new project
begins with the cat in the middle of the stage, ready for action. Add this block to tell
Scratch when to start
running the code
First steps
1 Drag the “move 10 steps” block from the “Motion”
when clicked
Click the white
section of the blocks palette and drop it into the code window on the
area to its right. Drag an orange “forever” block from block and type
forever in a different
the “Control’’ section of the blocks palette and drop it
number to
around this block. Click the green flag on the stage move 10 steps change how far
to run the program. The cat moves until it hits the the cat moves
edge of the stage.
The “forever” block
repeats anything
inside it endlessly
Bouncing Rotating
2 Drag an “if on edge, bounce” block inside your 3 Drag the blue “set rotation style” block into the
“forever” block. Now the cat bounces when it hits the “forever” block and drop it below the “if on edge, bounce”
edge of the stage. The cat is upside down when block. Now the cat will face the right way up after
it walks to the left. bouncing off the edge of the stage.
Try changing
when clicked 10 to 30 to make when clicked
the cat sprint!
forever forever The cat faces left or
right, and is always
move 10 steps move 10 steps the right way up
Heading the
of the cat 180°
4 right way
point in direction -90 △ Compass
Drag the “point in direction” Directions are measured in
block into the code area. degrees, from 0° at the top.
Click on the number in the Move the You can use any number
white window and type in arrow on the between -179° and +180°.
a new direction. drop-down
compass to The cat will follow
select a the mouse-pointer
direction for
the cat
‹ 38–39 Making
things move
To change what a sprite looks like, its expression,
or its position, you need to change its “costume.”
Sending 70–71
messages
›
Costumes are pictures of a sprite in different poses.
Different costumes
1 Click the “Costumes” tab to see the cat’s
costumes. They show the cat with its legs and
arms in two different positions.
△ Ballerina’s code
The same code works for the ballerina and
the cat. The ballerina has four costumes, and
she uses them all as she dances on the stage.
EXPERT TIPS
Switching
You can choose to show a specific
switch costume to ballerina-a
costume for your sprite using
the “switch costume to” block.
Switch costumes: Use the menu in the block to choose a costume.
You can use this block to
choose a particular position
for your sprite. switch backdrop to backdrop1
Switch backdrops: Change the picture on the stage with this block.
She crouches
and says “Down!”
42 S TA R T I N G F R O M S C R AT C H
‹ 38–39 Making
things move
Welcome to the special effects studio! Using the purple
“Looks” blocks, find out how to make sprites vanish and
Sending 70–71
messages
›
reappear, grow and shrink, and fade in and out.
Use the “hide” block
Hiding sprites to make sprites
disappear in games
To make a sprite disappear, use the “hide” block. The
sprite is still on the stage, and it can still move around,
but it can’t be seen unless the “show” block is used to
make it visible again.
▽ Disappearing cat
Try this code using the cat sprite. It
disappears and reappears but it keeps
moving, even when you can’t see it. EXPERT TIPS
Showing sprites
when clicked Select a sprite in the sprites list. You
will see an information panel above
forever this list. There, you can use the “Show”
icons to show or hide a sprite.
wait 1 seconds This block hides
the cat
hide
This block
turn 90 degrees rotates
Sprite Sprite1 x 0 y 0
the cat
move 100 steps clockwise
Show Size 100 Direction 90
glide 0.1 secs to x: pick random -150 to 150 y: pick random -150 to 150
repeat 20
This block makes the
change ghost effect by -5 ghost move slowly,
hidden from view
Using this block makes the
sprite fade back in
44 S TA R T I N G F R O M S C R AT C H
Clicking LINGO
Code can be added to a sprite that makes What is an event?
it do something if the sprite is clicked while
the program is running. Experiment with An event is something that
happens, such as a key being
different blocks to see what a sprite can
pressed or the green flag being
do when clicked. clicked. The blocks that look for
Drag this block events go at the top of the code.
from the “Events” The code waits until the event
menu to start happens, and then it runs.
the code
when this sprite clicked
Key presses
Programs can be built to react when different
keys on the keyboard are pressed. For another
way of using the keyboard that’s better for
creating games, see pages 66–67.
Choose the
Choose the key here
key here
Change the
text here
when h key pressed when g key pressed
Change the
Webcam motion detector number to 40
If you have a webcam, it can be used with when video motion > 40
Scratch too. Add this code to the cat, and
play sound Meow until done
when you wave at it through the webcam,
it will meow back. To use the webcam △ Detect motion
blocks, click “Add Extension” at the bottom Use the “when video motion” block. The code
left, then choose “Video Sensing”. will start when you’re moving around enough.
EXPERT TIPS
Backdrop changes
Choose the
A sprite can react to the backdrop backdrop here
changing. For example, you can have a
backdrop that makes the sprite disappear.
when backdrop switches to Desert
Upload a new backdrop from the stage
list in the bottom right of the screen, and hide
then add the “when backdrop switches Hides the sprite when
to” block to do this. the backdrop changes
46 S TA R T I N G F R O M S C R AT C H
Repeat loop
To repeat an action a certain number of times, use a
“repeat 10” block. Change the number in it to set how
many times the loop will repeat itself. Add the “Dinosaur4” REMEMBER
sprite to a new project and build it this code. Loop block shape
The loop blocks are shaped like
when clicked
jaws. Drop the blocks that you
repeat 3 Change the number to 3 want to repeat into the jaws, so
the loop wraps around them. As
switch costume to dinosaur4-d you add more blocks, the jaws
stretch to make room for them.
wait 0.5 seconds The sprite stands
on one leg
switch costume to dinosaur4-c
The sprite stands
wait 0.5 seconds
up straight
▷ Loops in loops
This “forever” loop when clicked
has several repeat
loops inside it. Make forever
sure the blocks are
inside the right loops, repeat 3
otherwise the program
won’t work properly. switch costume to dinosaur4-d
The previous
dance move repeat 3
(see opposite)
move 20 steps
The dinosaur
moves three
steps to the right wait 1 seconds
This block creates
repeat 3 a short pause
‹ 44–45 Events
Each sprite has a pen tool that can draw a line behind ‹ 46–47 Simple loops
it wherever it goes. To create a picture, turn on the pen
and then move the sprite across the stage, like moving
a pen across paper. To use the pen blocks, click “Add
Extension” at the bottom left, then choose “Pen”.
Draw a square
To draw a square, you simply put the pen The sprite will
leave a line
down on the stage and then move the sprite behind it
in a square shape. Use a loop to draw the four
sides and turn the corners.
when clicked
if on edge, bounce
Keeps the
Keeps the plane
plane moving
on the stage
pen down
Turns the pen on
pen up
Turns the pen off
erase all
Clears the pen trail
50 S TA R T I N G F R O M S C R AT C H
if on edge, bounce
Set my speed using
the “set steps to 0”
block.
EXPERT TIPS
Read-only variables
Deleting variables Some variables are set by Scratch and can’t
When you no longer want a variable, be changed. They’re still variables, though,
right-click on it in the blocks palette and because their values vary. These blocks are
then select “Delete the variable.” You’ll lose known as sensing blocks.
any information that was in it.
Tracks the distance to
Variables distance to ▾
something, such as the
mouse-pointer.
Make a Variable Variables can
be renamed
Reports the number of
here costume #
my variable the costume a sprite is
wearing.
steps
Rename variable Tells you which direction
direction a sprite is traveling in.
Delete the “steps” variable
52 S TA R T I N G F R O M S C R AT C H
‹ 50–51 Variables
As well as storing numbers in variables (see pp.50–51), Math 112–113
in Python
›
Scratch can be used to carry out all sorts of calculations
using the “Operators” blocks.
Doing sums
There are four “Operators” blocks
that can be used to do simple 7 + 22 64 – 28
calculations. These are addition, △ Addition △ Subtraction
subtraction, multiplication, The “+” block adds the two The “–” block subtracts the
and division. numbers in the block together. second number from the first.
think 2 + 5 11 * 10 120 / 4
Results in a variable
Variables are useful if you
For more complex calculations, such as fixing want to repeat the same sum
the sale price of an item, instead of just using with different values.
numbers you can use the value of a variable in
a sum. The result can be stored in a variable too.
wait 2 seconds
◁ Switching costumes
switch costume to pick random 1 to 3
This code changes a sprite’s
costume at random every
two seconds.
◁ Random costumes
Costumes can make a sprite
appear to move its body,
or might give it different
clothes, as shown here.
‹ 50–51 Variables
In programming, a sequence of letters and symbols Strings 114–115
in Python
›
is called a “string”. Strings can contain any character
on the keyboard (including spaces) and be of any length.
Strings can also be grouped together in lists. Keyboard characters are
lined up as if they were
hanging from a string
A B C D E F G H I
Working with words 1 Create a new variable
Click the “Variables” button in the blocks
Programs often need to remember words, palette and click the “Make a Variable” button.
such as a player’s name. Variables can be Create a variable called “greeting”.
created to remember these words. Scratch
Variables
programs can also ask the user questions,
which they answer by typing into a text Make a Variable
box that pops up. The following code asks
Name your
for the user’s name, and then makes a greeting
variable
sprite say “Hello” to them. “greeting”
my variable
New List delete all of sentence The “ask” block asks the
user to type in a word
forever
New list name: This adds the user’s
ask Add a word and wait answer to the list
sentence
add answer to sentence
For all sprites For this sprite only
think sentence for 2 seconds
Cancel OK
‹ 38–39 Making
things move
To put a sprite in a particular spot, or to find out its
exact location, you can use coordinates. Coordinates
‹ 52–53 Math
are a pair of numbers that pinpoint a sprite’s position
on the stage using an x and y grid. Type in these boxes to change
the sprite’s current coordinates
◁ Show coordinates
x position
on the stage
Check the boxes beside
y position the “x position” and △ Position of a sprite
“y position” blocks to You can see a sprite’s current coordinates in
show a sprite’s position the information panel above the sprites list.
on the stage.
x and y grid
To pinpoint a spot, count the number of
steps left or right, and up or down, from 180
y
the middle of the stage. Steps to the left
or right are called “x”. Steps up or down are 120
called “y”. Use negative numbers to move
left and down. (x: –100, y: 100)
60
(x: 180, y: 50)
–120
when clicked
Record a sound
using the computer’s
Click here to select a microphone
sound effect from
Scratch’s library
Choose a Sound
play drum (1) Snare Drum for 0.25 beats rest for 0.25 beats
EXPERT TIPS
Playing music Tempo
Connecting notes together makes a tune. Create a new
variable called “note” (see pp.50–51), and then add the The speed of music is called its
following code to any sprite to create a piece of music. tempo. The tempo decides how
long a beat is within a piece of
music. There are three blocks for
Set the value of the managing the tempo.
when clicked variable “note” first
set tempo to 60
set note to 1 Choose an instrument
PROJECT 2
‹ 40–41 Costumes
Simple programs can be both useful and fun. ‹ 46–47 Simple loops
This program creates a die that can be rolled. Play ‹ 50–51 Variables
it to see who can get the highest number, or use it ‹ 52–53 Math
instead of a real die when you play a board game.
Fill Outline 2
Paint
Choose a
Color 72
color from
the color bar
Right-click on your
EXPERT TIPS
3 costume to the 1 Use the menu
to duplicate
left of the painting
the die Rotation tool
area, and choose costume
“duplicate”. Repeat To make the die appear to roll
this step until you costume1
123 x 123
when the code is run, you can
have six costumes. duplicate rotate each costume to a different
delete angle. Click on the “Convert to
Vector” button in the bottom
left-hand corner and select the
“Select” tool. When you click back
Select a costume. Click the circle button
on to the painting area, a rotation
4 on the painting area and choose a solid
tool will appear.
white color from the palette. Add spots
to each of the six costumes until you
have made all six sides of a die.
Sometimes you’ll roll the same number twice, and it looks like This block selects
6 the program isn’t working because the image doesn’t change. This a random costume
code makes the die change costumes five times before it stops.
Each time you press the spacebar, it looks like it’s rolling.
Comparing numbers =
◁ The “=” block
This block will give one of two answers:
You can compare numbers using the “true” if the two numbers in the boxes
“=” block from the “Operators” section are equal, and “false” if they aren’t.
of the blocks palette.
The numbers are These numbers
equal, so “true” true are not equal, so false
appears in the “false” appears in
speech bubble the speech bubble
say 3 = 3 say 3 = 2
set age to 10
This sign means “less than”, so the
block is asking if “age” is less than
△ Create a variable 18. The answer will be “true”, as 10
Click the “Variables” button in the blocks age < 18 is smaller than 18
palette and create a new variable called
“age”. Set its value to 10 (click on the △ Comparing numbers
block to make sure the value has Find the green comparison blocks in the “Operators” menu.
changed). Drag the “age” variable into As well as checking whether two numbers are equal, you can
the comparison blocks. check whether one is greater or less than another.
T R U E O R FA L S E ? 63
EXPERT TIPS
Comparing words
The “=” block is not just used for numbers; The variable “name”
contains “Lizzie”, so the
it can also be used to check whether two answer is true
strings are the same. It ignores capital
letters when comparing strings. name = Lizzie
set name ▾ to Lizzie Drag and drop the The answer is false
variable into the because the variable
comparison block doesn’t contain “Dan”
△ Create a variable
To experiment with comparing strings,
create a new variable called “name” and name = Dan
set its value to “Lizzie”.
Not!
◁ The “not” block
The “not” block can simplify things by reversing not
The “not” block changes the
the answer of a Boolean expression. For example, answer around, from true to
it’s easier to check if someone’s age is not 10 false and from false to true.
than to check every other possible age.
Combining questions or
To ask more complicated questions, you can combine
comparison blocks and ask more than one question and
at the same time.
△ Comparison blocks
The “or” and “and” blocks are used
to combine Boolean expressions
age < 18 or age > 65 in different ways.
‹ 62–63 True
or false?
Tests of whether something is true or false can be
used to tell the computer what to do next. It will
Sensing and 66–67
detecting
›
perform a different action depending on whether
the answer is true or false.
Drag a Boolean if then
expression into
Making decisions this window
mouse down?
△ ”Sensing” blocks
These blocks can test whether a sprite is touching
another sprite, or whether a button is pressed.
repeat until
‹ 40–41 Costumes
The “Sensing” blocks enable your program to see what is ‹ 56–57 Coordinates
happening on your computer. They can detect keyboard
controls, and let sprites react when they touch each other. This block checks if a key is
being pressed. You can choose
which key to check for
Keyboard controls
Using “Sensing” blocks with “if-then” blocks allows you key space pressed?
to move a sprite around the screen using the keyboard. This block checks if the mouse
The “key pressed?” block has a menu of most of the button is being pressed
keys on the keyboard, so a sprite can be programmed
to react to almost any key. You can also link actions to mouse down?
the click of a mouse button. △ “Sensing” blocks
Putting everything inside Adding these blocks into an “if-then” block
a “forever” block means the
allows the program to detect if a mouse
code repeatedly checks for
key presses button or key is being pressed.
when clicked
change y by 10
change y by -10
change x by -10
△ Controlling sprites
Keyboard controls give you
precise control over your
if key right arrow pressed? then sprites, which is especially
useful in games.
change x by 10
◁ Movement code
This code lets you move sprites up,
down, left, or right using the arrow
keys on the keyboard.
SENSING AND DETECTING 67
Sprite collisions Use this block to identify when
a sprite touches another sprite
It can be useful to know when
one sprite touches another—in touching frog ?
games, for example. Use “Sensing” This block senses when a
blocks to make things happen sprite touches an area of
a particular color
when sprites touch each other, or
when a sprite crosses an area that
touching color ?
is a certain color.
‹ 46–47 Simple
loops
Simple loops are used to repeat parts of a program
forever, or a certain number of times. Other, cleverer
‹ 62–63 True
or false?
loops can be used to write programs that decide
exactly when to repeat instructions.
say Ouch!
This will happen only when
the cat touches the dog
△ Testing the program
Move the dog out of the cat’s way and run
the program. Then drag and drop the dog
into the cat’s path to see what happens.
change y by 20
‹ 38–39 Making
things move
Sometimes it’s useful for sprites to communicate
with each other. Sprites can use messages to tell
‹ 40–41 Costumes
other sprites what to do. Scratch also lets you
‹ 44–45 Events
create conversations between sprites. This “Events” block lets a sprite send a
message to all the other sprites
say How are you? for 2 seconds say Hi! for 2 seconds
broadcast howareyou
The “howareyou”
message starts
this third section
of code Great, thanks!
△ Chatty monkeys
This program works because it uses the “broadcast message
and wait” block. If the “broadcast message” block was used,
the monkeys would talk over each other.
72 S TA R T I N G F R O M S C R AT C H
‹ 50–51 Variables
To avoid repeating the same set of blocks over and over Time to 82–83
experiment
›
again, it’s possible to take a shortcut by creating new blocks.
Each new block can contain several different instructions.
Sound
define jump
jump
Events
Control
to make
a new
Operators
The new block Define the
block Variables
“jump” block in
the code area
My Blocks
“Add an input number or text” and type “steps”. Run without screen refresh
Select “Add a label” and change it to “and shout”.
Click “Add an input number or text” again and call Cancel OK
PROJECT 3
‹ 40–41 Costumes
This exciting, fast-paced game brings together all of the ‹ 38–39 Making
things move
Scratch skills you’ve learned so far. Follow these steps to
create your very own “Monkey mayhem” and see if you
‹66–67 Sensing and
detecting
can hit the bat with the bananas!
EXPERT TIPS
Getting started Avoiding errors
Start a new Scratch project. The cat sprite isn’t needed
This is the biggest Scratch
for this project. To remove it, right-click on it in the program you’ve tried so far, so you
sprites list and then click “delete” in the menu. This will might find that the game doesn’t
leave you a blank project to work on. always work as you expect it to.
Here are some tips to help things
run smoothly:
Add a new backdrop from the Click here to
1 backdrop library. This button is add a new
backdrop from
Make sure you add the code to the
correct sprite.
found to the right of the sprites list.
the backdrop Follow the instructions carefully.
library
Remember to make a variable before
using it.
Check that all the numbers in the
Choose a Backdrop blocks are correct.
MONKEY MAYHEM
Adding more sprites
The monkey can now be moved across the stage using
the left and right arrow keys. To make the game more
interesting, add some more sprites. Give the monkey
some bananas to throw, and a bat to throw them at!
go to x: 210 y: -140
This “if-then-else” block
makes the bananas reappear
else
on either the right or left
side of the stage, randomly
go to x: -210 y: -140
show
MONKEY MAYHEM
The finishing touches 8
Create a new variable called “Time”. Make sure it’s
available for all sprites in the game by selecting the
To make the game even more exciting, you “For all sprites” option. Check that the box next to
can add a timer, use a variable to keep score the variable in the blocks palette is checked, so that
of how many bats the player hits, and add a players can see the time displayed on the stage.
game-over screen that appears once the
player is out of time. Time
GAME OVER
to the new backdrop.
Use the text tool
to write on the
duplicate backdrop
Add this short bit of code to the bananas Add this code to the bananas sprite too. When the
12 sprite. It sets the score to 0 at the beginning 13 bananas hit the bat, it plays a sound, increases
of the game. the score by 10, and hides the bananas.
Makes the
when clicked bananas when I receive hitbybananas
disappear
Add the “Pop” sound
set Score to 0 hide
from the sound library
to the banana sprite
start sound Pop (see pp.58–59)
This resets the score
change Score by 10
MONKEY MAYHEM
Time to play To make the game last
You can edit the
program to give the
Now the game is ready to play. Click the longer, try increasing player more points for
the time limit each successful hit
green flag to start and see how many
times you can hit the bat with the
bananas before the time runs out.
Score 0
Spacebar
Space
△ Controls
Steer the monkey left and right with To make the
the keyboard cursor keys. Tap the game harder,
spacebar to fire bananas at the bat. make the bat
move faster
EXPERT TIPS
Adding more sprites
To add more bats to aim at, right-click the bat in
the sprites list and select “duplicate”. A new bat
will appear with the same code as the first one.
Try adding some other flying sprites:
◁ Going bananas
There are countless ways to
change Monkey mayhem. By
adjusting the speeds, scores,
sounds, and sprites, you can
create your own unique
version of the game.
82 S TA R T I N G F R O M S C R AT C H
move 10 steps
Every tutorial
is a video Click here
that explains to go to the
a concept next screen
step by step
▷ Similar to Scratch
Python uses loops, variables,
and branches too. Use your
Scratch knowledge to start
learning Python!
Playing
with Python
86 P L AY I N G W I T H P Y T H O N
A useful language
Python is a versatile language that can be used to
make many different types of programs, from word
processing to web browsers. Here are a few great
reasons to learn Python.
Python contains
lots of programs
you can use and
build on
Hello World!
The message appears
on screen like this
Hello World!
Installing Python
Before you can use the Python programming language,
you need to download and install it on your computer.
Python 3 is free, easy to install, and works on Windows
PCs, Macs, and Linux operating systems such as Ubuntu.
MAC UBUNTU
△ Mac △ Ubuntu
If you use an Apple Mac, find out which Ubuntu is a free operating system that
operating system it has before you install works just like Windows and Macs. To
Python. Click the apple icon in the top find out how to install Python on
left and choose “About This Mac.” Ubuntu, turn to page 91.
I N S TA L L I N G P Y T H O N 89
Python 3 on Windows
Before you install Python 3 on a Windows PC, make sure you get
permission from the computer’s owner. You may also need to
ask the owner to provide an admin password during installation.
Python 3 on a Mac
Before you install Python 3 on a Mac, make sure you get
permission from the computer’s owner. You may also need to ask
the owner to provide an admin password during installation.
http://www.python.org
• Python 3.7.0 - 2019-02-15
Don’t worry about the • Download macOS 64-bit/32-bit installer
exact number, as long
as it has a 3 at the front
This version runs
on most Macs
IDLE icon
Python.pkg
3 Install IDLE
Type the commands shown below into 4 Run IDLE
After the installation is complete, enter
the Terminal window one at a time. Make sure “IDLE” into the search bar and double-click on
you start typing after the “$” sign. the blue-and-yellow “IDLE icon.
This updates the system
so you can install the latest
version of any software
‹88–91 Installing
Python
IDLE helps you write and run programs in Python.
See how it works by creating this simple program
Which 106–107
window?
›
that writes a message on the screen.
“Save As...”. Enter the file name IDLE File Edit Format Run Window Help
“HelloWorld” and click “Save”. prin New File
Open...
Open Module...
Recent Files ▶
If you get an error message,
check your code carefully Module Browser
to make sure you haven’t
made any mistakes. Path Browser
Close
Save
Click here to
save the file
Save As...
menu and select “Run Module”. This will IDLE File Edit Format Run Window Help
run the program in the shell window. print("Hello World!") Python Shell
Check Module
Click here to
run the program Run Module
EXPERT TIPS
>>>
Traceback (most recent call last):
File "C:\PythonCode\errors.py", line 1, in <module>
pront("Hello World!")
Cut
NameError: name "pront" is not defined
Copy
The word Python
doesn’t understand Paste Click here to highlight the
line where the error appears
Go to file/line in the code window
PROJECT 4
Ghost game SEE ALSO
Ghost game 98–99
decoded
›
This simple game highlights some of the things
to watch out for when writing programs in
Program 100–101
flow
›
Python. Once the code has been typed in, run
the program to play the game. Can you escape
the haunted house?
Once the code has been carefully typed in, use the The game begins in the shell window. The ghost is
2 “Run” menu to select “Run Module.” You must save 3 hiding behind one of three doors. Which one will
the program first. you pick? Type 1, 2, or 3 then press “Enter.”
The aim of the game is to pick a door with no ghost If you’re unlucky you’ll pick a door with a ghost
4 behind it. If this happens, you’ll move to the next 5 behind it, and the game ends. Run the program
room and keep playing the game. again to see if you can beat your last score.
1 2 3
98 P L AY I N G W I T H P Y T H O N
Game setup
1 These instructions run
# Ghost Game This sets up the “randint”
command, which generates
only once—at the beginning from random import randint
random numbers
of the game. They set up print("Ghost Game")
the title, variables, and the The “print” command
feeling_brave = True
“randint” command. displays text when
score = 0 the game is run
EXPERT TIPS
Type carefully
When using Python, enter the
code very carefully. If you leave
out a colon, quotation mark, or
parenthesis, the program won’t
work properly. You need to match
the use of capital letters and
spaces exactly too.
GHOST GAME DECODED 99
The main loop This selects a
2 This loop tells the story
while feeling_brave: random number
ghost_door = randint(1, 3) between 1 and 3
and receives the player’s guess.
It keeps on going as long as there print("Three doors ahead ...")
isn’t a ghost behind the door The “print”
print("A ghost behind one.") command displays
that’s picked. When a ghost
print("Which door do you open?") the text onscreen
appears, the “feeling_brave”
variable changes to “False” and door = input("1, 2 or 3?")
the loop stops repeating. This line asks for
door_num = int(door) the player’s answer
if door_num == ghost_door:
Branching part This branch runs
3 The program takes a
print("GHOST!") if there’s a ghost
behind the door
different path depending on feeling_brave = False
the player picks
whether or not there was a else:
ghost behind the door that was
print("No ghost!") If there’s no ghost,
picked. If there was a ghost, the
the player sees
“feeling_brave” variable is set to print("You enter the next room.")
this message
“False” but if not, the player’s score = score + 1
score increases by one.
Game ending
4 This runs just once, when
print("Run away!")
you meet the ghost and the print("Game over! You scored", score)
loop ends. Python knows this
isn’t part of the loop because The score is a variable—it will
it’s not indented. change depending on how many
rooms the player gets through
REMEMBER
Achievements
Congratulations—you’ve created Run a program: You’ve learned how
your first Python game! You’ll learn to run a Python program.
more about these commands later Structured a program: You’ve used
in the book, but you’ve already indents to structure a program.
achieved a lot: Used variables: You’ve used variables
to store the score.
Entered a program: You’ve typed a
Displayed text: You’ve displayed
program into Python and saved it.
messages on the screen.
100 P L AY I N G W I T H P Y T H O N
Input
1 In Python, the “input()” function takes
an input from the keyboard. It’s similar to the The question in
“ask and wait” block in Scratch. the Scratch block
Processing
2 Variables are used to keep track of the score and This Scratch block
sets the value of the
the function “randint” picks a random door. Different variable “score” to 0
blocks are used to do these things in Scratch.
‹86–87 What is
Python?
At first glance, Python can look quite scary,
especially when compared to Scratch. However,
Harder 104–105
commands
›
the two languages aren’t actually as different as
they seem. Here is a guide to the similarities
between basic commands in Python and Scratch.
Command Python 3 Scratch 3.0
Set a variable
magic_number = 42 set magic_number to 42
to a number
Set a variable
word = "dragon" set word to dragon
to a text string
cats = cats + 1
Add a number
or change cats by 1
to a variable
cats += 1
Add a + 2 a + 2
Subtract a - 2 a – 2
Multiply a * 2 a * 2
Divide a / 2 a / 2
SIMPLE COMMANDS 103
Command Python 3 Scratch 3.0
forever
while True:
Forever loop jump
jump()
repeat 10
for i in range (10):
Loop 10 times jump
jump()
Is equal to? a == 2 a = 2
OR or or
if a = 2 then
if a == 2:
If then say Hello!
print("Hello!")
if a = 2 then
if a == 2:
say Hello!
print("Hello!")
If then else else
else:
print("Goodbye!") say Goodbye!
104 P L AY I N G W I T H P Y T H O N
‹86–87 What is
Python?
Python can also be used to do some of the more
complicated things that are possible in Scratch: for
‹ 102–103 Simple
commands
example, creating complex loops, playing with strings
and lists, and drawing pictures with turtle graphics.
Call a function
jump() jump
or subprogram
Call a function
greet("chicken") greet chicken
or subprogram
HARDER COMMANDS 105
Command Python 3 Scratch 3.0
penup() pen up
Length of
len(name) length of name
a string
Add an item
menu.append(thing) add thing to menu
to end of list
How many
len(menu) length of menu
items on list?
Delete 2nd
del menu[1] delete 2 of menu
item on list
‹ 92–93 Introducing
IDLE
There are two different windows to choose from
in IDLE. The code window can be used to write
‹96–97 Ghost
game
and save programs, while the shell window runs
Python instructions right away.
▷ Code window
The code window is ideal
Code vs Shell ◁ Shell window
The shell window is perfect
for longer pieces of code for quick experiments, such
because they can be saved as checking how a command
and edited. It’s easier than works. It’s also a handy
retyping all the instructions calculator. It doesn’t save the
if you want to do the same instructions though, so if you’re
thing again or try something trying something you might
similar. It needs to be saved want to repeat, consider using
and run each time, though. the code window instead.
108 P L AY I N G W I T H P Y T H O N
△ Assign a string
To assign a string, type in the variable name, an
equals sign, and then the string in quote marks.
Printing a variable
The “print” command is used to show something
on the screen. It has nothing to do with the printer.
You can use it to show the value of a variable.
△ Integers △ Floats
An integer is a number without A float is a number with a decimal
a decimal point, such as the 1 point, such as 1.5. They aren’t normally
in the variable “sheep”. used to count whole objects.
Strings
Just like in Scratch, a piece of text in Python is called
a “string.” Strings can include letters, numbers, spaces, Always remember that
and symbols such as full stops and commas. They are strings need quote
marks at the start
usually put inside single quote marks. and the end.
‹ 52–53 Math
Python can be used to solve all sorts of ‹ 108–109 Variables
in Python
mathematical problems, including addition,
subtraction, multiplication, and division.
Variables can also be used in sums.
Simple calculations
In Python, simple calculations can be made by typing them
into the shell window. The “print()” function is not needed
You can’t divide by zero,
for this—Python gives the answer straight away. Try these so you’ll always get an error
examples in the shell window: if you try to do so.
△ Multiplication △ Division
Use the “*” symbol to multiply two Use the “/” symbol to divide the
numbers together. first number by the second one.
‹54–55 Strings
and lists
Python is excellent for using words and sentences
within programs. Different strings (sequences of
‹ 110–111 Types
of data
characters) can be joined together, or individual
parts of them can be selected and pulled out.
Creating a string
A string might include letters, numbers, symbols,
or spaces. These are all called characters. Strings
can be placed in variables.
The quote marks indicate the
variable contains a string
▷ Strings in variables >>> a = "Run! "
Variables can store strings.
Type these two strings into
the variables “a” and “b”. >>> b = "Aliens are coming."
Adding strings
Adding two numbers together creates a new number.
EXPERT TIPS
In the same way, when two strings are added together,
one string simply joins on to the other one. Length of a string
The “len()” function is used to find
out the length of a string. Python
>>> c = a + b The variables “a” counts all of the characters,
>>> print(c)
and “b” combine to including spaces, to give the total
become variable “c” number of characters in a string.
Run! Aliens are coming.
Calculates the
△ Adding strings together length of the string
The “+” symbol joins one string to another. in variable “a” (“Run! “)
and the answer becomes the variable “c”.
A new string is added
to variable “c” >>> len(a)
4
>>> c = b + " Watch out! " + a
The new string >>> len(b)
>>> print(c)
appears in the middle 18
Aliens are coming. Watch out! Run! of the message
‹ 100–101 Program
flow
Programs interact with users through input and output.
Information can be input into a program using a keyboard.
‹ 110–111 Types
of data
Output is shown as information printed on the screen. Loops 122–123 ›
in Python
Adding a space
1 Using input
A program can prompt the
after the colon
makes the output 2 Output in the shell window
When the program is run, the message
look tidier
user what to type. The message is “Enter your name: ” and its response appear
put inside the brackets of “input()”. in the shell window.
name = input ("Enter your name: ") Enter your name: Jina
print("Hello", name) Hello Jina
Output
The “print()” function is used to display characters
in the shell window. It can be used to show
a combination of text and variables.
Output is displayed
on the screen
‹ 62–63 True or
false?
Programs make decisions about what to do
by comparing variables, numbers, and strings
‹ 108–109 Variables
in Python
using Boolean expressions. These give an
answer of either “True” or “False.”
Logical operators
Logical operators are used to compare variables against
numbers or strings, or even against other variables.
The resulting answer is either “True” or “False.”
“Equals”
== operator
“Not equal
!= to” operator
This checks This checks
whether “toys” whether “toys”
“Less than”
is equal to 1 is more than 1
< operator
‹64–65 Decisions
and branches
Boolean expressions can be used to determine which
route a program should follow, depending on whether
‹118–119 Making
decisions
the answer to the expression is “True” or “False.” This is
known as “branching.”
Do or do not
The “if” command means that if a condition is “True,” then the program runs
a block of commands. If the condition isn’t “True,” the block is skipped. The
block after the “if” command is always indented by four spaces.
“if” condition
1 This code asks the user
ans = input("Is it your birthday? (y/n)") Prompts users
what to type in
if it’s their birthday. It checks if ans == "y":
whether the answer is “y”. If so, print("Happy Birthday!")
a birthday message is printed.
This part of the
Indented by four spaces program runs only
Type in “y”
if the user types “y”
Output if condition is “True”
2 Run the program and enter “y”.
Is it your birthday? (y/n)y The message
appears
The message is printed. It doesn’t Happy Birthday!
appear if anything else is entered.
Do this or that
The “if” command can be combined with an
“else” command. This combination means that
if something is “True,” one thing happens, and if
not, something else happens.
“if-else” condition
1 If “y” is entered, the program
ans = input("Is it New Year? (y/n)") Remember the colon
“if-elif-else” condition
1 This program checks what is typed 2 Output for the condition that’s “True”
Test the program. Enter two numbers and
in. If it’s “add”, “sub”, “mul”, or “div”, the type in “sub”. The answer will be the first number
result of the sum is shown. minus the second number.
Remember to Enter two numbers
Asks the user to add quote marks a = 7
input a number and brackets
b = 5
Type in “sub”
add/sub/mul/div:sub
a = int(input("a = ")) to subtract
Answer = 2 5 from 7
b = int(input("b = "))
op = input("add/sub/mul/div:")
Answer is calculated
if op == "add": by subtracting variable
Type “add” “a” from variable “b”
c = a + b to add the
elif op == "sub": variables
together
c = a - b
“else” condition output
elif op == "mul": 3 The “else” condition runs if something other than
c = a * b “add”, “sub”, “mul”, or “div” is typed in, and an error message
is displayed.
elif op == "div": Type “div” to
c = a / b divide the a = 7
variables
else: b = 5
Type something
c = "Error" add/sub/mul/div:try different here
‹48–49 Pens
and turtles
Programs that contain repeating lines of code can be
time-consuming to type in and difficult to understand.
While loops 124–125 ›
A clearer way of writing them is by using a loop command.
Escaping 126–127
loops
›
The simplest loops are ones that repeat a certain number
of times, such as “for” loops.
Repeating things
A “for” loop repeats the code without having
to type it in again. It can be used to repeat
something a certain number of times, for
example, if you want to print the names of
a class of 30 students.
Nested Loops
Loops inside a loop are called “nested loops.” >>> The value of “a”
In nested loops, the outer loop repeats only 1 x 1 = 1
The value First time around
after the inner loop has gone around its of “b” 2 x 1 = 2 the outer loop (the
required number of times. inner loop repeats
3 x 1 = 3 three times)
To make the loops repeat “n” number of times, 1 x 2 = 2
the last number in the range must be “n + 1” Second time around
2 x 2 = 4 the outer loop
n = 3 Outer loop 3 x 2 = 6
for a in range(1, n + 1): 1 x 3 = 3
Third time around
for b in range(1, n + 1): 2 x 3 = 6 the outer loop
print(b, "x", a, "=", b * a) 3 x 3 = 9
‹118–119 Making
decisions
“For” loops are useful when you know how many times a
task needs to be repeated. But sometimes you’ll need a
‹ 122–123 Loops
in Python
loop to keep repeating until something changes. A “while” Escaping 126–127 ›
loop keeps on going around as many times as it needs to. loops
while True:
answer = input("Type a word and press enter: ")
The typed word
print("Please do not type \"" + answer + "\" again.") is stored in the
variable “answer”
>>>
Type a word and press enter: tree No matter what
is typed, this REMEMBER
Please do not type "tree" again loop just keeps
Type a word and press enter: hippo
on going “forever” block
Please do not type "hippo" again Remember the “forever” block in
Scratch? It repeats the code inside
Type a word and press enter: water
it until the red stop button is
Please do not type "water": again clicked. A “while True” loop does
Type a word and press enter exactly the same thing. It can be
used to make a program keep
doing something, such as asking
questions or printing a number, as
EXPERT TIPS long as the program is running.
Stop the loop
If you get stuck in an infinite loop, you can forever
stop it from IDLE. Click in the Python shell
window, then hold down the “CTRL” key and
press the “C” key. This asks IDLE to stop the
Ctrl-C
program. You might have to press “CTRL-C”
a few times. This is similar to clicking the red The “forever” block keeps
stop button in Scratch. the sprite moving endlessly
126 P L AY I N G W I T H P Y T H O N
‹ 122–123 Loops
in Python
Programs can get stuck in a loop, but there are ways
to escape. The word “break” leaves a loop (even a
‹ 124–125 While
loops
“forever” loop), and the word “continue” skips back
to the start of the next loop.
Insert a “break”
2 A “break” can be added so the
table = 7
Skipping
The “continue” keyword can be used to skip a question without
leaving the loop. It tells the program to ignore the rest of the code
inside the loop and skip straight to the start of the next loop.
Insert a continue
table = 7 4 Add an “if” statement inside the loop to
for i in range(1,13): see if the user answered “skip”. If so, the program
print("What's", i, "x", table, "?") will print “Skipping” and execute a “continue”
to skip to the next go around the loop.
guess = input()
Asks the question
if guess == ‘stop’: “What’s 1 x 7?” first
time around the loop
break
What happens
if guess == "skip": 5 If the user doesn’t want to answer
print("Skipping") a question, he or she can type “skip” and
Skips straight continue to the next question.
continue to the next loop
ans = i * table >>>
if int(guess) == ans: What's 1 x 7 ?
Type “skip” to go to
print("Correct!") skip the next question
else: Skipping
print("No, it's", ans) What's 2 x 7 ? The loop goes around
print("Finished") again as normal when
14
the answer is correct
Correct!
What's 3 x 7 ?
128 P L AY I N G W I T H P Y T H O N
‹54–55 Strings
and lists
If you need to keep lots of data in one place, then you
can put it in a list. Lists can contain numbers, strings,
Silly 132–133
sentences
›
other lists, or a combination of all these things.
What is a list?
▽ Looking at lists
A list is a structure in Python where items are kept in
Each item in a list sits inside single
order. Each entry is given a number that you can use to quote marks, and is separated from
refer back to it. You can change, delete, or add to the the next item by a comma. The whole
items in a list at any point. list sits inside a pair of square brackets.
The list is stored in the variable “mylist”
The items in the list sit inside The items in a list are
a pair of square brackets separated by commas
▷ How it works
You can think of a list as a row Typing “mylist[1] = "cake"”
[1]
of shelves in a kitchen. Each would replace “milk” on shelf 1
shelf holds one item from the with “cake” instead
list. To make changes to an
item, you must refer to the
shelf it is on. The value of “mylist[2]”
[2] is “cheese”
To get to an item
on the list, you
[3] The ice cream would then move to position
4, and so on
◁ Lists in loops
Hello Simon
You can use a loop to work through
When run, this program
Hello Kate every item in a list. This program
displays “Hello”, followed
Hello Vanya by each name on the list says “Hello” to a series of names,
one after the other.
Useful functions
Python contains lots of useful functions for performing certain tasks.
When a function is called, Python retrieves the code for that function
and then runs it. When the function is finished, the program returns to
the line of code that called it and runs the next command.
Shows that 1 m 45 cm
To figure out the total in is equal to 145 cm
Prints the value of “total” “cm”, the value of “m” needs
followed by “cm tall” to be multiplied by 100
(because 1 m = 100 cm)
PROJECT 5
‹ 124–125 While
loops
Loops, functions, and lists can be used individually
for lots of different tasks. They can also be used ‹ 128–129 Lists
together to create interesting programs that can ‹ 130–131 Functions
do even more complex tasks.
while True:
print(pick(name), pick(verb), "a", pick(noun), end=".")
input()
‹ 110–111 Types
of data
Python uses lists for keeping data in order. It also has
other data types for storing information called “tuples”
‹ 128–129 Lists
and “dictionaries.” Data types such as these, which hold
lots of items, are called “containers.”
Tuples
Tuples are a bit like lists, but the items inside them
can’t be changed. Once a tuple is set up it always
stays the same. Tuples are surrounded
by brackets
>>> print(age)
◁ Print the dictionary
Name of the dictionary
The order of the items
{"Sanjay": 8, "Mary": 10} can change, because the
positions of items in a
The value of “Mary” is 10
The key for this dictionary are not fixed.
item is “Sanjay” Dictionary
name New key
▷ Add a new item >>> age["Owen"] = 11
A new value can be Adds a new item
>>> print(age) to the dictionary.
added to the dictionary
by labeling it with the {"Owen": 11, "Sanjay": 8, "Mary": 10}
new key.
The new value is now The existing values
in the dictionary are still there
Assign a new value to
the item labelled “Owen”
>>> age["Owen"] = 12
◁ Change a value
Assign a new value to
>>> print(age) an existing key to change
{"Owen": 12, "Sanjay": 8, "Mary": 10} its value.
▷ Delete an item
>>> del age["Owen"] The item labelled
Deleting an item in a dictionary “Owen” no longer
doesn’t affect other items because >>> print(age) appears in the
they are identified by their key, not {"Sanjay": 8, "Mary": 10} dictionary
by their position in the dictionary.
136 P L AY I N G W I T H P Y T H O N
‹ 108–109 Variables
in Python
There’s something about how Python stores lists
in variables that might seem a bit odd at first. But
‹ 128–129 Lists
take a look at what’s going on behind the scenes
and it all makes sense.
2
Remember how variables
only store values? a b
Variables are like boxes that hold values. △ How variables work
The value in one variable can be copied Each variable is like a box containing a
and stored in another. It’s like photocopying piece of paper with a value written on it.
the value contained in box “a” and storing
a copy in box “b.” This copies the contents
of “a” into “b”
Assign a value to a variable
1 Assign the value 2 to variable
>>> a = 2
in one variable it won’t affect the value >>> print("a =", a, "b =", b)
stored in another variable. In the same a = 100 b = 2
way, changing what’s written on a piece
of paper in box “a” won’t affect what’s on Now “a” contains 100,
the paper in box “b”. but “b” still contains 2
Variable “a” still contains 100. Even though >>> print("a =", a, "b =", b)
the value of “b” was copied from “a” a = 100 b = 22
at the start, they are now independent—
changing “b” doesn’t change “a”.
“b” now contains 22,
but “a” is still 100
L I S TS I N VA R I A B L E S 137
What happens if a list is put in a variable?
Copying the value in a variable creates two independent
copies of the value. This works if the value is a number, but
what about other types of value? If a variable contains a list
it works a bit differently. Use square brackets
to create a list
Change list A
2 Change the value in
>>> listA[1] = 1000
“listA[1]” to 1,000. “listB[1]” >>> print("listA =", listA, "listB =", listB)
now contains 1,000 as well. listA = [1, 1000, 3] listB = [1, 1000, 3]
Changing the original list has
changed the copy of the list too. The second item of
This is the third both “listA” and “listB”
item in the list has been changed
Change list B
3 Change the value of
>>> listB[2] = 75
“listB[2]” to 75. “listA[2]” is now >>> print("listA =", listA, "listB =", listB)
75 as well. Changing the copy listA = [1, 1000, 75] listB = [1, 1000, 75]
of the list has changed the
original list as well. The third item of both “listA”
and “listB” has been changed
‹ 130–131 Functions
Making 158–159 ›
Variables created inside a function (local variables) shapes
and variables created in the main program
(global variables) work in different ways. Local variables are like film stars
in a car with mirrored windows—
they are inside the car (function)
Local variables but no one can see them
Global variables
A variable created in the main program is
called a global variable. Other functions Global variables
can read it, but they can’t change its value. are like people
walking along the
street—everyone
can see them
>>> def func3(y): “y” contains the value >>> print(z) Prints the value in global
passed to it when variable “z” after “func3”
print(y) “func3” is called butter
has finished running
y = "bread"
print(y) Here “y” contains “bread” Local variable “y” of “func3” holds a
copy of the value in “z”. Although “y”
>>> z = "butter" has been changed to “bread”, the
This creates a global
>>> func3(z) value in global variable “z” isn’t
variable called “z”
affected and is still “butter”
butter The input “y” now contains
bread the value of “z” passed to it
when “func3” is called
EXPERT TIPS
Changing a
1 global variable
>>> c = 12345 Initial value
in global Calling functions
Global variable “c” is given >>> def func4(): variable “c”
There are two different ways of
the value 12345. “func4” c = 555
gives “c” the value 555
calling functions.
print(c)
and prints it out. It looks
like our global variable >>> func4() Prints the function(a)
“c” has been changed. value of “c”
555 In Python, items of data are called
inside “func4”
“objects.” Some functions are called
by passing them the data object (“a”).
Print variable
2 If we print “c” from
>>> print(c)
a.function()
outside the function, we 12345
see that “c” hasn’t changed Other functions are called by adding
at all. “func4” prints only The value in global their name at the end of the data
the value of its new local variable “c” hasn’t object (“a”) after a period.
variable—also called “c”. been changed
140 P L AY I N G W I T H P Y T H O N
PROJECT 6
Drawing machine SEE ALSO
‹ 122–123 Loops
in Python
It’s time to try a more complex project. This program, the
drawing machine, turns a string of simple instructions
Libraries 152–153 ›
into turtle commands to draw different shapes. The skills
used in planning this program are essential for any coder.
EXPERT TIPS
“do” isn’t “R”. N
Is it “U”?
Letter commands Y
do == U? penup()
The Turtle controller will use
Because “do”
these letters to stand for is “U”, the
different turtle commands: N If “do” isn’t a letter command
the function “penup()”
N = New drawing (reset) recognizes, it stops the
report unknown command
reports an error turtle from
U/D = Pen up/down
drawing
F = Forward
B = Backward
R = Right turn Once the After any command is
command is finished executed successfully,
L = Left turn return from function you return to the the program goes to
main program the end of the function
142 P L AY I N G W I T H P Y T H O N
DRAWING MACHINE
The Turtle controller
The first part of the program is a function that moves the turtle,
one command at a time. It is planned out in the flowchart on the
previous page. This code enables the turtle to convert the “do”
and “val” values into movement commands.
Loads all the commands
that control the turtle
DRAWING MACHINE
Creating the String artist
The pseudocode on the previous page plans a function called the
String artist, which will turn a string of values into single commands
that are sent to the Turtle controller. The next stage is to turn the
pseudocode into real Python code, using a function called “split()”.
The “split()” function splits a string into a list of This string lists the
6 smaller strings. Each break point is marked by a commands to create
the sample house shape
special character ( “-” in this program).
Now write out the pseudocode for the String artist Tells the program to split the string
7 using real Python code. Use the “split()” function to wherever it sees a “-” character
slice up the input string into turtle commands.
This makes the program loop
through the list of strings—each
def string_artist(program): item is one command for the turtle
cmd_list = program.split("-")
Gets the If the length of the command is 0 (so
length of the for command in cmd_list: the command is blank), the function
command string cmd_len = len(command) skips it and moves to the next one
if cmd_len == 0:
Checks if the Takes the first character of the command
command continue (remember, strings start at 0) and sets it
is followed by as the command type (“F”, “U”, etc.)
cmd_type = command[0]
more characters
(the number) num = 0
This takes all the remaining
if cmd_len > 1: characters from the command
Converts the by cutting off the first one
characters from num_string = command[1:]
strings into num = int(num_string)
numbers Prints the command on the
print(command, ":", cmd_type, num) screen so you can see what
the code is doing
turtle_controller(cmd_type, num)
>>> string_artist("N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100")
N : N 0 The turtle commands
Resets the screen and puts
L90 : L 90 are all separated by a “-”
the turtle back at the center
F100 : F 100
R45 : R 45 For command “F100”, the command
type is “F” and “num” is “100”
F70 : F 70
R90 : R 90
This makes the turtle turn 45
F70 : F 70 degrees before drawing the roof
R45 : R 45
This command makes the
F100 : F 100 turtle draw the right-hand
side of the roof
R90 : R 90
F100 : F 100
DRAWING MACHINE
Finish off the code with a user interface
The drawing machine needs an interface to make it easier to
use. This will let the user enter a string from the keyboard
to tell the machine what to draw.
This code creates a pop-up window where the user The triple quote (‘‘‘) tells Python
10 can input instructions. A “while True” loop lets them that everything until the next
triple quote is part of the same
keep entering new strings.
string, including the line breaks
N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100-B10-U-R90-F10-D-
F30-R90-F30-R90-F30-R90-F30
N-F100-L90-F200-L90-F50-R60-F30-L120-F30-R60-F40-R60-F30-L120-F30-
R60-F50-L90-F200-L90-F100-L90-U-F150-L90-F20-D-F30-L90-F30-L90-F30-
L90-F30-R90-U-F40-D-F30-R90-F30-R90-F30-R90-F30-L180-U-F60-R90-D-
F40-L120-F40-L120-F40
REMEMBER
Achievements
You created the drawing machine program Created the function “turtle_controller” that figures
by achieving several smaller targets: out what turtle command to execute from the letter
and number it’s been given.
Used a flowchart to plan a function by working out Created the function “string_artist” that produced
the decision points and the resulting actions. a turtle drawing from a string of instructions.
Wrote pseudocode to plan out a function before Made an interface that allows the user to tell
writing out the real code. the program what to draw from the keyboard.
148 P L AY I N G W I T H P Y T H O N
‹ 94–95 Errors
Programmers aren’t perfect, and most programs ‹ 122–123 Loops
in Python
contain errors at first. These errors are known as
“bugs” and tracking them down is called “debugging.”
What next? 176–177 ›
Types of bugs
Three main types of bugs can turn up in programs—syntax,
runtime, and logic errors. Some are quite easy to spot, while
others are more difficult, but there are ways of finding and
fixing them all.
This will cause an error Age cannot be less than 5
The Python keyword as no number can be and greater than 8 at the
is ”for” not “fir” divided by 0 same time, so no free tickets
Output
2 The answer for the program should
Sum of numbers 1 to 5 is 10
New output
4 The loop is adding only the numbers
DEBUG: n= 0 total= 0
Fix the
5 faulty line
top_num = 5
Correct output
6 The “print” command shows that
DEBUG: n= 1 total= 1
Insertion sort
Imagine you’ve been given your class’s exam papers to put
in order from the lowest to the highest mark. “Insertion
sort” creates a sorted section at the top of the pile and then
inserts each unsorted paper into the correct position. △ Sorting in order
“Insertion sort” takes each
▽ How it works When counting the paper in turn and inserts it into
“Insertion sort” goes through each positions, Python starts at 0 the correct (sorted) place.
of these stages sorting the numbers
far quicker than a human could. 0 1 2 3 4 5
6 is sorted into position 1 2 6 5 1 4 3
6 is more than 2, so is sorted
after 2 in the sorted section
Sorted! 1 2 3 4 5 6
4, 5, and 6 shuffle along to
make room for 3 in position 2
ALGORITHMS 151
Selection sort
“Selection sort” works differently to “insertion sort.” It swaps
pairs of items instead of constantly shifting all of the items.
Each swap moves one number to its final (sorted) position.
Swap the smallest value
with the first value
△ Swapping positions
Switching one thing with another
is usually quick and doesn’t affect
Swaps 1 and 2 2 6 5 1 4 3 anything else in the list.
Swaps 2 and 6 1 6 5 2 4 3
Swaps 5 and 6 1 2 3 4 6 5
The largest number is in last
position after the swap, so
no further swapping is required
Sorted! 1 2 3 4 5 6
EXPERT TIPS
Sorting in Python
There are lots of different sorting “a” is a list of
algorithms, each with different unsorted numbers
strengths and weaknesses. Python’s
“sort()” function uses an algorithm This calls
>>> a = [4, 9, 3, 8, 2, 6, 1, 5, 7] the “sort()”
called “Timsort,” named after its function
designer, Tim Peters. It’s based on >>> a.sort()
two sorting algorithms: “Insertion >>> a The numbers
sort” and “Merge sort.” Type in this [1, 2, 3, 4, 5, 6, 7, 8, 9] in list “a” are
code to see how it works. now sorted
152 P L AY I N G W I T H P Y T H O N
◁ Batteries
Standard Library modules included
Python comes with a “Standard Library” that has Python’s motto
lots of useful bits of code ready to use. Stand-alone is “batteries are
included.” This
sections of a library called “modules” can be added means it comes
to Python to make it even more powerful. with lots of ready-
to-use code.
◁ Random
This module can pick
a random number,
or shuffle a list into ▽ Turtle
a random order. This module is used to
draw lines and shapes
on the screen.
△ Time
The Time module gives the current
time and date, and can calculate
dates—for instance, what day will
it be in three days’ time?
▽ Tkinter
Tkinter is used to make buttons,
windows, and other graphics that
help users interact with programs. ▷ Math
Use the Math
module to work
with complex
mathematical
calculations.
△ Socket
The code in this module helps
computers connect to each other
over networks and the internet.
LIBRARIES 153
Importing modules EXPERT TIPS
Before using a module, you have to tell the computer Pygame
to import it so it can be used by your program. This
allows the bits of code it contains to be available to you. Pygame is a
Python library
Importing modules is done using the “import” command.
designed for
Python can import modules in a few different ways. writing video
games. Pygame
◁ “import random” gives you access to sound modules
import random This way of importing and special graphics that can be
requires you to type the used in games. You’ll be able to
module name at the start of use Pygame once you have a good
random.randint(1, 6) the code. It makes it easier understanding of the basics of
random.choice(my_list) to read because you know Python covered in this book.
which module it came from.
This creates a
Tkinter window
EXPERT TIPS
2 Press the button to
roll the die
Tk
Clear and simple
Run the program, then click the
button to roll the die and see the When you’re designing a GUI, try
result. This program can be simply 6 not to confuse the user by filling
changed so that it simulates a the screen with too many buttons.
12-sided die, or a coin being tossed. Label each button with a sensible
Press to roll!
name to make the application
A new number appears here easy to understand.
each time the button is clicked
156 P L AY I N G W I T H P Y T H O N
‹154–155 Making
windows
Pictures and graphics on a computer screen are
made up of tiny colored dots called pixels. To
Making 158–159
shapes
›
create graphics in a program, the computer needs Changing 160–161 ›
to be told exactly what color each pixel should be. things
Choose a color
2 The “color chooser” window will
appear. Pick the color you want and
then click the “OK” button.
Color values
3 When a color is selected, a list
((60.234, 190.742, 52.203), "#3cbe34")
Colored canvas
2 Run the code and the
Tk
(x1=50, y1=50)
100
Draw an alien
You can draw almost anything by combining different
shapes. Here are some instructions for creating an alien
using ovals, lines, and triangles.
window.title("Alien")
c = Canvas(window, height=300, width=400) Draws a green oval
c.pack() for the body
Draws a blue
triangle for
the alien’s hat
‹ 158–159 Making
shapes
Once a graphic has been drawn on the canvas, it doesn’t
need to stay the same. Code can be used to change the
Reacting to 162–163
events
›
way it looks, or move it around the screen.
Changing colors
You can make the mouth look as though
it is opening and closing by simply
changing the color of the oval.
Mouth open
Mouth
Write the code
1 Type this code to create two The function “itemconfig()” 2 Open and close
closed
functions that will make the mouth Type this code into the shell
changes the properties of
seem to open and close. shapes you’ve already drawn window to make the mouth open
and close.
def mouth_open():
>>> mouth_open()
c.itemconfig(mouth, fill="black")
>>> mouth_close()
def mouth_close(): The opened
mouth will Enter these commands
c.itemconfig(mouth, fill="red") be black to make the alien open
The closed mouth and close its mouth
The shape’s ID will be red
CHANGING THINGS 161
Hide and show ◁ Blinking alien
Shapes can be hidden using the “itemconfig()” To make the alien blink,
function. If you hide the eyeball, and then you need to hide the
pupil and make the
show it again a moment later, the alien looks white of the eye green.
as though it is blinking.
Saying things
Text can also be displayed on the screen to make I am an alien!
the alien talk. You can even make it say different
things in response to user commands.
Adding text
1 This code adds text to the Positions the text
graphic of the alien and creates a on the canvas
function to steal its hat.
‹ 158–159 Making
shapes
Computers receive a signal when a key is pressed or a
mouse is moved. This is called an “event.” Programs can
‹ 160–161 Changing
things
instruct the computer to respond to any events it detects.
Event names
Lots of different events can be triggered using
input devices like a mouse or keyboard. Tkinter
has names to describe each of these events.
Spacebar
pressed
<space> <KeyPress-a>
Mouse events
To make a program respond to mouse events, simply link Burp!
(or bind) a function to an event. Here, the function “burp”
is created, then bound to the “<Button-1>” event.
c.itemconfig(eye, fill="green")
c.itemconfig(eyeball, state=HIDDEN)
def unblink2(event):
Hides the
c.itemconfig(eye, fill="white") eyeball
c.itemconfig(eyeball, state=NORMAL)
c.bind_all("<KeyPress-a>", blink2)
c.bind_all("<KeyPress-z>", unblink2)
Shows the
eyeball a z
△ Make the alien blink
When this code is run, the “A” key
This code links This binds the function will make the eye close, and the
functions to events “unblink2” to the “Z” key “Z” key will make it open again.
def eye_control(event):
The eyeball moves
key = event.keysym up if the up arrow
key is pressed
if key == "Up":
c.move(eyeball, 0, -1)
The eyeball
elif key == "Down": moves left if the
c.move(eyeball, 0, 1) left arrow key
is pressed
elif key == "Left":
c.move(eyeball, -1, 0)
elif key == "Right": Activates the
function
c.move(eyeball, 1, 0) “eye_control” △ Eyeball control
when any key The eyeball moves in the direction
c.bind_all("<Key>", eye_control)
is pressed of the pressed arrow key.
164 P L AY I N G W I T H P Y T H O N
PROJECT 7
Bubble blaster SEE ALSO
‹154–155 Making
windows
This project uses all the skills taught in this chapter
to make a game. It’s a big project, so tackle it in stages
‹ 156–157 Color and
coordinates
and remember to save the program regularly. Try to ‹ 158–159 Making
understand how each part fits together before moving shapes
and the submarine IDLE File Edit Shell Debug Window Help
Draws a red
ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill="red")
circle outline
ship_id2 = c.create_oval(0, 0, 30, 30, outline="red")
SHIP_R = 15 The radius (size) of the submarine.
BUBBLE BLASTER
Controlling the submarine
The next stage of the program is to write the code that makes the
submarine move when the arrow keys are pressed. The code will
create a function called an “event handler.” The event handler
checks which key has been pressed and moves the submarine.
x coordinate gets
smaller going left
▷ How it works
The “move_ship” function moves the
sub in different directions. Adding to
the sub’s x and y coordinates moves
Don’t forget to it right and down, while subtracting y coordinate gets x coordinate gets
save your work from them moves it left and up. larger moving down larger going right
BUBBLE BLASTER 167
BUBBLE BLASTER
Make the bubbles move
There are now lists to store the ID, size, and speed of the bubbles,
which are randomly generated. The next stage is to write the code
that makes the bubbles move across the screen. Goes through each
bubble in the list
This function will go
def move_bubbles():
5 through the list of
bubbles and move for i in range(len(bub_id)):
each one in turn. c.move(bub_id[i], -bub_speed[i], 0)
window.update()
Removes bubbles that
are off the screen sleep(0.01)
BUBBLE BLASTER
Figuring out the distance between points
In this game, and lots of others, it is useful to know the distance
between two objects. Here’s how to use a well-known mathematical
formula to have the computer work it out.
Loads the “sqrt” function
from the Math library
This function calculates Gets the position
from math import sqrt
11 the distance between two of the first object
objects. Add this bit of def distance(id1, id2): Gets the position of
code directly after the x1, y1 = get_coords(id1) the second object
code you wrote in step 9.
x2, y2 = get_coords(id2)
return sqrt((x2 - x1)**2 + (y2 - y1)**2)
This variable keeps This loop goes through the entire list of bubbles (it
track of points scored goes backward to avoid errors when deleting bubbles)
def collision():
points = 0
Checks for collisions
for bub in range(len(bub_id)-1, -1, -1): between the sub
and any bubbles
if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):
points += (bub_r[bub] + bub_speed[bub])
del_bubble(bub)
return points
score = 0
#MAIN GAME LOOP
while True:
if randint(1, BUB_CHANCE) == 1: Creates new bubbles
create_bubble()
move_bubbles()
clean_up_bubs() Adds the bubble
score to the total
score += collision()
print(score)
Shows the score in the shell
window.update() window—it will be displayed
sleep(0.01) properly later
EXPERT TIPS
Python shortcut Don’t forget to
save your work
BUBBLE BLASTER
Adding a few final touches
The main stages of the game are now working. All that remains
is to add the final parts: displaying the player’s score, and setting
a time limit that counts down until the game ends.
Type in this code after the code you entered in step Creates “TIME” and “SCORE”
14 12. It tells the computer to display the player’s score labels to explain to the player
what the numbers mean
and the time left in the game.
c.itemconfig(time_text, text=str(time_left))
Displays the
time remaining
Next, set up the time limit and the score required to gain
15 bonus time, and calculate the end time of the game. This
bit of code should come just before the main game loop.
Imports functions
from the Time library
from time import sleep, time
BUB_CHANCE = 10
Starts the game with a
TIME_LIMIT = 30 30-second time limit
BONUS_SCORE = 1000
SCORE
score = 0
Sets when bonus time is
bonus = 0 given (when a player has
scored 1,000 points)
end = time() + TIME_LIMIT
△ Scoreboard
Stores the finish time in Scoreboards are a great visual way to
a variable called “end” show players at a glance how well they
are doing in a game.
BUBBLE BLASTER 173
Don’t forget to
Displays the
save your work
time remaining
Don’t forget to
save your work
174 P L AY I N G W I T H P Y T H O N
BUBBLE BLASTER
Time to play
Well done! You’ve finished writing Bubble The player
blaster and it’s now ready to play. Run the scores points for
popping bubbles
program and try it out. If something isn’t with the sub
working, remember the debugging tips—
look back carefully over the code on the
previous pages to make sure everything Bubble Blaster
is typed out correctly. IDLE File Edit Shell Debug Window Help
The timer counts TIME SCORE
Up arrow key down to the end
Left
of the game 13 241
arrow key Down arrow key
Right
arrow key
△ Controls
The submarine is steered using the arrow
keys. The program can be adjusted so it
works with other controls.
EXPERT TIPS
Improving your game
All computer games start as a basic idea. They
are then played, tested, adjusted, and improved.
Think of this as version one of your game. Here
are some suggestions of how you could change
and improve it with new code:
◁ Super submarine
Now you can share this
game with your friends.
Take turns to see who can
score the most points.
Afterwards, show them
the code behind it and
explain how it all works.
176 P L AY I N G W I T H P Y T H O N
‹ 152–153 Libraries
Now that you’ve tackled the Python projects in this book, Computer 204–205
games
›
you’re on your way to becoming a great programmer.
Here are some ideas for what to do next in Python,
and how to take your programming skills farther.
Experiment REMEMBER
Play around with the code samples Read lots of code
in this book. Find new ways to remix
them or add new features—and Find interesting programs or
don’t be afraid to break them too! libraries written by other people
and read through the code and
This is your chance to experiment their comments. Try to understand
with Python. Remember that it how the code works, and why it is
is a professional programming built that way. This increases your
language with a lot of power—you knowledge of coding practices.
can do all sorts of things with it. You will also learn useful bits of
information about libraries that
you can use in future programs.
Build your own libraries
Programmers love to reuse code and share their
work. Create your own library of useful functions and
share it. It’s a great feeling to see your code being
used by another programmer. You might build
something as useful as Tkinter or Turtle!
W H AT N E X T ? 177
Make games EXPERT TIPS
with Python Different versions of Python
You could create your own game When you find code elsewhere (in other books or online), it
using Python. The PyGame may be written for a different version of Python. The versions
library, which is available to are similar, but you might need to make small changes.
download from the web, comes Python 2
with lots of functions and tools print "Hello World"
that make it easier to build
games. Start by making simple Python 3
print("Hello World")
games, then progress to more
complex ones.
Score 56
22
Basic elements
A computer consists of four main The memory contains
parts: input, memory, processor, and information in sections, Memory
like books on library
output. Input devices gather data, shelves. Memory is used
similar to the way your eyes or ears to store programs and
the data they use
collect information about the world
around you. Memory stores the data,
while processors examine and alter it,
just like a human brain. Output devices
show the results of the processor’s The control unit
retrieves programs
calculations, like a person speaking or from the memory in
moving after deciding what to do. order to run them
Keyboard
LINGO
GIGO
“Garbage in, garbage out” (“GIGO”
for short) is a computing phrase
The arithmetic logic
unit retrieves data for meaning that even the best
its calculations from programs will output nonsense
the memory if they receive the wrong input.
5>3=?
Printer
Screens provide
Screen Speaker
visual output
182 INSIDE COMPUTERS
1
a current
At the most basic level, computers understand only
two values: electrical signals that are “on” and “off.”
▷ 1 and 0
Because there are only two values, computers deal with A wire with ON
numbers using a base of two, or “binary.” Each digit is electrical signal
either a 1 or a 0, and each extra digit in the number “on” is a 1. A wire
is worth two times the previous digit.
Each extra digit is
with electrical
signal “off” is a 0. 0
worth twice as much
OFF
x2 x2 x2 x2 x2 x2 x2
128 64 32 16 8 4 2 1
◁ Binary
The range of
values that
can be written
doubles with
1 1 1 1 0 0 0 1
each digit added.
1 1 1 1 0 0 0 1
Binary numbers can be
F 1 241=F1
1111 in binary is
15, which is F in
0001 in binary is 1, which
hexadecimal
is 1 in hexadecimal
The number
in decimal
▽ Comparing base systems
REMEMBER
Using this table, you can see that expressing
numbers in hexadecimal gives the most Bits, nibbles, and bytes
information with the fewest digits.
A binary digit is known as a “bit,” and is the
DIFFERENT BASES smallest unit of memory in computing. Bits
Decimal Binary Hexadecimal are combined to make “nibbles” and “bytes.” A
kilobit is 1,024 bits. A megabit is 1,024 kilobits.
0 0 0 0 0 0
1 0 0 0 1 1
2 0 0 1 0 2 Bits: Each bit is a single
binary digit—a 1 or 0.
3 0 0 1 1 3
4 0 1 0 0 4 1
5 0 1 0 1 5
6 0 1 1 0 6 Nibbles: Four bits make up
a nibble—enough for one
7 0 1 1 1 7 hexadecimal digit.
8 1 0 0 0 8
1001
9 1 0 0 1 9
10 1 0 1 0 A
Bytes: Eight bits, or two
11 1 0 1 1 B hexadecimal digits, make up a
12 1 1 0 0 C byte. This gives us a range of
13 1 1 0 1 D values from 0 to 255 (00 to FF).
14 1 1 1 0 E
10110010
15 1 1 1 1 F
184 INSIDE COMPUTERS
‹ 180–181 Inside
a computer
Computers use binary code to translate numbers into
electrical signals. But how would a computer use binary
‹182–183 Binary
and bases
code to store the words and characters on this page?
ASCII
The first computers each stored characters in their own ASCII
unique way. This worked fine until data needed to be 32 SPACE 64 @ 96 `
moved between computers. At this point, a common 33 ! 65 A 97 a
system was chosen, called the American Standard Code 34 “ 66 B 98 b
for Information Interchange (ASCII, pronounced “askey”). 35 # 67 C 99 c
36 $ 68 D 100 d
▷ ASCII table 37 % 69 E 101 e
In ASCII, a decimal number value is 38 & 70 F 102 f
given to each character in the upper- 39 ‘ 71 G 103 g
and lower case alphabets. Numbers are 40 ( 72 H 104 h
also assigned to punctuation and other
41 ) 73 I 105 i
characters, such as a space.
42 * 74 J 106 j
43 + 75 K 107 k
44 , 76 L 108 l
▷ ASCII in binary
Because each character has a R = 82 = 1010010 45 - 77 M 109 m
number, that number then needs 46 . 78 N 110 n
to be converted to binary to be
stored in a computer. r = 114 = 1110010 47
48
/
0
79
80
O
P
111
112
o
p
49 1 81 Q 113 q
50 2 82 R 114 r
▽ ASCII in Python This command prints 51 3 83 S 115 s
You can convert between the character, the ASCII 52 4 84 T 116 t
ASCII and binary code in most value, and the binary
value for each letter in 53 5 85 U 117 u
languages, including Python.
the name “Sam” 54 6 86 V 118 v
55 7 87 W 119 w
>>> name = "Sam" 56 8 88 X 120 x
>>> for c in name: 57 9 89 Y 121 y
print(c, ord(c), bin(ord(c))) 58 : 90 Z 122 z
Here are the 59 ; 91 [ 123 {
results. The 60 < 92 \ 124 |
S 83 0b1010011 beginning of
each binary 61 = 93 ] 125 }
a 97 0b1100001
number is 62 > 94 ^ 126 ~
m 109 0b1101101 marked “0b” 63 ? 95 _ 127 DELETE
SYMBOLS AND CODES 185
Unicode
As computers across the world began to share data, the
limits of ASCII began to show. Thousands of characters
used in hundreds of languages had to be represented,
so a universal standard called Unicode was agreed on.
▷ Unicode characters
Unicode characters are
represented by their
hexadecimal value, which
appears as a series of
letters and numbers
(see pp.182–183). Each 2602 2EC6 08A2 0036
character has its own code.
More characters are added
all the time, and there are
some unusual ones, such
as a mini umbrella.
REMEMBER
▽ Unicode in Python
Hexadecimals Unicode can be used to display special characters
in Python. Simply type a string containing a Unicode
Hexadecimal numbers have a base of 16.
character code.
Ordinary decimal numbers are used for 0 to 9,
and the values 10–15 are represented by the Putting “\u” before the
hexadecimal code tells the
letters A to F. Each hexadecimal number has an computer this is Unicode
equivalent binary value.
The Unicode value The same value >>> "Zo\u00EB"
of ë as hexadecimal as binary
"Zoë"
‹ 180–181 Inside
a computer
Computers use electrical signals not only to understand
numbers and letters but also to make decisions using
‹182–183 Binary
and bases
devices called “logic gates.” There are four main types
of logic gates: “AND,” “NOT,” “OR,” and “EXCLUSIVE OR.”
AND gate
Gates use one or more input signals to produce an output signal,
based on a simple rule. AND gates switch their output signal “on” (1)
only when both input signals are “on” (1 and 1).
1 1 0
1 0 0
1 0 0
REAL WORLD
NOT gate
These gates “flip” any input
George Boole (1815–64)
to its opposite. “On” input George Boole was an English
becomes “off” output, and mathematician whose work made
“off” input turns to “on” logic gates possible. He worked
output. NOT gates are also out a system to solve logic
known as “inverters.” 1 0 problems. This kind of math,
which deals in values that can
only be true or false (positive or
△ Input 1 = output 0
negative), is known as “Boolean
logic” in his honor.
The NOT gate flips an “on” input to
an “off” output, and vice versa.
L O G I C G AT E S 187
OR gate
An OR gate produces an “on” output when either
one of the inputs is “on,” or when both are “on.”
1 1 0
1 1 0
1 0 0
EXCLUSIVE OR gate
This type of gate only gives 1 1
an “on” output when one
input is “on” and the other is
“off.” Two “on” or two “off”
0 1
inputs will produce an “off”
output. Gates like this are 1 0
also known as “XOR” gates.
△ Inputs 1 and 1 = output 0 △ Inputs 1 and 0 = output 1
Two “on” inputs produce The output is “on” only when
an “off” output. the inputs are different.
EXPERT TIPS
Building computer circuits
By combining these four basic with two NOT gates in a loop,
logic gates, you can create circuits you can create a circuit that
to perform a whole range of will store a bit of data (a single
advanced functions. For example, 1 or 0). Even the most powerful
by linking an AND gate to an computers are based on
XOR gate, you create a circuit that billions of tiny logic circuits.
can add two binary digits (bits)
Computer chips contain
together. By linking two OR gates many logic circuits
188 INSIDE COMPUTERS
‹ 180–181 Inside
a computer
Inside a computer are many types of electronic chips.
Most importantly, the processor chip runs programs
‹186–187 Logic
gates
and memory chips store data for instant access.
The processor
Processors are a collection of very small and complex circuits, printed on
a glasslike material called silicon. Small switches called transistors are
combined to form simple logic gates, which are further combined to form
complex circuits. These circuits run all the programs on your computer.
◁ Circuits in
a processor
The circuits are kept
synchronized by a
clock pulse, just like
an orchestra is kept in
time by a conductor.
Machine code
Save to
Processors understand only a set of memory
program instructions called “machine
code.” These simple instructions for
operations like adding, subtracting,
and storing data are combined to
create complex programs. Call another
piece of code
REMEMBER
Processing information
The processor and memory, when
combined with input and output MEMORY
devices, give you everything you Contains the
need for a computer. In a game position of the A game program
character running
program, for example, the user
inputs position data by clicking The character
the mouse, the processor does the Mouse click jumps on screen
calculations, reads and writes
memory, and then produces output
in the form of making the character
INPUT PROCESSOR OUTPUT
jump on the screen.
190 INSIDE COMPUTERS
‹ 180–181 Inside
a computer
There are a few programs that every computer
needs in order to work. Some of the most important
‹182–183 Binary
and bases
programs are operating systems, compilers, ‹188–189 Processors
and interpreters. and memory
Operating system
The operating system (OS) is the
This program has run
manager of the computer’s and is now waiting Each program has its
resources. It controls which for its next slice of own space in the
programs are allowed to run, how processor time computer’s memory
off
Programs run in turn
Program
▷ How it works Memory
3
The processor’s time is
divided up into slices. A
program will be given a off
slice. If it can’t finish in
that time, it is paused and This program is
the next program runs. waiting to run
ESSENTIAL PROGRAMS 191
input data
Compilers and Compiler
interpreters output output
Program Run program
The languages you write Program Run compiler in machine in machine
programs with, such as code code
output data
Links to monitor
Links to keyboard
Links to speaker
Links to mouse
Links to printer
Links to network
‹182–183 Binary
and bases
A computer’s memory doesn’t just store numbers and
characters. Many more types of data can be stored,
‹188–189 Processors
and memory
including music, pictures, and videos. But how is this ‹190–191 Essential
data stored? And how can it be found again? programs
EXPERT TIPS
▽ File information
File sizes There is more to a file than just its
contents. File properties tell the system
Files are essentially collections of
everything it needs to know about a file. Right-click on a file to see
data in the form of binary digits properties such as file
(bits). File sizes are measured in type, location, and size
the following units:
FILE PROPERTIES
The file name
Bytes (B) should be
1 B = 8 bits (for example, 10011001) memorable name groove
The location of
Gigabytes (GB) the file on the
computer full directory
1 GB = 1,024 MB = 1,073,741,824 B /Users/Jack/Music
path
The file size
Terabytes (TB) (see the box on
the left) size 50 MB
1 TB = 1,024 GB = 1,099,511,627,776 B
S T O R I N G D ATA I N F I L E S 193
Directories EXPERT TIPS
It’s easier to find files on a computer system if they are Managing files
well organized. To help with this, files can be grouped
together in “directories,” also known as “folders.” It’s A file manager program helps find files
and directories. Each operating system
often useful for directories to contain other directories has a different one:
in the form of a directory tree.
Windows: Use Windows Explorer to
▽ Directory tree look around the directory tree.
When directories are placed inside other Apple: Use Finder to look around the
directories, it creates a structure that resembles directory tree.
an upside-down tree, and just like a tree it has Ubuntu: Use Nautilus to look around
roots and branches (confusingly called “paths”). the directory tree.
This “path”
This “path”
contains Sara’s
contains Jack’s
user data
user data
Jack’s Sara’s
folder folder
Music Photos
story.txt film.mpg
‹182–183 Binary
and bases
The internet is a network of computers all across the
world. With so many computers, clever systems are
‹ 192–193 Storing data
in files
needed to make sure information goes to the right place.
IP addresses
Every computer or phone connected to the internet has an address,
much like a building. The addresses are called “Internet Protocol (IP)
Packets are put
addresses” and each one is made up of a series of numbers. back together in
the right order
▽ Sending information
Receiving computer
Files travel between computers in accepts packets
small chunks called packets. Special
computers called routers forward
these packets to their destination.
Sending
computer
transmits data
5 7 8 Routers
deliver
6
packets like
EXPERT TIPS mailmen to
the correct
Sockets 9 10 11 addresses
△ C++
alert(‘Hello World!’);
Based on C, but with extra
features. Used in programs
that need to be fast, such
as console games.
△ Objective-C
Based on C, with some extra △ JavaScript
features. It has become popular Used to create
because of its use on Apple’s programs that run on
class HelloWorldApp { Mac and iOS devices. web browsers, such
public static void main(String[] args) {
as simple games and
System.out.println(“Hello World!”);
} email websites.
} <?php
echo “Hello World!”;
?>
△ Java ◁ PHP
A very versatile language that Mostly used for creating
can run on most computers. interactive websites, PHP
It’s often used for coding on runs on the web servers
the Android operating system. that host websites.
COMPUTER LANGUAGES 199
Languages from the past REAL WORLD
Many languages that were famous twenty or thirty years Millennium bug
ago have fallen in popularity, despite still being used in
some very important systems. These languages are often Many programs in older languages
like COBOL used two digits to
seen as difficult to code by modern standards.
represent a year (such as 99 for
1999). The “millennium bug” was
BASIC
Designed in 1964 at Dartmouth College, in the predicted to cause problems in
US, BASIC was very popular when home
2000 when these dates rolled over
computers first became available.
into the new millennium as 00.
Fortran
Designed in 1954 at IBM, a technology firm, Fortran the world had to be
is mainly used for calculations on large computers. updated to prevent
It is still being used in weather forecasting. the millennium bug
COBOL
Designed in 1959 by a committee of experts,
COBOL is still being used in many business and
banking programs.
△ Ook!
△ Chef Designed to be used by
A program written in Chef is orangutans, Ook! has only three
△ Piet meant to resemble a cooking elements: “Ook,” “Ook!”, and
Programs created in Piet code look recipe. However, in practice, “Ook?” These can be combined
like abstract art. The “Hello World!” the programs rarely produce to create six commands, such
program is shown above. useful cooking instructions. as “Ook! Ook” and “Ook? Ook!”
200 PROGRAMMING IN THE REAL WORLD
‹ 18–19 Becoming
a coder
Computing is driven forward every day by millions of
programmers all around the world, but every now and
Computer 204–205
games
›
then someone special comes along and takes a massive
leap. Here are a few of the most famous coders.
A l a n Tu r i n g
A d a L o v e la ce Nationality
: British
sh
Nationalit y: Briti Dates: 191
2–54
Gu np ei Yo ko i an d Sh ig er u M iy am Ti m B e rn e rs -L e e
ot o
Nationalit y: Japanese Nationalit y: British
nt
Dates: Yokoi 1941–97, Miy
amoto 1952–present Dates: 1955–prese
working at
Famous for: Yokoi and Famous for: While
s sc ientific
Miyamoto worked for CERN (a famou
er in Switzerland),
Nintendo, the gaming research cent
vented
company. Yokoi Tim Berners-Lee in
invented the Game wi de we b,
the world
Boy, while Miyamoto ad e it fre e fo r
and m
made successful games ever yo ne . He wa s
n
such as Super Mario. knighted by Quee
04 .
Elizabeth II in 20
S e r g e i B r in Ma rk Zu ck erb erg
L ar r y Page and
Nationality: American
merican
Nationalit y: A
Dates: 1984–present
73–present
Dates: Both 19
Op en So ur ce M ov em en t
Nationality: All
t
Dates: Late 1970s–presen
tion of
rce movement is a collec
Famous for: The open sou tw are should
world who believe sof
programmers around the be en responsible
all. The movement has
be free and available to h as the GNU/Linux
ces of software, suc
for many significant pie lin e en cyc lop edia.
kipedia, the on
operating system and Wi
202 PROGRAMMING IN THE REAL WORLD
‹180–181 Inside
a computer
Computers and programs have become an invisible
part of daily life. Every day, people benefit from very
‹
192–193 Storing
data in files
complex computer programs that have been written
to solve incredibly tough problems.
Secret codes
When you log in to a website,
buy something, or send a
message across the internet,
smart programs scramble your
secret data so that anyone who
intercepts it won’t be able to ◁ Cryptography
understand it. Global banking Cryptography is the
systems rely on these advanced study of codes. Complex
mathematical codes
programs capable of hiding
scramble and unscramble
secret information. personal data to keep it
safe from thieves.
BUSY PROGRAMS 203
Artificial Intelligence
Intelligent programs do more
than just make computer games
fun. Artificial Intelligence (AI)
is being used to provide better
healthcare, as well as helping
robots operate in places too
△ Medicine △ Bomb disposal
dangerous for humans to go,
Systems are able to analyze a Many soldiers’ lives can be
such as war zones and areas huge database of medical saved by using an intelligent
destroyed by natural disasters. information and combine it robot to safely dispose of a
with details from the patient bomb in an area that has been
to suggest a diagnosis. cleared of people.
1 Complex problem
is entered into 6 Final result appears
supercomputer much faster
△ How it works
Problems are broken into smaller problems that are all worked
on separately at the same time by different processors. The
results are then combined together to give the answer.
204 PROGRAMMING IN THE REAL WORLD
‹ 200–201 Coding
stars
What does it take to make a modern video game?
All computer games are a different mix of the same
Making 206–207
apps
›
ingredients. Great games are usually made by teams
of software developers—not just programmers.
△ Graphic designer
All of the levels and
◁ Level designer characters need to
The architects of the game’s look good. The graphic
virtual world, level designers designers define the
△ Coder create settings and levels structure and appearance
Programmers write the that are fun to play. of everything in the game.
code that will make the
game work, but they can
do this only with input
from the rest of the team. LINGO
▷ Tester Consoles
Playing games all
day may seem like a A console is a special type of
great job, but testers computer that is well suited to
often play the same running games. Consoles, such as
level over and over the PS4 and Xbox One, often have
again to check for bugs. advanced graphics and sound
processors capable of running
many things at once, making
△ Scriptwriter more realistic games possible.
Modern games have
interesting plots just like
great books and films. ◁ Sound designer
Scriptwriters develop Just like a good movie,
all the characters and a great game needs
stories for the game. to have quality music
and sound effects to
set the mood.
COMPUTER GAMES 205
Game ingredients
The most common ingredients in games are often combined
into a “game engine.” Engines provide an easy-to-use base so
that new games can be developed quickly.
◁ Game physics
In a virtual world, the rules of the
real world, such as gravity and
collisions, must be re-created to
make the game more believable.
△ Graphics
As games become more realistic their
graphics must become more complex.
Body movements, smoke, and water are
▷ Controls particularly hard to get right.
Familiar controls that make sense to
the player help make a great game.
Good control design makes the player
forget that they are using a controller. ▷ Sound
All of the words spoken in the
game must be recorded, as well
as the background music and
the sound effects that change
Open the pod bay
doors, Hal throughout the game.
I’m sorry Dave, I’m
afraid I can’t do that REAL WORLD
Serious games
Games are being used for
more than just fun. Pilots,
surgeons, and soldiers are just
some of the professionals
who use games at work for
△ Artificial intelligence training purposes. Some
Human players often play alongside or businesses even use strategy
against computer-controlled players. games to improve their
Artificial intelligence programming allows employees’ planning skills.
these characters to respond realistically.
206 PROGRAMMING IN THE REAL WORLD
‹190–191 Essential
programs
Mobile phones have opened up a world of possibilities
for coders. With a computer in everyone’s pocket, mobile
‹ 198–199 Computer
languages
apps can use new inputs, such as location-finding and ‹204–205 Computer
motion-sensing, to give users a better experience. games
What is an app?
“App” (short for “application”) is a word that describes
◁ Social network
programs that run on mobile devices, including
Social apps can allow
smartphones, tablets, and even wearable technology people to connect with
such as watches. There are many different categories friends, whether they are
of apps that do different things. nearby or far away, to
share thoughts, pictures,
◁ Games music, and videos.
All sorts of games are available on mobile
devices, from simple puzzle games to
fast-paced action adventures.
△ Travel
Travel apps use your location
combined with other users’ reviews
to provide recommendations for
restaurants, hotels, and activities.
△ Weather
Mobile apps use your location to
provide accurate weather forecasts,
and also allow you to check the
weather around the world.
◁ Sport △ Education
People use apps to track their fitness Educational apps are great for
when running or cycling, and can also learning. Young children can learn
keep up to date on the latest sports to count and spell, and older
scores while on the go. people can learn a new language.
MAKING APPS 207
How to build an app
There are many questions to answer before
building an app. What will it do? What devices will
it run on? How will the user interact with it? Once
these questions are answered, building an app
is a step-by-step process.
‹ 198–199 Computer
HTM L ◁ HTML
HTML (HyperText Markup
▷ JavaScript
JavaScript controls how the
Language) builds the basic page changes when you use
structure of the page, with it. Click on an email, for
different sections that instance, and JavaScript
contain text or images. makes a message open up.
PROGRAMMING FOR THE INTERNET 209
HTML <html> Blocks of text are surrounded by “tags,”
a very common feature in HTML code.
When you open a website, your <head> This tag gives the window a title
internet browser downloads an <title>The Hello World Window</title>
HTML file and runs the code to turn </head>
it into a web page. To see how it <body>
works, type the code here into an
<h1>Hello World in HTML</h1>
IDLE code window (see pp.92–93)
<p>Hello World!</p>
and save it as a file with the ending The “<p>” and “</p>”
“.html”. Double click the file and it </body> tags surround
ordinary paragraphs
will launch a browser window </html>
saying “Hello World!” This tag shows where
the HTML code ends
test.html JavaScript
interactive
features such
as buttons
Hello World!
Don’t forget to give your OK
filename an “.html” ending
210 PROGRAMMING IN THE REAL WORLD
‹ 162–163 Reacting
to events
JavaScript is great for creating mini programs that run
inside HTML, bringing websites to life and allowing users
‹ 122–123 Loops
in Python
to interact with them. Although it works like Python, ‹ 208–209 Programming
JavaScript code is more concise and trickier to learn. for the internet
Getting input
As with Python, you can use JavaScript to ask the user
for information. JavaScript can do this with a pop-up This line creates
a pop-up box and
box. The following program prompts the user to stores the text the
enter their name and responds with a greeting. user types into it
The text in quotes
appears in the box
Use a prompt
1 This short script
<script>
stores the user’s name in a var name = prompt("Please enter your name");
variable. Type the code into var greeting = "Hello " + name + "!";
the IDLE code window and
document.write(greeting);
remember to save it with a JavaScript lines
“.html” filename. </script>
always end with
a semicolon
The “</script>” tag shows This line displays
where the JavaScript ends the greeting
EXPERT TIPS
Loops in JavaScript
A loop is a section of code that repeats. Using
loops is much quicker and easier than typing
out the same line of code over and over again. Loop output
2 Save the code as a “.html” file and run
Loop code
1 Like Python, JavaScript uses “for” to set up a loop. The repeated
it. The loop keeps repeating as long as “x”
is less than 6 (“x<6” in the code). To
lines of code are enclosed in curly brackets. This loop creates a simple increase the number of repeats, use a
counter that increases by one each time it repeats. higher number after the “<” symbol.
‹ 194–195 The
internet
Not all programs are fun games or useful apps. Some
programs are designed to steal your data or damage
‹202–203 Busy
programs
your computer. They will often seem harmless, and
you might not realize that you have been a victim.
Malware
Programs that do things without your knowledge or
permission are known as “malware.” Unauthorized
access to a computer is a crime, but there are many
different types of programs that still try to sneak on
to your computer.
▷ Worm
A worm is a type of malware that crawls around a
network from computer to computer. Worms can clog
up networks, slowing them down—the first worm
brought the internet to a virtual standstill in 1988. △ Virus
Just like a virus in the human body,
this malware copies itself over and over
again. They are usually spread through
emails, USB sticks, or other methods of
transferring files between computers.
REAL WORLD
Famous worm
On May 5, 2000, internet users in the Philippines
received emails with the subject “ILOVEYOU.” An
attachment appeared to be a love letter, but was
actually a piece of malware that corrupted files.
◁ ILOVEYOU
This worm quickly spread
△ Trojan to computers around the
Malware that pretends to be a harmless program is world. It is estimated to
known as a “trojan.” The word comes from a ruse used have cost more than $20
in the Trojan War: the Greeks gave the Trojans a giant billion to fix the damage
wooden horse, with soldiers hidden inside. By breaching it caused.
the Trojan defenses without detection, they won the war.
BAD PROGRAMS 213
What malware does
Viruses, worms, and trojans are all types
of malware that are created to get into your
machine, but what do they do once they
have infected their target? They might
delete or corrupt files, steal passwords,
or seek to control your machine for
some larger purpose as part of an
organized “zombie botnet.”
▷ Zombie botnets
Botnets are collections of infected
computers that can be used to send
spam emails, or flood a target website
with traffic to bring it crashing down.
‹ 180–181 Inside
a computer
Computers don’t have to be big or expensive. A wide
range of small and cheap computers are available.
‹202–203 Busy
programs
Because of their small size and low cost, these computers
are being used in lots of new and exciting ways.
Raspberry Pi
The Pi is a credit-card-sized computer, created to teach the basics
of how computers work. For its size it is impressively powerful,
with the ability to run similar programs to a modern PC. LED lights show
the Pi is working
Audio output for
headphones or speakers Two USB connectors for
a mouse, a keyboard, or
Video output for any other add-ons
older TVs
Network connection
Removable memory to access the internet
card stores operating
systems, programs,
and data HDMI video output—to
connect to modern TVs
Power connector
REAL WORLD
Home-built robots
With their small size, cost, and Robotic spider controlled
by the Arduino
weight, mini computers are
being used more and more to
build different types of robot.
For example:
◁ Be nosy
Read websites and books about
programming and try out other
people’s code. You’ll pick up
expert tips and tricks that might
have taken you years to figure
out on your own.
△ Steal ideas
If you come across a great program, think how you
might code it yourself. Look for clever ideas to use
in your own code. All the best programmers copy
each other’s ideas and try to improve them.
REMEMBER
Have fun!
Coding is a lot like trying to solve puzzles.
It’s challenging and you’ll often get stuck.
Sometimes it’s frustrating. But you’ll also
have breakthroughs when you solve a
problem and feel a buzz of excitement
at seeing your code work. The best way to
keeping coding fun is to take on challenges
that suit you. If a project is too easy you’ll
get bored; if it’s too hard you’ll lose interest.
Never be afraid to fiddle, tinker, experiment,
and break the rules—let your curiosity lead
you. But most of all, remember to have fun!
218 REFERENCE
Glossary
algorithm call event GUI
A set of step-by-step To use a function in a Something a computer The GUI, or graphical user
instructions followed program. program can react to, such interface, is the name for
when performing a as a key being pressed or the buttons and windows
task: for example, by a compression the mouse being clicked. that make up the part of
computer program. A way of making data the program you can see
smaller so that it takes execute and interact with.
ASCII up less storage space. See run.
“American Standard hacker
Code for Information computer network file A person who breaks
Interchange”—a code used A way to link two or more A collection of data stored into a computer system.
for storing text characters computers together. with a name. “White hat” hackers work
as binary code. for computer security
container float companies and look for
binary code A part of a program A number with a decimal problems in order to fix
A way of writing numbers that can be used to point in it. them. “Black hat” hackers
and data that uses only store a number of break into computer
0s and 1s. other data items. function systems to cause harm or
A piece of code that does to make profit from them.
bit data part of a larger task.
Information, such as hardware
A binary digit—0 or 1.
The smallest unit of text, symbols, and gate The physical parts of a
digital information. numerical values. Used by computers to computer that you can
make decisions. Gates see or touch, such as wires,
Boolean expression debug use one or more input the keyboard, and the
To look for and correct signals to produce an display screen.
A question that has only
two possible answers, such errors in a program. output signal, based on
a rule. For example, “AND” hexadecimal
as “true” and “false”.
debugger gates produce a positive A number system based on
branch A program that checks output only when both 16, where the numbers 10
other programs for errors input signals are positive. to 15 are represented by
A point in a program where
in their code. Other gates include “OR” the letters A to F.
two different options are
available to choose from. and “NOT”.
directory index number
bug A place to store files to GPU A number given to an
keep them organized. A graphics processing item in a list. In Python,
An error in a program’s
unit (GPU) allows images the index number of the
code that makes it behave
encryption to be displayed on a first item will be 0, the
in an unexpected way.
computer screen. second item 1, and so on.
A way of encoding data so
byte that only certain people
can read or access it. graphics input
A unit of digital
information that Visual elements on a Data that is entered into
contains eight bits. screen that are not text, a computer: for example,
such as pictures, icons, from a microphone,
and symbols. keyboard, or mouse.
GLOSSARY 219
Index
Page numbers in bold refer bits 183, 189, 218 in strings 114 comments, adding 143
to main entries. black-hat hackers 213 Unicode 185 comparison blocks/operators
blank lines 117 Chef 199 62–3, 118–19
blocks circles, drawing 157, 158 compass 39
A
Ada 18
colored 31
connecting 18
creating 72–3
circuits, computer 187, 188, 189
clicking, and events 44, 66, 162
clock pulse 188
compilers 191
components, computer 181, 217
compression 202, 218
addition 52, 102, 112 defining 72, 73 coordinates computer circuits 187, 188, 189
AI see Artificial Intelligence functions of 31 drawing with 158 computer games see games
algorithms 16, 17, 150–1, 218 help with 83 and location 168 computer languages see
Allen, Paul 200 with inputs 73 and movement 166 programming languages
ALU see arithmetic logic unit programming 22 in Python 157 computer programmers see
American Standard Code for types of 31 in Scratch 56–7 coders
Information Interchange see blocks palette 27, 31, 32, 35, 38, COBOL 199 computer programs 14–15
ASCII 50 code 22, 23 algorithms 16, 17
“and” block/operator 63, 103, bomb disposal 203 building 27 bad programs 212–13
118, 119 Boole, George 186 and colored blocks 30–1 essential 190–1
AND gate 186 Boolean expressions 62, 63, 64, flow of 30 experimenting with 19
Android operating system 198, 65, 111, 118–19, 120, 218 pausing 69 how they work 15
207 botnets, zombie 213 in Python 101 uses of 14
anti-malware software 213 brackets repeating 68 computers
antivirus programs 213 errors 94 running 30 deconstructing 217
apostrophes 115 in lists 128, 129 in Scratch 30–1, 101 invention of 201
Apple Mac in tuples 134 and sprites 28 main parts of 180–1
file management 193 using 112, 119 stopping 30, 68 mini 214–15
operating system 190, 207 brain, training 216 testing 30 supercomputers 203
programming languages branches/branching 65, 99, 100, code area 27 console games 198
198 120–1, 218 Code tab 27 consoles 14, 204
Python 3 on 88, 90 breaks, inserting in loops 126–7 code windows 92, 93, 106–7 containers 134, 218
Scratch on 25 Brin, Sergei 201 errors in 94 “continue” keyword 127
apps, making 206–7 broadcast blocks 70–1, 77 coders 14, 15 “Control” blocks 31, 65, 68
Arduino 214, 215 browser windows 210, 211 becoming a coder 18–19 control unit 180
arithmetic logic unit (ALU) 181 Bubble blaster project 164–75 becoming a master controls, game 174, 205
arrow keys 163, 166 bugs 148–9, 177, 207, 218 programmer 216–17 costumes 40–1
Artificial Intelligence (AI) 203, buttons famous 200–1 and movement 23, 40, 41
205 creating 152, 154–5 and games 204 random 61
ASCII 184, 218 labelling 155 think like a computer 16–17 Roll the die project 60–1
audio output 181, 215 linking to events 162 coding and speech bubbles 41
bytes (B) 183, 192, 218 clear 143 switching 34, 40, 41
computer programs 14–15 cryptography 202
B
Babbage, Charles 200 C
reading 176, 216
what is coding? 14–19
coding clubs 82, 207
CSS (Cascading Style Sheets) 208
cursor tools 26
lists megabytes (MB) 183, 189, 192 nested loops 47, 69, 123 position
adding/deleting items 55, 105, memory 180–1, 188–9, 190, network adaptors 181, 195 coordinates 56–7
128, 129, 169 192, 219 networks, computer 152, random 43, 57
combining 129 messages 194, 218 “print()” function 87, 101, 102,
commands 105 reacting to 70 nibbles 183 108, 109, 116, 117, 130
copying 137 sending and receiving 70 NOT gate 186 printers 181
creating 55, 105 microphones, and events 44, 45 notes, musical 59 processors 100, 101, 180–1,
in loops 129 Microsoft 200 numbers 188–9, 190, 203, 219
playing with 55 Microsoft Windows binary and bases 182–3 program flow 100–1
putting tuples in 134 file management 193 comparing 62, 118 programming languages 15, 18,
in Python 128–9, 132–3 operating system 190, 207 data types in Python 110 19, 22, 49, 83, 198–9, 219
in Scratch 54–5 Python 3 on 88, 89 random 53, 104, 113, 152, 155 conversion into machine code
using 55, 129, 167 Scratch on 25 188
in variables 136–7 millennium bug 199 first 200
local variables 138, 139
logic circuits 187, 188, 189
logic errors 148
mini computers 214–15
Miyamoto, Shigeru 201
mobile phones 14, 204, 215
O
Objective-C 198
from the past 199
and interpreters 191
learning new 217
logic gates 186–7, 188, 189 apps 206–7 Ook 199 popular 198
logical operators 118–19 modules 219 open source movement 201 Python and Scratch commands
LOGO 49 importing 153 operating systems (OS) 25, compared 102–5
“Looks” blocks 31, 40, 42–3 Standard Library 152 88–91, 92, 190–1, 207, 219 text-based 86
loop blocks 46 Monkey mayhem project 74–81 operators 219 weird 199
loops 100, 103, 219 motherboard 181 blocks 31, 52, 53 programs see computer
complex 68–9 “Motion” blocks 31, 32, 33, 34, 36, logical 118–19 programs
with conditions 104 38–9, 57, 75 “or” block/operator 63, 103, 118 projects 11, 23
escaping 126–7 motion detector, webcam 45 OR gate 187 Bubble blaster 164–75
“for” 122, 124 mouse OS see operating systems Drawing machine 140–7
forever 46, 47, 69, 103, 125 control 25 output Escape the dragon! 32–7
in JavaScript 211 events 162, 211 and branching 120–1 Ghost game 96–9
lists in 129 input function 180, 189 devices 180, 181, 189 Monkey mayhem 74–81
main 99, 168, 169, 171 mouse-pointer logic gates 186–7 remixing existing 82
nested 69, 123 coordinates 56 program 31, 92, 100, 101, Roll the die 60–1
in Python 122–7, 133 following 69 106, 108, 116–17, 180–1 Silly sentences 132–3
in Scratch 46–7, 68–9 pointing toward 32, 33, 36 PS4 204
simple 46–7 movement pseudocode 143, 144, 147
skipping 124, 127
stopping 125
variable 123
coordinates 57
and costumes 23, 40, 41
with keys 66, 163, 166
P
packets 194, 195
Pygame 153, 177
Python 19, 83, 84–177
algorithms 150–1
while 124–5 and “Sensing” blocks 66, 67 Page, Larry 201 ASCII in 184
Lovelace, Ada 200 sprites 22, 23, 38–9, 57 painting area 60, 61 Booleans 111
low-level languages 191 Mpegs 193 passwords, theft of 213 branching 120–1
multiplication 52, 102, 112 paths 193 Bubble blaster project 164–75
music “Pen” blocks 31, 48–9, 87, 107 bugs and debugging 148–9
M
Mac see Apple Mac
adding 37, 79
files 192, 193, 202
making your own 59
Peters, Tim 151
photograph files 193
Pi 214
code structure 98–9
color and coordinates 156–7
color codes 107
macOS 190 playing 59 pictures, files 192, 193 different versions of 177
machine code 188, 191, 219 tempo 59 Piet 199 Drawing machine project
Malbolge 199 mutable/immutable objects 129 pilots 205 140–7
malware 212–13, 219 Pixar 86 errors 94–5
Math module 152 pixels 156 escaping loops 126–7
math
in Python 102, 112–13
in Scratch 52–3, 102
N
name errors 95
player’s name 50
PNGs 193
pop-up boxes/windows 146,
functions 130–1, 132–3
Ghost game project 96–9
harder commands 104–5
MATLAB 18 NASA 86 209, 210 input and output 116–17
medicine 203 negative numbers 56, 57 ports 195, 219 installing 88–91
INDEX 223
introducing IDLE 92–3 Random module 152, 153, 157 make some noise 58–9 sound library 79
libraries 152–3 random numbers 53, 104, 113, making things move 38–9 sounds 22, 23
lists 128–9, 132–3 152, 155 math in 52–3 adding to program 58–9, 79
lists in variables 136–7 random positions 43, 57 menu and tools 26 detectors 45
loops in 122–7, 133 Raspberry Pi 25, 214 and microphones 45 in games 205
making decisions 118–19 reacting to events 162–3 Monkey mayhem project playing 58
making games with 177 readable code 133 74–81 selecting from library 37, 58
making shapes 158–9 remainders 53 pens and turtles 48–9, 87 volume control 58
making windows 154–5 repeat loops 46, 122, 211 and Python 87, 102–5, 124, 125 spam 213
math in 112–13 “repeat until” block 68, 76, 77, and Python’s Ghost game 101 speakers 181
numbers in 110 78, 124 Roll the die project 60–1 speech bubbles 22, 28, 87, 101
print in 87 rewriting code 217 sending messages 70–1 adding 41, 161
program flow 100–1 robots 16, 203, 217 sensing and detecting 66–7 conversations 71
reacting to events 162–3 home-built 215 simple commands 102–3 speed, setting 51, 77
saving work 88 Roll the die project 60–1 simple loops 46–7 “split()” function 144
and Scratch 87, 101, 102–5, rotation software 24 sprites 22, 23, 28–9, 39, 219
124, 125 styles 38 special effects 42–3 adding graphic effects 43
code blocks 101 tools 61 sprites 28–9 adding more 76–7, 80
shell and code windows 92, routers 194, 195 strings and lists 54–5 adding sounds 58–9
93, 106–7 Ruby 18 true or false 62–3 changing size 43
shortcuts 171 running typical programs 23 changing time or speed 35, 51
Silly sentences project 132–3 programs 23, 102, 106 understanding 22 coordinates 56–7
simple commands 102–3 code blocks 30 variables 50–1, 108 collisions 67
sorting in 151 runtime errors 148 versions of 25 communication between
strings in 110, 114–15, 117 and webcams 45 70–1
tuples and dictionaries 134–5 website 24, 82 controlling 31, 66
turtle graphics 87
types of data 110–11
Unicode in 185
S
saving your work 11
what is Scratch? 18, 22–3
screens 181
scriptwriters 204
copying or deleting 29
creating and editing 29, 34, 36
designing your own 39
variables 99, 101, 108–9, 116 in Python 88, 93, 106, 107 SD cards 215 direction 39
variables and functions 138–9 in Scratch 24, 25, 33 secret data 202 and events 44–5
website 89 saying things (in Python) 161 selection sort 151 hiding and showing 42
what is Python? 19, 86–7 score 50, 79, 99, 172–3 “Sensing” blocks 31, 34, 36, 51, in the interface 28
what next? 176–7 scoreboards 172 65, 66–7, 75 movement 22, 23, 38–9, 57,
while loops 124–5 Scratch 20–83 separators 117 66–7
account 24 servers 219 naming 29
adding sounds 58–9, 79 shapes pen tools 48–9
Q
questions
backpack 82
blocks 30–1, 72–3
colored blocks and code
adding color 159
drawing 140
making 158–9
renaming 29
rotation styles 38
and code blocks 28
asking 54 30–1, 101 moving 160 selecting from library 34, 36,
combining 63 complex loops 68–9 naming 160 39, 75, 76
true or false 62–3 coordinates 56–7 shell windows 92, 93, 106–7, 116 and “Sensing” blocks 66–7
quote marks costumes 40–1 errors in 95 sprite list 27
errors 94 creating blocks 72–3 silicon chips 188, 189 turtle graphics 49
in lists 128 decisions and branches 64–5 Silly sentences project 132–3 and variables 35, 50–1
in strings 110, 114, 116 Escape the dragon! project skipping, in loops 127 what they can do 28
32–7 slicing 115 square roots 53
events 44–5 smartphones 206 stage 23, 25, 27
R
radio waves 195
experimenting with 82–3
harder commands 104–5
help menu 83
social apps 206
Socket module 152
sockets 195, 219
Standard Library modules 152
stop button 30
stopping programs 102
RAM 189 hide and seek 42–3 software 14, 15, 219 strategy games 205
“randint()” function 98, 99, 101, installing and launching 24–5 sorting algorithms 150–1 strings 219
104, 113, 130, 153, 155 interface 26–7, 49 “Sound” blocks 31, 58–9 adding 114
Random Access Memory see RAM lists 55 sound designers 204 assigning 108
224 REFERENCE
T washing machines 14
watches 206
tablets 25, 206
tabs 26, 27
teleporting 43
V
values
wearable technology 206
weather forecasting 199, 203,
206, 215
television 215 assigning to variables 108, web browsers 86, 195, 198
tempo 59 109, 113, 118, 136 web servers 198
terabytes (TB) 192 changing 136 webcams, and events 44, 45
testers, game 204 in dictionaries 135 websites
text editors 88 and functions 131 construction 208–9
text files 193 variables 35, 219 email 198, 208
text messages 14 assigning a value to 108, 109, interactive 198, 208, 210, 211
text-based programming 113, 118, 136 Python 89
languages 86 changing contents of 109 Scratch 24, 82
time limit 172–3 comparing 62, 63, 118 while loops 124–5
Time module 152 creating 50, 54, 77, 102, 108 white-hat hackers 213
Tkinter module 152, 154–5, 156, deleting 51 Wikipedia 201
157, 158, 159, 162, 165, 176 and functions 138–9 Windows
transistors 188 global 138, 139 see Microsoft Windows
travel apps 206 lists in 136–7 windows
Trojans 212, 213, 219 local 138, 139 code and shell 92, 93, 106–7
true or false 62–3, 64, 111, loop variables 123 making 152, 154–5, 165
118–21, 125 naming 50, 109, 143 word processing 86
tuples 134, 219 in Python 99, 101, 108–9, 116, words, comparing 63
Turing, Alan 200 138–9 world wide web 201
turtle graphics 49, 87, 105, 107 read-only 51 worms 212, 213
Acknowledgments
DORLING KINDERSLEY would like to thank: Max Albert for technical Scratch is developed by the Lifelong Kindergarten Group at MIT
assistance on the US edition; Vicky Short, Mandy Earey, Sandra Perry, Media Lab. See http://scratch.mit.edu
and Tannishtha Chakraborty for their design assistance; Olivia
Stanford for her editorial assistance; Caroline Hunt and Steph Lewis Python is copyright © 2001–2013 Python Software Foundation; All
for proofreading; Helen Peters for the index; and Adam Brackenbury Rights Reserved.
for creative technical support.