Help Your Kids With Computer Coding PDF
Help Your Kids With Computer Coding PDF
C 0m Uter
p
CoDing
A UNIQUE STEP-BY-STEP VISUAL GUIDE,
FROM BINARY CODE TO BUILDING GAMES
HELP YOUR KIDS WITH
C 0m Uter
p
CoDing
HELP YOUR KIDS WITH
C 0m Uter
p
CoDing
A UNIQUE STEP-BY-STEP VISUAL GUIDE,
FROM BINARY CODE TO BUILDING GAMES
LONDON, NEW YORK, MELBOURNE,
MUNICH, AND DELHI
DK LONDON
Editor Sam Priddy
Designer Fiona Macdonald
Additional editors Sam Atkinson,
Lizzie Davey, Daniel Mills, Ben Morgan
US editor Jill Hamilton
Additional designer Simon Murrell
Managing editor Paula Regan
Managing art editor Owen Peyton Jones
Senior producer, pre-production Ben Marcus
Senior producer Mary Slater
Jacket editor Maud Whatley
Jacket designer Laura Brim
Jacket design development manager Sophia MTT
Publisher Sarah Larter
Art director Phil Ormerod
Associate publishing director Liz Wheeler
Publishing director Jonathan Metcalf
DK INDIA
Senior art editor Devika Dwarkadas
Editors Suefa Lee, Neha Pande
Art editors Sanjay Chauhan,
Shreya Anand Virmani
Assistant art editor Vanya Mittal
DTP designer Sachin Gupta
Managing editor Rohan Sinha
Deputy managing art editor Sudakshina Basu
Pre-production manager Balwant Singh
Jacket designer Suhita Dharamjit
Senior DTP designer Harish Aggarwal
DR. JON WOODCOCK M.A. (OXON) has a degree in Physics from the University of
Oxford and a Ph.D. in Computational Astrophysics from the University of London. He
started coding at the age of eight 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.
SEAN MCMANUS learned to program when he was nine. His first programming
language was Logo. Today he is an expert technology author and journalist. His other
books include Scratch Programming in Easy Steps, Web Design in Easy Steps, and Raspberry
Pi For Dummies. Visit his website at www.sean.co.uk for Scratch games and tutorials.
CLAIRE QUIGLEY studied Computing Science at Glasgow University where she obtained
a B.S. and a Ph.D. She has worked in the Computer Laboratory at Cambridge University
and on a project that aimed to develop computational thinking skills in primary school
pupils. She is a mentor at CoderDojo Scotland, a coding club for young people.
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 be
two objects. Add this bit of code direct
the code you wrote in step 9.
42 S TA R T I N G F R O M S C R AT C H
38–39 Making
things move
Scripts can be used to change the size of a
sprite and add special effects to it.
from the dr
menu. The
effect makes
becom
Welcome to the special effects studio! Using the purple
“Looks” blocks, find out how to make sprites vanish and
Sending 70–71
messages
Type in positive numbers
to make sprites bigger
reappear, grow and shrink, and fade in and out. and negative numbers
change size by 10 to make them smaller change
Each line of
Now update the main game loop to use the
e between points 13 functions you have just created. Remember that
code is clearly
s useful to know the distance the order is important, so make sure you put labeled so
o use a well-known mathematical everything in the right place. Then run the code.
k it out. Bubbles should burst when they hit the sub. you can’t
Check the shell window to see the score.
go wrong
etween
score = 0
ly after
Loads the “sqrt” function #MAIN GAME LOOP Sets the score to zero
from the Math library when the game starts
while True:
Creates new bubbles
Gets the position of if randint(1, BUB_CHANCE) == 1:
the first object
create_bubble()
d1) Gets the position of
the second object
Gives back the distance
move_bubbles() Adds the bubble
d2) between them score to the total
clean_up_bubs()
**2 + (y2 - y1)**2)
score += collision()
print(score)
window.update() Shows the score in the shell
window—it will be displayed
H I D E Big
g bubbles. A N bubbles
D SEEK 43 sleep(0.01) properly later
ators” block
ndom
When to save
This block
position selects a random
vertical position
Read on and
This save icon appears
ck random -150 to 150
get coding! on the project spreads. It
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 they
Becoming 18–19
a coder
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:
forever
move 10 steps
go to mouse pointer ▾
turn
15 degrees
15 degrees
move 10 steps
point towards ▾
glide 1 secs to x: 0 y: 0
programming languages.
Stage
1 backdrop Sprite 1 Sprite 2
New backdrop:
Backpack
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 scripts to
3 Objects such as people, vehicles, Sprites like me can be
programmed to talk
make new computer programs.
and animals can be added to a program. in speech bubbles.
These objects are called sprites. Scripts
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 place in an area on the screen called the “stage.” The red button
stops a program
Background images and sprites can be added to the stage,
and you can write scripts to make things happen. The green flag
runs a program
▷ Running a program
Untitled
Starting a program is
by abcd (unshared)
called “running” it. To
run a program in Scratch,
click the green flag above
the stage.
Background image
▷ Scripts make
REMEMBER
sprites move
when clicked
Scratch contains blocks Scratch programs
that can be used to make forever
scripts. This script makes In Scratch, when you save your
the shark bounce around next costume work it is called a “project.” A
the screen. The “next project includes all the sprites,
costume” block makes it wait 0.25 secs backgrounds, sounds, and scripts
open and close its mouth you’re working with. When you
with each movement. move 10 steps load a project again later,
everything will be where it was
if on edge, bounce
The “forever” block when you saved it. A Scratch
keeps the sprite project is a computer program.
moving endlessly
24 S TA R T I N G F R O M S C R AT C H
▷ 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 works well on
automatically saves work for you. To find Windows, Ubuntu, and Mac operating
your work, click your username at the top systems. It needs Adobe Flash software, Ready?
right of the screen and click “My Stuff.” though, so it won’t work on some tablets. Let’s go!
▽ Experiment
Scratch interface Click the buttons and tabs to
explore and experiment with
the Scratch interface. The
This is Scratch’s screen layout, or “interface.” projects that follow explain
The stage is on the left and programs are how to use them.
created on the right.
Click for full Change Menu Cursor
screen view language options tools
CURSOR TOOLS
Click on the tool you want to use,
and then click on the sprite or
script that you want to use it on.
Copy a sprite or script.
x: 153 y: -61
Enlarge a sprite.
Stage
1 backdrop Sprite 1 Sprite 2 Sprite 3
Shrink a sprite.
New backdrop:
Motion Events
Looks Control Select different Current
types of blocks sprite
Sound Sensing x: -126 selected
y: 96
Pen Operators
Data More Blocks
when clicked
Position
forever of the
move 10 steps
current
go to mouse-pointer ▾
sprite on
turn 15 degrees move 10 steps the stage
Blocks snap
turn 15 degrees
together—use the
mouse to move
point in direction 90 ▾ them around
forever
go to mouse-pointer ▾
Backpack
26–27 Scratch
interface
Sprites are the basic components of Scratch. Every Scratch
program is made up of sprites and the scripts that control
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.
other sprites and the user of the program. Here are a few
things sprites can do:
Motion Events
Looks Control
Sound Sensing x: -126
y: 96
Pen Operators
Data More Blocks
when clicked
forever
move 10 steps
go to mouse-pointer ▾
turn 15 degrees move 10 steps
turn 15 degrees
on them go to x: 0 y: 0
play sound pop ▾ until done
x: 153 y: -61
go to mouse-pointer ▾
Sprites New sprite:
glide 1 secs to x: 0 y: 0
Backpack
can have lots of scripts.
SPRITES 29
Creating and editing sprites
Games are more exciting when there are more sprites
to hit, dodge, or chase each other around the stage.
It’s simple to create, copy, and delete sprites.
The sprite’s
Spike new name
x: 84 y: -69 direction: -90° appears in
rotation style: the sprite list
can drag in player:
show: Spike
30 S TA R T I N G F R O M S C R AT C H
26–27 Scratch
interface
Functions of blocks
Different types of blocks do different things ▽ Motion, looks, sound, and pen
in programs. Some of them make sprites These blocks control what a sprite does on
screen—this is called the output of a program.
move, some manage sounds, and some
Pick a sprite and try each block to see what it does.
decide when things happen.
This block
▽ Events and sensing turn 15 degrees rotates the
Brown “Events” blocks make things sprite
happen. Light blue “Sensing” blocks
detect information about the keyboard,
mouse, and what a sprite is touching. think Hmm... for 2 secs
This block
shows a
thought
when clicked bubble
Detects when play sound meow ▾
the green flag This block
is clicked plays a sound
recording
key space ▾ pressed? pen down
Checks whether This block draws a line
the spacebar as a sprite moves
is pressed
COLORED BLOCKS AND SCRIPTS 31
▽ Data and operators ▽ Control
Orange “Data” blocks and green The “Control” blocks make decisions about
“Operators” blocks store numbers when blocks run. They can be programmed
and words and do things with them. to repeat instructions.
Stores a number
in a variable
set age ▾ to 10 forever
This makes the
Chooses a blocks inside it run
random number on loop (forever)
pick random 1 to 10
Flow of scripts
When a program runs, Scratch carries out the
instructions on the blocks. It starts at the top
of the scripts and works its way down.
is running
when clicked Press this
button to stop a
wait 2 secs program
PROJECT 1
Click the blue “Motion” button in the blocks palette. Click the “Events” button in the blocks palette. Drag
3 The blue “Motion” commands will appear. Drag the 4 the “when green flag clicked” block into the scripts
“point toward” block into the scripts area and drop it area. Join it to the top of your script.
inside the “forever” block. Click the black arrow in
This block snaps to
the block and choose “mouse-pointer.” the top of the script
Click the drop-down when clicked The menu shows
menu and select “mouse-pointer”
forever “mouse-pointer” forever has been chosen
mouse-pointer
ESCAPE THE DRAGON! 33
Click the “Motion” button again, and drag the “move The picture behind the sprites is called a backdrop.
6 10 steps” block into the scripts area. Drop it inside 7 To the left of the sprite list is a button to add a
the “forever” block. Click the green flag button so backdrop from the library. Click it, then select the
the cat chases the mouse-pointer! “Space” theme from the list. Click the “stars” image
and then click the “OK” button at the bottom right.
when clicked
Stage
forever 1 backdrop
Choose backdrop
point towards mouse-pointer ▾ from the library
New backdrop:
move 10 steps
move 10 steps
forever
through space.
point towards mouse pointer ▾
turn 15 degrees move 10 steps
turn 15 degrees
point in direction 90 ▾
point towards ▾
go to x: 0 y: 0
x: 153 y: -61
go to mouse pointer ▾
Sprites New sprite:
glide 1 secs to x: 0 y: 0
Above the sprite list is a button to add a sprite from Add this script to the dragon sprite. Click the
8 the library. Click it, choose the “Fantasy” category 9 color-coded buttons in the blocks palette to select
from the menu on the left, and select “Dragon.” Click the blocks below, then drag the blocks into the
the “OK” button in the bottom-right of the screen. scripts area. The dragon will now chase the cat.
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 script. Click the number 11 second script to the scripts area. The “wait until”
boxes in the block and change them to -200 and block is found in the “Control” section, and the
-150. Click the purple “Looks” button and add the “touching” block is in the “Sensing” section. The
“switch costume to” block to your script. dragon now breathes fire when it touches the cat.
Use the menu to
Place this block choose “Sprite1”
when clicked here to make the when clicked (the cat)
dragon start in
go to x: -200 y: -150 the corner wait until touching Sprite1 ▾ ?
Type in the variable name “Time” and make sure The variable name and the number in it appear
13 the “For all sprites” button is selected underneath, 14 on the stage in a small box. Right-click it and
then click “OK.” This means that the cat, dragon, choose “large readout.” This shows just the
and any other sprites can use the variable. number in the box.
OK Cancel hide
go to mouse-pointer ▾
Sprite 1
The donut
is now your
selected sprite
Select the cat in the sprite list so its script Click the green flag button to run the program.
18 appears. Click the menu in the “point toward 19 Press the mouse button and the donut moves
mouse-pointer” block. Change it 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.
Donut
Dragon
Now add some music. Click the “Sounds” tab Select the “drip drop” sound and click the
20 above the blocks palette. Each sprite has its 21 “OK” button at the bottom-right. The sound
own sounds, and they are managed here. is added to the cat sprite, and appears in
Click the button on the left to add a sound the “Sounds” area.
from the library.
“Sounds” tab
when clicked
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 scripts, 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, Co-ordinates 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.
First steps
1 Drag the “move 10
move 10 steps
steps” block from the Click the white window on
“Motion” section of the the block and type in a
blocks palette and drop it different number to change
into the scripts area to its how far the cat moves
right. Each time you click Add this block to tell
the block, the cat moves. Scratch when to start The “forever” block
running the script repeats anything
Keep on moving inside it endlessly
2 Drag a yellow
when clicked
“forever” block from the
blocks palette and drop forever EXPERT TIPS
it around the “move 10
steps” block. Click the move 10 steps Rotation styles
green flag on the stage
to run the program. The Find the cat in the “Sprites” list in
cat moves until it hits the bottom left of the screen. Click
the edge of the stage. Try changing the “i” button in the top left of the
10 to 30 to make frame. Here you’ll find a button to
Bouncing the cat sprint! change the cat’s rotation style—so
3 Drag an “if on edge, when clicked
it doesn’t walk around on its head!
bounce” block inside your
“forever” block. Now the forever The cat faces the direction
cat bounces when it hits it’s walking in, sometimes
the edge of the stage. The move 10 steps upside down.
cat is upside down when
it walks to the left. if on edge, bounce The cat faces left or right, and
is always the right way up.
This block makes the cat
turn around when it hits
The cat doesn’t rotate at all.
the edge of the stage
MAKING THINGS MOVE 39
Which direction? The direction -90°
means “left”
0°
The cat is now marching left and right across the screen.
It’s possible to change the cat’s direction, so it walks up
and down, or even diagonally. The “Motion” blocks can -90° 90°
be used to make a game of cat and mouse.
Click the block to make
the cat change direction Select or type in a new
number to change the 180°
Heading the direction of the cat
4 right way △ Compass
Drag the “point in direction” point in direction 45 ▾ Directions are measured in
block into the scripts area degrees, from 0° at the top.
and open its drop-down (90) right You can use any number
menu. There are four between -179° and +180°.
directions to choose from. (-90) left
The drop-down
Or, click on the number in menu gives you The cat will follow
(0) up the mouse-pointer
the window and type in a four options
new direction. (180) down
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.
Costumes tab
costume1
93x101
One of the
2
cat’s costumes
Different costumes
1 Click the “Costumes” tab to see the cat’s costume2
costumes. They show the cat with its legs and 89x101
arms in two different positions.
if on edge, bounce
The colors remind
you where to find
the blocks
COSTUMES 41
The green flag starts
Dancing ballerina the ballerina’s dance
Now try making a ballerina dance. Add
the ballerina sprite from the library. Select when clicked
your cat in the sprite list and drag its forever
script on to the ballerina in the sprite list.
Sprite 1
This copies the script to the ballerina. next costume
△ Ballerina’s script
The same script 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 script 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 sprite list.
Click the “i” button on it to open
forever the information panel. There you
This block hides can also use the “show” tick box
wait 1 secs the cat to show or hide a sprite.
hide
This block rotates
turn 90 degrees the cat clockwise Sprite1
x: 84 y: -69 direction: -90°
move 100 steps rotation style:
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
A script can be added to a sprite that makes it do What is an event?
something if the sprite is clicked while the program
is running. Experiment with different blocks to see An event is something that
happens, such as a key being
what a sprite can do when clicked.
pressed or the green flag being
Drag this block
from the “Events” clicked. The blocks that look for
menu to start events go at the top of a script.
the script The script waits until the event
when this sprite clicked happens, and then it runs.
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 when video motion ▾ > 40
with Scratch too. Add this script to the play sound meow ▾ until done
cat, and when you wave at it through
the webcam, it will meow back. △ Detect motion
Use the “when loudness > 10” block. Click the menu
to change “loudness” to “video motion.” The script 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 left of the screen, and hide
then add the “when backdrop switches Hides the sprite when
to backdrop1” 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 “Dinosaur1” REMEMBER
sprite to a new project and build it this script. 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 dinosaur 1-d ▾ you add more blocks, the jaws
stretch to make room for them.
wait 0.5 secs The sprite stands 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 dinosaur 1-d ▾
The previous
dance move repeat 3
(see opposite)
move 20 steps
The dinosaur
moves three
steps to the right wait 1 secs
This block creates
repeat 3 a short pause
44–45 Events
Each sprite has a pen tool that can draw a line 46–47 Simple loops
behind 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.
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
clear
Clears the pen trail
50 S TA R T I N G F R O M S C R AT C H
Click here to
create a variable
Tick to show the The variable block can be
variable on the stage used inside other blocks
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 variable.” You’ll lose known as sensing blocks.
any information that was in it.
Tracks the distance to
distance to ▾
something, such as the
Make a Variable
Variables can mouse-pointer.
be renamed
Make a List Reports the number of
here
costume # the costume a sprite is
steps wearing.
rename variable
Tells you which direction
direction a sprite is travelling in.
delete 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 “Operator” blocks.
Doing sums
There are four “Operator” 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 sec
◁ Switching costumes
switch costume to pick random 1 to 3
This script 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
Create a new variable
Working with words 1 Click the “Data” button in the blocks palette
Programs often need to remember words, and click the “Make a Variable” button. Create a
such as a player’s name. Variables can be variable called “greeting”.
created to remember these words. Scratch
programs can also ask the user questions,
which they answer by typing into a text Make a Variable
box that pops up. The following script asks Make a List Name your
variable “greeting”
for the user’s name, and then makes a
sprite say “Hello” to them. greeting
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.
–120
when clicked
Upload a recording
Record a sound using from the computer
the computer’s
microphone
Use this menu to choose between This block adds a silent break in the
different types of drum music. Higher numbers will give you
a longer break
EXPERT TIPS
Playing music Tempo
Connecting notes together makes a tune. Create a new
variable called “note” (see pages 50–51), and then add The speed of music is called its
the script below 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 bpm
set note ▾ to 1 Choose an instrument
The tempo is measured in beats per
set instrument to 1▾ Add a “forever” minute, or “bpm.”
loop around these
forever two blocks
change tempo by 60
change note ▾ by 1
Increase the tempo to make your
play note note for 0.5 beats music faster, or use a negative number
to make it slower.
Drag the “note” variable
from the “Data” section
of the blocks palette tempo
△ Rising scale
This script makes a series of notes that play when the green Checking this box makes the sprite’s
flag is clicked. The pitch of each note gets higher one step tempo show on the stage.
at a time, and each note plays for half a beat.
60 S TA R T I N G F R O M S C R AT C H
PROJECT 2
40–41 Costumes
Simple programs can be both useful and fun. 46–47 Simple loops
This program creates a dice that can be rolled. 50–51 Variables
Play it to see who can get the highest number, 52–53 Math
or use it instead of a real dice when you play
a board game.
Select the paintbrush button Click the rectangle button on the left of the
1 under the stage to draw a 2 painting area. To make your dice colorful, select a
new sprite. solid color from the palette (see box below). Then
in the painting area hold down the “shift” key,
New sprite: press the left mouse button, and then drag the
mouse-pointer to make a square in the middle.
Draws a
The rectangle button
new sprite
makes a square when
the “shift” key is pressed
EXPERT TIPS
Changing colors
Under the painting area are the Click for outline Click for block Currently
color controls. Click the solid of block of solid color selected color
rectangle to draw a block of
solid color. Click the empty
rectangle to draw an outline
of a square or rectangle. Use the
slider to change the thickness
of the square’s lines. To choose
a color, simply click it.
Sometimes you’ll roll the same number twice, and it looks like This block selects
a random costume
6 the program isn’t working because the image doesn’t change. This
script makes the dice change costumes five times before it stops.
Each time you press the spacebar, it looks like it’s rolling.
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 “Data” 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 a script 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 any key. You can also link actions to the mouse down?
click of a mouse button. △ “Sensing” blocks
Putting everything inside a Adding these blocks into an “if-then” block
“forever” block means the
allows the program to detect if a mouse
script 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 script
This script lets you move sprites
up, down, left, or right using the
arrow keys on the keyboard.
SENSING AND DETECTING 67
Use this block to identify when a sprite
Sprite collisions 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 only happen 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.
Stop! This stops all scripts This stops only the script
in a program this block is in
Another useful “Control”
block is the “stop all” block, stop all ▾ This stops the sprite’s other
scripts, but continues to run
which can stop scripts from the script this block is in
all
running. It’s useful if you
want to stop sprites from this script ◁ Stopping scripts
moving at the end of a game. Use the drop-down menu to
other scripts in sprite
choose which scripts to stop.
COMPLEX LOOPS 69
◁ Waiting blocks
Waiting wait 1 secs
The “wait secs” block waits
It’s easier to play a game or see what’s a set amount of time. The
going on in a program if you can make a wait until “wait until” block responds
script pause for a moment. Different to what’s happening in
the program.
blocks can make a script wait a number
of seconds or until something is true.
Sprite waits 5 seconds when clicked Sprite waits until
and then says something the mouse button
is pressed
forever
when clicked
wait until mouse down?
wait 5 secs
go to mouse-pointer ▾
say I’m tired of waiting
As soon as the
△ ”wait secs” block condition is true, the
With the “wait secs” block you can △ ”wait until” block sprite moves to the
enter the number of seconds you This block waits until the Boolean mouse-pointer
want a sprite to wait. expression in it is true.
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
broadcast message1 ▾
Broadcasting
This block starts a script when
The broadcast blocks in the “Events” menu a sprite receives a message
enable sprites to send and receive messages.
Messages don’t contain any information other when I receive message1 ▾
than a name, but can be used to fine-tune a △ Broadcast blocks
sprite’s actions. Sprites only react to messages One type of broadcast block lets a sprite send a message.
that they are programmed to respond to— The other tells the sprite to receive a message. Choose an
they ignore any other messages. existing message or create a new one.
say How are you? for 2 secs say Hi! for 2 secs
broadcast howareyou ▾
The “howareyou”
message starts the
third script
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.
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
sprite 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
Make sure you add scripts to the
1 backdrop library. This button is Stage
correct sprite.
found to the left of the sprite list. 1 backdrop
Follow the instructions carefully.
Remember to make a variable before
Click here to add a New backdrop: using it.
new backdrop from Check that all the numbers in the
the backdrop library blocks are correct.
Double-click on a
backdrop in the backdrop
library to make it appear
on the stage
M O N K E Y M AY H E M 75
Monkey1
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
Name the
The next step is to add a flying bat and make it drop
New Variable new variable
6 to the ground if it’s hit by the bananas. Add “Bat2” “Speed”
from the sprite library, then create a new variable Variable name: Speed
called “Speed” (for the bat sprite only). To create a This variable
new variable, first click the “Data” button in the For all sprites For this sprite only will only be
blocks palette, and then select the “Make a Variable” used with the
Cloud variable (stored on server)
button. Untick the box by the “Speed” variable in the bat sprite
“Data” section so it doesn’t appear on the screen.
OK Cancel
Add the below script to the bat. In the main “forever”
7 loop, the bat moves to a random position on the left
of the stage, chooses a random speed, then moves
backward and forward across the stage until the bananas
hit it. When the bat is hit, it drops to the ground.
MONKEY MAYHEM
Create a new variable called “Time”. Make sure it’s
The finishing touches 8 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 ticked, 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
Add this short script to the bananas sprite. Add this script to the bananas sprite too. When the
12 It sets the score to 0 at the beginning 13 bananas hit the bat, it plays a sound, increases the
of the game. 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
play sound pop ▾ (see pp.58–59)
This resets the score
change Score ▾ by 10
MONKEY MAYHEM
Time to play Make up a new To make the game last
Now the game is ready to play. Click the title for the game longer, try increasing
and type it in the time limit
green flag to start and see how many
times you can hit the bat with the
bananas before the time runs out. Untitled
by abcd (unshared)
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 sprite list and select “duplicate”. A new bat
will appear with all the same scripts as the first
one. Try adding some other flying sprites:
Score 0
◁ 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
Block help
1 To find out more about a particular
block, click the “block help” button on the
when left arrow ▾ key pressed
cursor tools bar at the top of the screen.
The help
window explains turn 30 degrees
?
every block
This is the “block
help“ button
Ask a question 30°
2 The cursor will turn into a
The cursor
becomes a
question mark. Use this to click on question mark
the block you want to know about.
turn 15 degrees
?
Type in the number of degrees you want the
sprite to rotate.
Help window
3 The help window opens to
(If you type in a negative number, the sprite will
go in the opposite direction.)
tell you how the block works, with
tips on how it can be used.
▷ 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
print(‘Hello World!’)
when clicked
Type the message
say Hello World! you want here
Hello World!
The message appears
on screen like this
Hello World!
△ Print in Scratch △ Print in Python
In Scratch, the “say” block is used to show In Python, a command called “print” displays
something on the screen. text on the screen.
move 10 steps
for n in range(24):
Moves the sprite
forward forward(10)
turn 15 degrees Turns the
right(15)
turtle clockwise
Turns the sprite
penup() 15 degrees
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 PY 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.3
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.3.3 Mac OS X 64-bit... (for Mac OS X 10.6 and later)
Don’t worry about the • Python 3.3.3 Mac OS X 32-bit... (for Mac OS X 10.5 and later)
exact number, as long as
it has a 3 at the front This version runs
on most Macs
Install Run IDLE
3 Double-click the .dmg file. A window 4 During installation, click “next” at each prompt to
will open with several files in it, including accept the default settings. After installation ends, open
the Python installer file “Python.mpkg”. the “Applications” folder on your Mac and open the “Python”
Double-click it to start the installation. folder (make sure you select Python 3, not Python 2).
Double-click “IDLE” to check the installation worked.
IDLE icon
Python.mpkg
Python
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.
Class Browser
Path Browser
INTRODUCING IDLE 93
Enter the code
3 In the new code window, type in print(‘Hello World!’)
this text. It’s an instruction to write the
words “Hello World!” Use single
quote marks
“Save As”. Enter the file name “HelloWorld” Untitle New Window
and click “Save”.
prin Open
Open Module
Recent Files
Class Browser
If you get an error message,
check your code carefully
Path Browser
to make sure you haven’t
made any mistakes.
Close
Save Copy As
menu and select “Run Module”. This will HelloWorld Python Shell
run the program in the shell window.
print(‘Hello World!’) Check 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
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 Python.
Program 100–101
flow
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 only # Ghost Game This sets up the “randint”
command, which generates
run once—at the beginning from random import randint random numbers
of the game. They set up
the title, variables, and the print(‘Ghost Game’)
The “print” command
“randint” command. feeling_brave = True displays text when
the game is run
score = 0
This resets the
score to 0
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
2 This loop tells the story while feeling_brave: This selects a
random number
and receives the player’s guess. ghost_door = randint(1, 3) between 1 and 3
It keeps on going as long as there
isn’t a ghost behind the door print(‘Three doors ahead...’)
that’s picked. When a ghost print(‘A ghost behind one.’) The “print”
appears, the “feeling_brave” command displays
variable changes to “False” and print(‘Which door do you open?’) the text onscreen
the loop stops repeating. door = input(‘1, 2 or 3?’)
This line asks for
door_num = int(door) the player’s answer
Branching part
3 The program takes a
if door_num == ghost_door:
This branch runs
different path depending on print(‘GHOST!’) if there’s a ghost
whether or not there was a behind the door
feeling_brave = False the player picks
ghost behind the door that was
picked. If there was a ghost, the else: If there’s no ghost, the
“feeling_brave” variable is set to print(‘No ghost!’) player sees this message
“False” but if not, the player’s
score increases by one. print(‘You enter the next room.’)
score = score + 1
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 2.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 2.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
or subprogram
jump() jump
Call a function
greet(‘chicken’) greet chicken
or subprogram
HARDER COMMANDS 105
Command Python 3 Scratch 2.0
Length of
a string
len(name) length of name
Create an
empty list
menu = list() Make a List
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 for
longer pieces of code
Code vs Shell ◁ Shell window
The shell window is perfect for
quick experiments, such as
because they can be saved 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.
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.
The string
in quotes
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
You can’t divide by zero,
into the shell window. The “print()” function is not needed so you’ll always get an error
for this—Python gives the answer straight away. Try these if you try to do so.
examples in the shell window:
△ 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 quotation marks
indicate the variable
contains a string
▷ Strings in variables
Variables can store strings. >>> a = ‘Run! ’
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
The variables “a” and “b”
out the length of a string. Python
>>> c = a + b counts all of the characters,
combine to become
>>> print(c) variable “c” including spaces, to give the total
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)
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
Using input Output in the shell window
1 A program can prompt the
after the colon
makes the output 2 When the program is run, the message
look tidier
user what to type. The message is “Enter your name: ” and its response appear in
put inside the brackets of “input()”. the shell window.
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
Dave-is-12 12
△ Hyphenate the outputs The character △ Outputs on new lines
A hyphen can be put between the variables between the The space or character between the outputs
outputs
when they’re printed. Other characters, is called a “separator” (“sep”). Using “\n” prints
such as “+” or “*”, can be used too. each output on a new line.
Period added
>>> print(a, end=‘.’) as an “end”
end sep
character
Dave.
△ Add a period to the output
A period can be added as another string to be
printed, but it will print with a space before it.
To avoid this, use “end=‘.’” instead.
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 >>> toys = 10 This checks whether
“toys” is equal to 1
“Less than”
>>> toys == 1
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.
Prompts users
what to type in
“if” condition
1 This code asks the user ans = input(‘Is it your birthday? (y/n)’)
if it’s their birthday. It checks if ans == ‘y’: This part of the
whether the answer is “y”. If so, program only runs
a birthday message is printed. print(‘Happy Birthday!’) if the user types “y”
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)’)
prints a special message for New if ans == ‘y’: Remember the colon This message only
Year. It shows a different message appears if the
if anything else is entered. print(‘Happy New Year!’) user enters “y”
print(‘Time for Fireworks.’)
else: Only runs if user
does not enter “y”
Remember to put print(‘Not yet!’)
a colon here too
BRANCHING 121
Output if condition is “True” “else” condition output
2 Run the program and type in “y”. The program 3 Type in “n”, or any other character,
shows your New Year message. It doesn’t show the and the New Year message isn’t shown.
other message. Instead, the “Not yet!” message appears. Type in “n”
elif op == ‘sub’:
c = a - b “else” condition output
elif op == ‘mul’: Type “div” to
3 The “else” condition runs if something other than
divide the “add”, “sub”, “mul”, or “div” is typed in, and an error message
c = a * b variables is displayed.
elif op == ‘div’:
c = a / b Shows an error message a = 7
in “c” if something else Type something
else: is typed in b = 5 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.
for i in range(3):
forward(100) The “for” loop tells the
The turtle program to repeat the
in Python right(120) instructions three times
The output
>>> 2 4 6 8 10 appears in twos >>> 10 9 8 7 6 5 4 3 2 1
To make the loops repeat “n” number of times, Outer 1 x 2 = 2 Second time around
the last number in the range must be “n + 1” loop the outer loop
2 x 2 = 4
n = 3 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
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
loops
loop keeps on going around as many times as it needs to.
While loops No
▷ How it works Monster friendly?
A while loop keeps repeating as long as a certain A while loop
condition is true. This condition is called the checks if the Yes
“loop condition” and is either true or false. condition is true.
If it is, it goes
Create a while loop around the loop Stay very still
1 Set the starting value of the “answer” variable in again. If it’s not,
the loop condition. The loop condition has to be true it skips the loop.
to start with or the program will never run the loop.
The code Run away!
The “answer” variable is set to “y”
inside the answer = ‘y’
loop must The while loop only runs
be indented while answer == ‘y’:
if the condition is true
four spaces
print(‘Stay very still’)
answer = input(‘Is the monster friendly? (y/n)’)
If the condition is false, unindented code after
print(‘Run away!’) the loop runs and a different message appears
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
user can escape the loop. The program for i in range(1,13):
executes a break if the user types “stop”.
print(‘What\’s’, i, ‘x’, table, ‘?’)
guess = input()
If “guess” equals “stop”, the if guess == ‘stop’:
program skips the rest of the
loop and prints “Finished”
break
ans = i * table
The “ans” variable
if int(guess) == ans: holds the correct
print(‘Correct!’) answer to the
question
else:
print(‘No, it\’s’, ans)
print(‘Finished’)
ESCAPING LOOPS 127
How it works
>>> 3 If the user decides not to carry on
What’s 1 x 7 ? after the third question and types “stop”,
the break command is executed and the
1 The first time around the program leaves the loop.
loop “i” is equal to 1
No, it’s 7
What’s 2 x 7 ?
14 The value of “i” changes to
2 next time around the loop
Correct!
What’s 3 x 7 ?
stop This executes the break
command and the
Finished program exits the loop
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
for i in range(1,13): to see if the user answered “skip”. If so,
the program will print “Skipping” and
print(‘What\’s’, i, ‘x’, table, ‘?’) execute a “continue” to skip to the next
guess = input() go around the loop.
Asks the question
if guess == ‘stop’: “What’s 1 x 7?” first
time around the loop What happens
break 5 If the user doesn’t want to answer
if guess == ‘skip’: a question, he or she can type “skip” and
continue to the next question.
print(‘Skipping’)
Skips straight
continue to the next loop >>>
ans = i * table What’s 1 x 7 ?
if int(guess) == ans: skip Type “skip” to go to
the next question
print(‘Correct!’) Skipping
else: What’s 2 x 7 ? The loop goes around
print(‘No, it\’s’, ans) again as normal when
14 the answer is correct
print(‘Finished’) 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”
[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
The position of an
item in a list is
[5] append(‘pie’)”. This will then be
added after “tea”, in position 6
▽ Lists in lists
The items in a list can be lists themselves. The Because the list is inside square
“suitcase” list below contains two lists of brackets, it becomes an
individual item within the
clothes—it is like a suitcase shared by two “suitcase[1]”
“suitcase” list—“suitcase[0]”
people, where they each pack three items.
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.
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.
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
Tuples are
stays the same. surrounded
by brackets
◁ What is a tuple?
>>> dragonA = (‘Sam’, 15, 1.70) A tuple contains items separated by
>>> dragonB = (‘Fiona’, 16, 1.68) commas and surrounded by brackets.
Tuples are useful for collecting several
The items in a tuple are bits of data together, such as a dragon’s
separated by commas name, age, and height.
◁ Change a value
>>> age[‘Owen’] = 12 Assign a new value to the
Assign a new value to
item labeled ‘Owen’
>>> print(age) an existing key to change
its value.
{‘Owen’: 12, ‘Sanjay’: 8, ‘Mary’: 10}
▷ Delete an item
>>> del age[‘Owen’] The item labeled
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 dictionary
by their position in the dictionary. {‘Sanjay’: 8, ‘Mary’: 10}
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
only store values?
Variables are like boxes that hold values.
The value in one variable can be copied
a b
and stored in another. It’s like photocopying △ How variables work
the value contained in box “a” and storing Each variable is like a box containing a
a copy in box “b”. piece of paper with a value written on it.
Now “a” and “b” both This prints out the variable
contain the value 2 names with their values
Change a value
2 If you change the value stored >>> a = 100 Change the value in “a” to 100
in one variable it won’t affect the value >>> print(‘a =’, a, ‘b =’, b)
stored in another variable. In the same
way, changing what’s written on a piece a = 100 b = 2
of paper in box “a” won’t affect what’s on
the paper in box “b”. Now “a” contains 100,
but “b” still contains 2
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.
Changing the original list has listA = [1, 1000, 3] listB = [1, 1000, 3]
changed the copy of the list too.
The second item of both
This is the third “listA” and “listB” has
item in the list 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
of the list has changed the listA = [1, 1000, 75] listB = [1, 1000, 75]
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
are like people
can read it, but they can’t change its value. walking along the
street—everyone
Variable outside the function Same global variable
1 Create a global variable called “b” in the 2 We can also print “b” directly from the
can see them
main program. The new function (“func2”) can main program. “b” can be seen everywhere
read the value of “b” and print it. because it wasn’t created inside a function.
“func2” can see
>>> b = 1000 the value of “b” >>> print(b)
>>> def func2(): because “b” is a 1000
global variable
print(b)
Global variable “b” can
>>> func2() be used anywhere in
Printing “func2” gives you the main program
1000 the value stored in “b”
VA R I A B L E S A N D F U N C T I O N S 139
Variables as input to functions
When a variable is used as input to a function its value is copied into a
new local variable. Therefore, changing the value of this new local variable
inside the function doesn’t change the value of the original variable.
Changing values inside a variable Print variable
1 “func3” uses input “y”, which is a local 2 Printing the value of “z” after calling “func3” shows
variable. It prints the value of “y”, then changes it hasn’t changed. Calling “func3” copies the value in “z”
that value to “bread” and prints the new value. (“butter”) into local variable “y”, but “z” is left unchanged.
>>> def func3(y): “y” contains the >>> print(z) Prints the value in global
value passed to variable “z” after “func3” has
print(y) butter finished running
it when “func3”
y = ‘bread’ is called
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 = Backwards
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”
Loads all the commands
and “val” values into movement commands. that control the turtle
elif do == ‘B’:
This tells the function to turn
backward(val) a “do” value of F into the
turtle command “forward”
elif do == ‘R’:
right(val) As in the flowchart, the function
checks the “do” letter against all
elif do == ‘L’: the letters it understands
left(val)
This command tells
This command instructs
the turtle to start elif do == ‘U’: the turtle to stop drawing
drawing on the page
penup() on the page
A blank command
check it’s not blank won’t work, so the
function skips it
—if it is go on to next item in list
Recognizes the first
command type is the first letter letter as a “do”
command
if followed by more characters Recognizes the
following characters
—turn them into a number as a “val” number
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
special character ( “-” in this program). sample house shape
[‘N’, ‘L90’, ‘F100’, ‘R45’, ‘F70’, ‘R90’, ‘F70’, ‘R45’, ‘F100’, ‘R90’, ‘F100’]
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 item
def string_artist(program): is one command for the turtle
cmd_list = program.split(‘-’)
If the length of the command is 0 (so
for command in cmd_list: the command is blank), the function
skips it and moves to the next one
cmd_len = len(command)
if cmd_len == 0: Takes the first character of the command
Gets the
(remember, strings start at 0) and sets it as
length of the
command
continue the command type (“F”, “U”, etc.)
string cmd_type = command[0]
This takes all the remaining
num = 0 Checks if the command characters from the command
is followed by more by cutting off the first one
if cmd_len > 1: characters (the number)
Converts the
characters from num_string = command[1:] Prints the command on the
strings into screen so you can see what
numbers num = int(num_string) the code is doing
print(command, ‘:’, cmd_type, num)
turtle_controller(cmd_type, num) Passes the command
to the turtle
D R AW I N G M AC H I N E 145
>>> string_artist(‘N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100’)
N : N 0 Resets the screen and puts
the turtle back at the center The turtle commands
L90 : L 90 are all separated by a “-”
F70 : F 70
This command makes the
R45 : R 45 turtle draw the right-hand
F100 : F 100 side of the roof
R90 : R 90
The turtle turns 90 degrees
F100 : F 100 right, ready to draw the
bottom of the house
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 The triple quote (‘‘‘) tells Python that
10 user can input instructions. A “while True” loop everything until the next triple quote
is part of the same string, including
lets them keep entering new strings.
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
The string lifts the pen The arrow shows where the
three times to draw the turtle stopped. This means that
eyes and beak separately the owl’s beak was drawn last
REMEMBER
Achievements
You created the drawing machine program Created the function “turtle_controller” that works
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
The Python keyword an error as no Age cannot be less than 5
is ”for” not “fir” number can be and greater than 8 at the
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
be (1 + 2 + 3 + 4 + 5), but it shows the
answer as “10”. You need to find out why. The answer should be “15”, not “10”
BUGS AND DEBUGGING 149
Add a “print”
3 and “input()” top_num = 5
The program doesn’t show total = 0
what it’s doing at each This command prints the
step. Adding a “print“ for n in range(top_num): current value of the loop
command here will let total = total + n variable and the total so far
you see what’s happening.
The “input()” command print(‘DEBUG: n=’, n, ‘total=’, total)
waits for the “return” or input()
“Enter” key to be pressed
before looping. print(‘Sum of numbers 1 to’, top_num, ‘is’, total)
New output
4 The loop is only adding the numbers DEBUG: n= 0 total= 0
from 0 up to 4, and not 1 to 5. This is DEBUG: n= 1 total= 1
because a “for” loop always starts counting This is actually the
from 0 (unless told otherwise), and always DEBUG: n= 2 total= 3 sum of the numbers
from 0 to 4, not 1 to 5
stops 1 before the end of the range. DEBUG: n= 3 total= 6
DEBUG: n= 4 total= 10
Sum of numbers 1 to 5 is 10
Fix the
5 faulty line top_num = 5 The new range will count
from 1 and stop at “top_num”
The range should total = 0 (1 less than “top_num + 1”)
go from 1 up to
“top_num + 1”, so that for n in range(1, top_num + 1):
the loop adds up the total = total + n
numbers from 1 to
”top_num” (5). print(‘DEBUG: n=’, n, ‘total=’, total)
input()
print(‘Sum of numbers 1 to’, top_num, ‘is’, total)
Correct output
6 The “print” command shows that DEBUG: n= 1 total= 1
the program is adding the numbers from DEBUG: n= 2 total= 3 When “n= 3”, the
1 to 5 and getting the correct answer. total is (1 + 2 + 3)
The bug has now been fixed! DEBUG: n= 3 total= 6
DEBUG: n= 4 total= 10
The correct answer
DEBUG: n= 5 total= 15 is now printed
Sum of numbers 1 to 5 is 15
150 P L AY I N G W I T H P Y T H O N
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 rather than 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 >>> a = [4, 9, 3, 8, 2, 6, 1, 5, 7]
called “Timsort”, named after its >>> a.sort()
designer, Tim Peters. It’s based on This calls the
“sort()” function The numbers
two sorting algorithms: “Insertion >>> a in list “a” are
sort” and “Merge sort”. Type in this [1, 2, 3, 4, 5, 6, 7, 8, 9] now sorted
code to see how it works.
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
gives you access to sound modules
◁ “import random” and special graphics that can be
import random This way of importing used in games. You’ll be able to
requires you to type the use Pygame once you have a good
module name at the start of understanding of the basics of
random.randint(1, 6) the code. It makes it easier to Python covered in this book.
random.choice(my_list) read because you know
which module it came from.
The module name comes Imports all the functions
before each function from the Random module
window = Tk()
EXPERT TIPS
Press the button to
2 roll the dice
Tk
Clear and simple
Run the program, then click the
button to roll the dice 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 dice, 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
things
to be told exactly what color each pixel should be.
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’)
of numbers will appear in the shell
window. These numbers are the values Red value Green value Blue value Code for the color
of red, green, and blue that have been in hexadecimal
mixed to make the chosen color. (see pp.182–183)
C O L O R A N D C O O R D I N AT E S 157
Drawing on a canvas EXPERT TIPS
To create graphics using Python, Coordinates
you need to make a blank area to
draw on. This is known as a canvas. In Tkinter, x coordinates get larger moving to
the right, and y coordinates get larger moving
You can use x and y coordinates to
downward. (0,0) is in the top-left corner.
tell Python exactly where to draw
on the canvas. +x
(0,0)
(300,50)
+y (50,100)
Create a graphics program
1 Use this code to create a window and (250,200)
put a canvas inside it. It will then draw
random circles on the canvas.
This imports the “randint” and “choice”
from random import * functions from the Random module
from tkinter import * This imports all of the
Tkinter functions
size = 500
The variable “size” sets the
window = Tk() dimensions of the canvas
▽ Coordinates grid
Drawing with coordinates The top-left corner of the rectangle
Coordinates are used to tell the computer exactly is at coordinates (50, 50). The
where to create shapes. The first number (“x”) tells the bottom-right corner is at (250, 350).
computer how far along the screen to go. The second
0 100 200 300 400 500
number (“y”) tells the computer how far down to go.
0
(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.
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.
Shape’s name,
or ID
◁ Moving eyeballs
>>> c.move(eyeball, -10, 0) Type this code into the shell
>>> c.move(eyeball, 10, 0) window to make the eyeball turn
to the left, then turn back again.
This function Sets coordinates
moves shapes for the movement
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
The function closed
Write the code Open and close
1 Type this code to create two
“itemconfig()” changes
the properties The opened
2 Type this code into the shell window
functions that will make the mouth of shapes you’ve mouth will to make the mouth open and close.
seem to open and close. already drawn be black
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 graphic Positions the text Put what you want
of the alien and creates a function to on the canvas the alien to say in
steal its hat. quote marks
A new message
appears when the
hat disappears Give my hat back!
Steal the hat
2 Type this code into the shell window
and see what happens.
Type this to
steal the hat
>>> steal_hat()
162 P L AY I N G W I T H P Y T H O N
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.
This brings the Tkinter window
to the front of your screen
window.attributes(‘-topmost’, 1)
def burp(event): Creates a function
called “burp” △ Burping alien
mouth_open()
Click the left mouse button and
c.itemconfig(words, text=‘Burp!’) the alien lets out a burp. This
Links the left mouse click is because the “burp” function
c.bind_all(‘<Button-1>’, burp) to the “burp” function
has been used.
REACTING TO EVENTS 163
Key events
Functions can also be bound to keys on the keyboard in
the same way. Type in the code below to make the alien
blink when the “A” and “Z” keys are pressed.
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
shapes
understand how each part fits together before moving
on to the next stage. By the end you’ll have a game
that you can play and share with friends.
Create the game window IDLE File Edit Shell Debug Window Help
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
MAX_BUB_SPD = 10
Sets the position
GAP = 100 of the bubble on Picks a random size for
the canvas the bubble, between the
def create_bubble(): minimum and maximum
x = WIDTH + GAP values possible
EXPERT TIPS
Bubble lists
Three lists are used to store bub_id: stores the ID number of the
information about each bubble. The bubble so the program can move it later.
lists start off empty, and information bub_r: stores the radius (size) of
about each bubble is then added the bubble.
as you create it. Each list stores a bub_speed: stores how fast the bubble
different bit of information. travels across the screen. Don’t forget to
save your work
168 P L AY I N G W I T H P Y T H O N
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.
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.
This variable keeps This loop goes through the entire list
def collision(): track of points scored of bubbles (it goes backwards to
avoid errors when deleting bubbles) Checks for collisions
points = 0 between the sub
for bub in range(len(bub_id)-1, -1, -1): and any bubbles
score = 0
#MAIN GAME LOOP Sets the score to zero
when the game starts
while True:
Creates new bubbles
if randint(1, BUB_CHANCE) == 1:
create_bubble()
move_bubbles() Adds the bubble
clean_up_bubs() score to the total
score += collision()
print(score)
window.update() Shows the score in the shell
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
and the time left in the game. what the numbers mean
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.
score += collision()
if (int(score / BONUS_SCORE)) > bonus:
bonus += 1 “print(score)” has been replaced by
“show_score(score)” so that the score
end += TIME_LIMIT now appears in the game window
show_score(score)
show_time(int(end - time()))
window.update()
Displays the time remaining
Don’t forget to sleep(0.01)
save your work
Finally, add a “GAME OVER” graphic. This will be Sets the font—
17 shown when the time runs out. Add this to the Puts graphic in the
middle of the screen
“Helvetica” is a good
font for big letters
very bottom of your program.
c.create_text(MID_X, MID_Y, \
text=‘GAME OVER’, fill=‘white’, font=(‘Helvetica’,30))
Tells you what your
c.create_text(MID_X, MID_Y + 30, \ score was
text=‘Score: ’+ str(score), fill=‘white’) Sets the text color
to white
c.create_text(MID_X, MID_Y + 45, \
text=‘Bonus time: ’+ str(bonus*TIME_LIMIT), fill=‘white’)
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
blaster and it’s now ready to play. Run the The timer counts The player scores
program and try it out. If something isn’t down to the end points for
working, remember the debugging tips— of the game popping bubbles
with the sub
look back carefully over the code on the
previous pages to make sure everything
is typed out correctly. IDLE File Edit Shell Debug Window
Bubble Blaster
Up arrow key
Left
TIME SCORE
arrow key Down arrow key 13 241
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:
Help
◁ 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 further.
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
games, then progress to more print(‘Hello World’)
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 1 1 1 0 0 0 1
Binary numbers can be
1111 in binary is
15, which is F in
hexadecimal
F 0001 in binary is 1, which
is 1 in hexadecimal
1 The number
241=F1
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
the character, the ASCII 51 3 83 S 115 s
You can convert between
ASCII and binary code in most value, and the binary 52 4 84 T 116 t
value for each letter in 53 5 85 U 117 u
languages, including Python.
the name “Sam”
54 6 86 V 118 v
>>> name = ‘Sam’ 55 7 87 W 119 w
>>> for c in name: 56 8 88 X 120 x
57 9 89 Y 121 y
print(c, ord(c), bin(ord(c)))
58 : 90 Z 122 z
59 ; 91 [ 123 {
S 83 0b1010011 60 < 92 \ 124 |
Here are the results. The 61 = 93 ] 125 }
a 97 0b1100001 beginning of each binary
number is marked “0b” 62 > 94 ^ 126 ~
m 109 0b1101101 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,
Putting “\u” before the
and the values 10–15 are represented by 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
problems. This kind of math,
known as “inverters”. 1 0 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 also 1 0
known as “XOR” gates.
△ Inputs 1 and 1 = output 0 △ Inputs 1 and 0 = output 1
Two “on” inputs produce The output is only “on” 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 XOR computers are based on
gate, you create a circuit that can billions of tiny logic circuits.
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 only understand 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 The character
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 memory
and interpreters.
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
programs
data stored? And how can it be found again?
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
▽ Port numbers
Ports The numbers used for ports range
Just as you mail a letter to a from 0 to 65535 and are divided A device’s IP address
is like the street
specific person in an apartment into three types: well-known, address of a building
building, you may want to registered, and private.
send packets to a specific
program on a device. Computers
use numbers called “ports” IP 165.193.128.72
as addresses for individual
programs. Some common
A port within
programs have ports specially a device is
reserved for them. For example, 1 2 3 4 like an
web browsers always receive apartment in
a building
packets through port number 80.
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
Designed in 1964 at Dartmouth College, in the
BASIC US, BASIC was very popular when home
predicted to cause problems in
2000 when these dates rolled over
computers first became available.
into the new millennium as 00.
△ 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
3–present
Nationalit y: American Dates: Gates 1955–present, Allen 195
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 ld W id e W eb ,
the Wor
Boy, while Miyamoto ad e it fre e fo r
and m
made successful games ever yone. He was
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 arr 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
only do this 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
games
motion-sensing, to give users a better experience.
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
languages
◁ HTML ▷ JavaScript
HTML HTML (HyperText Markup 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. This
When you open a website, your <head> tag gives the window a title
Internet browser downloads an
<title>The Hello World Window</title>
HTML file and runs the code to turn
it into a web page. To see how it </head>
works, type the code here into an <body>
IDLE code window (see pp.92–93) <h1>Hello World in HTML</h1>
and save it as a file with the ending
<p>Hello World!</p>
“.html”. Double click the file and it The “<p>” and “</p>”
</body> tags surround
will launch a browser window ordinary paragraphs
saying “Hello World!” </html> 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
for the Internet
JavaScript code is more concise and trickier to learn.
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 The text in quotes
enter their name and responds with a greeting. user types into it 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
the IDLE code window and var greeting = “Hello ” + name + “!”;
remember to save it with a document.write(greeting); JavaScript lines
“.html” filename. always end with
</script> a semicolon
Click the
button The tongue-twister
appears
Run the program
2 Double-click the file < > < >
to launch the program in a She sells seashells
browser window. Say this!
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 it. The loop keeps repeating as long as “x”
1 Like Python, JavaScript uses “for” to set up a loop. The repeated 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 to
Removable memory 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 algorithms 16, 17
to main entries. black-hat hackers 213 Unicode 185 bad programs 212–13
blank lines 117 Chef 199 essential 190–1
blocks circles, drawing 157, 158 experimenting with 19
A
Ada 18
colored 31
connecting 18
creating 72–3
circuits, computer 187, 188, 189
clicking, and events 44, 66, 162
clock pulse 188
how they work 15
uses of 14
computers
addition 52, 102, 112 defining 72, 73 coordinates deconstructing 217
Adobe Flash 25 functions of 31 drawing with 158 invention of 201
AI see Artificial Intelligence help with 83 and location 168 main parts of 180–1
algorithms 16, 17, 150–1, 218 with inputs 73 and movement 166 mini 214–15
Allen, Paul 200 programming 22 in Python 157 supercomputers 203
ALU see arithmetic logic unit types of 31 in Scratch 56–7 console games 198
American Standard Code for blocks palette 27, 31, 32, 35, 38, COBOL 199 consoles 14, 204
Information Interchange see 50 code windows 92, 93, 106–7 containers 134, 218
ASCII bomb disposal 203 errors in 94 “continue” keyword 127
“and” block/operator 63, 103, Boole, George 186 coders 14, 15 “Control” blocks 31, 65, 68
118, 119 Boolean expressions 62, 63, 64, becoming a coder 18–19 control unit 180
AND gate 186 65, 111, 118–19, 120, 218 becoming a master controls, game 174, 205
Android operating system 198, botnets, zombie 213 programmer 216–17 costumes 40–1
207 brackets famous 200–1 and movement 23, 40, 41
anti-malware software 213 errors 94 and games 204 random 61
antivirus programs 213 in lists 128, 129 think like a computer 16–17 Roll the dice project 60–1
apostrophes 115 in tuples 134 coding and speech bubbles 41
Apple Mac using 112, 119 clear 143 switching 34, 40, 41
file management 193 brain, training 216 computer programs 14–15 cryptography 202
operating system 190, 207 branches/branching 65, 99, 100, reading 176, 216 CSS (Cascading Style Sheets) 208
programming languages 198 120–1, 218 what is coding? 14–19 cursor tools 26
Python 3 on 88, 90 breaks, inserting in loops 126–7 coding clubs 82, 207
Scratch on 25 Brin, Sergei 201 coding contests 217
apps, making 206–7
Arduino 214, 215
arithmetic logic unit (ALU) 181
broadcast blocks 70–1, 77
browser windows 210, 211
Bubble blaster project 164–75
colors
adding to shapes 159
changing 60, 160
D
data 218
arrow keys 163, 166 bugs 148–9, 177, 207, 218 mixing 156 and functions 131
Artificial Intelligence (AI) 203, buttons in Python 156–7 input 180
205 creating 152, 154–5 selecting 156 output 181
ASCII 184, 218 labelling 155 commands secret 202
audio output 181, 215 linking to events 162 Python and Scratch sending via Internet 194, 195
bytes (B) 183, 192, 218 compared 102–5 theft 213
commas “Data” blocks 31, 50
B
Babbage, Charles 200 C
in lists 128
in tuples 134
comments, adding 143
data storage
in files 192–3
memory 180, 181, 188, 189
backgrounds/backdrop 23, 26 C 18, 198 comparison blocks/operators in variables 50
changes to 45 C++ 198 62–3, 118–19 data types
selecting from library 33, 74 calculations 180, 181, 189 compass 39 converting 111
switching 41 in Python 112 compilers 191 mixed 111
backpack, Scratch 82 in Scratch 52–3 components, computer 181, 217 spotting 111
banking 199, 202 supercomputers 203 compression 202, 218 tuples and dictionaries 134–5
bases 182–3 calling functions 104, 139, 218 computer circuits 187, 188, 189 debugging 148–9, 174, 177, 207,
BASIC 199 cameras 215 computer games see games 218
battery, computer 181 canvas 157, 158 computer languages see decimal system 182
beats 59 cars 14 programming languages decisions
Berners-Lee, Tim 201 characters computer programmers see and branches 64–5
binary code/signals 15, 182–3, between outputs 117 coders flowcharts 141
184, 185, 195, 218 numbering in strings 115 computer programs 14–15 logic gates 186–7
INDEX 221
F
Facebook 201
graphic designers 204
graphical user interface
see GUI
installation
Python 3 88–91
Scratch 24–5
lists
adding/deleting items 55, 105,
128, 129, 169
false see true or false graphics 218 instruments, musical 59 combining 129
fiberoptic cables 195 changing 160–1 integers 110, 219 commands 105
file browsers 190 color and coordinates 156–7 Integrated DeveLopment copying 137
files 218 effects 43, 152, 153 Environment see IDLE creating 55, 105
compressing 202 games 205 interface in loops 129
corruption 213 making shapes 158–9 GUI 154–5 playing with 55
managing 193 graphics processing unit Scratch 26–7, 49 putting tuples in 134
properties 192 see GPU user 140, 146–7, 219 in Python 128–9, 132–3
sizes 192 grid, x and y 56, 158 Internet 194–5 in Scratch 54–5
storing data in 192–3 GUI 154–9, 218 connecting to other using 55, 129, 167
firewalls 213 computers via 152 in variables 136–7
222 REFERENCE
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
Mac OS X 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 pilots 205 140–7
malware 212–13, 219 129 Pixar 86 errors 94–5
Math module 152 pixels 156 escaping loops 126–7
math player’s name 50 functions 130–1, 132–3
in Python 102, 112–13
in Scratch 52–3, 102
MATLAB 18
N
name errors 95
PNGs 193
pop-up boxes/windows 146,
209, 210
Ghost game project 96–9
harder commands 104–5
input and output 116–17
medicine 203 NASA 86 ports 195, 219 installing 88–91
megabytes (MB) 183, 189, 192 negative numbers 56, 57 position introducing IDLE 92–3
memory 180–1, 188–9, 190, nested loops 47, 69, 123 coordinates 56–7 libraries 152–3
192, 219 network adaptors 181, 195 random 43, 57 lists 128–9, 132–3
messages networks, computer 152, “print()” function 87, 101, 102, lists in variables 136–7
reacting to 70 194, 218 108, 109, 116, 117, 130 loops in 122–7, 133
sending and receiving 70 nibbles 183 printers 181 making decisions 118–19
microphones, and events 44, 45 NOT gate 186 processors 100, 101, 180–1, making games with 177
Microsoft 200 notes, musical 59 188–9, 190, 203, 219 making shapes 158–9
Microsoft Windows numbers program flow 100–1 making windows 154–5
file management 193 binary and bases 182–3 programming languages 15, 18, math in 112–13
operating system 190, 207 comparing 62, 118 19, 22, 49, 83, 198–9, 219 numbers in 110
Python 3 on 88, 89 data types in Python 110 conversion into machine code print in 87
Scratch on 25 random 53, 104, 113, 152, 155 188 program flow 100–1
millennium bug 199 first 200 reacting to events 162–3
INDEX 223
saving work 88 home-built 215 simple commands 102–3 sound designers 204
and Scratch 87, 101, 102–5, Roll the dice project 60–1 simple loops 46–7 sound library 79
124, 125 rotation software 24 sounds 22, 23
scripts 101 styles 38 special effects 42–3 adding to program 58–9, 79
shell and code windows 92, tools 61 sprites 28–9 detectors 45
93, 106–7 routers 194, 195 strings and lists 54–5 in games 205
shortcuts 171 Ruby 18 true or false 62–3 playing 58
Silly sentences project 132–3 running typical programs 23 selecting from library 37, 58
simple commands 102–3 programs 23, 102, 106 understanding 22 volume control 58
sorting in 151 scripts 30 variables 50–1, 108 spam 213
strings in 110, 114–15, 117 runtime errors 148 versions of 25 speakers 181
tuples and dictionaries 134–5 and webcams 45 speech bubbles 22, 28, 87, 101
turtle graphics 87 website 24, 82 adding 41, 161
conversations 71
types of data 110–11
Unicode in 185
variables 99, 101, 108–9, 116
S
saving your work 11
what is Scratch? 18, 22–3
screens 181
scripts 22, 23
speed, setting 51, 77
“split()” function 144
variables and functions 138–9 in Python 88, 93, 106, 107 building 27 sprites 22, 23, 28–9, 39, 219
website 89 in Scratch 24, 25, 33 and colored blocks 30–1 adding graphic effects 43
what is Python? 19, 86–7 saying things (in Python) 161 flow of 30 adding more 76–7, 80
what next? 176–7 score 50, 79, 99, 172–3 pausing 69 adding sounds 58–9
while loops 124–5 scoreboards 172 in Python 101 changing size 43
Scratch 20–83 repeating 68 changing time or speed 35, 51
account 24 running 30 coordinates 56–7
collisions 67
Q
questions
adding sounds 58–9, 79
backpack 82
blocks 30–1, 72–3
in Scratch 30–1, 101
and sprites 28
stopping 30, 68
communication between
70–1
asking 54 coordinates 56–7 testing 30 controlling 31, 66
combining 63 complex loops 68–9 scripts area 27 copying or deleting 29
true or false 62–3 costumes 40–1 scripts tab 27 creating and editing 29, 34, 36
quote marks creating blocks 72–3 scriptwriters 204 designing your own 39
errors 94 decisions and branches 64–5 SD cards 215 direction 39
in lists 128 Escape the dragon! project secret data 202 and events 44–5
in strings 110, 114, 116 32–7 selection sort 151 hiding and showing 42
events 44–5 “Sensing” blocks 31, 34, 36, 51, in the interface 28
experimenting with 82–3 65, 66–7, 75 movement 22, 23, 38–9, 57,
66–7
R
radio waves 195
harder commands 104–5
help menu 83
hide and seek 42–3
separators 117
servers 219
shapes
naming 29
pen tools 48–9
RAM 189 installing and launching 24–5 adding color 159 renaming 29
“randint()” function 98, 99, 101, interface 26–7, 49 drawing 140 rotation styles 38
104, 113, 130, 153, 155 lists 55 making 158–9 and scripts 28
Random Access Memory make some noise 58–9 moving 160 selecting from library 34, 36,
see RAM making things move 38–9 naming 160 39, 75, 76
Random module 152, 153, 157 math in 52–3 shell windows 92, 93, 106–7, 116 and “Sensing” blocks 66–7
random numbers 53, 104, 113, menu and tools 26 errors in 95 sprite list 27
152, 155 and microphones 45 silicon chips 188, 189 turtle graphics 49
random positions 43, 57 Monkey mayhem project Silly sentences project 132–3 and variables 35, 50–1
Raspberry Pi 25, 214 74–81 skipping, in loops 127 what they can do 28
reacting to events 162–3 pens and turtles 48–9, 87 slicing 115 square roots 53
readable code 133 and Python 87, 102–5, 124, 125 smartphones 206 stage 23, 25, 27
remainders 53 and Python’s Ghost game 101 social apps 206 Standard Library modules 152
repeat loops 46, 122, 211 Roll the dice project 60–1 Socket module 152 stop button 30
“repeat until” block 68, 76, 77, scripts and colored blocks sockets 195, 219 stopping programs 102
78, 124 30–1, 101 software 14, 15, 219 strategy games 205
rewriting code 217 sending messages 70–1 sorting algorithms 150–1 strings 219
robots 16, 203, 217 sensing and detecting 66–7 “Sound” blocks 31, 58–9 adding 114
224 REFERENCE
assigning 108
comparing 63, 118, 119
creating 114
turtle graphics 49, 87, 105, 107
commands 105, 145
Drawing machine project
read-only 51
results in 52
in Scratch 50–1, 108
X
x and y coordinates 56, 57, 157,
joining 105 140–7 splitting tuples into 134 158, 166, 168
length of 114 and loops 122 strings in 114 Xbox One 204
operators 119 Turtle module 152, 176 using 51, 109
in Python 110, 114–15, 117 video files 192, 193
in Scratch 54–5
separating 117
subprograms see functions U
video games 204–5
writing 153
viruses 212–13, 219
Y
Yokoi, Gunpei 201
subtraction 52, 102, 112 Ubuntu visual output 181
supercomputers 203 file management 193 volume control 58
surgeons 205
symbols, choice of 143
syntax 219
Python 3 on 88, 91
Scratch on 25
Unicode 185, 219
von Neumann, John 180
Z
zombie botnets 213
errors 94, 148 upper/lower case 94
USBs 215
user interface 140, 146–7, 219
W
washing machines 14
Zuckerberg, Mark 201
T watches 206
wearable technology 206
tablets 25, 206
tabs 26, 27
teleporting 43
V
values
weather forecasting 199, 203,
206, 215
web browsers 86, 195, 198
television 215 assigning to variables 108, web servers 198
tempo 59 109, 113, 118, 136 webcams, and events 44, 45
terabytes (TB) 192 changing 136 websites
testers, game 204 in dictionaries 135 construction 208–9
text editors 88 and functions 131 email 198, 208
text files 193 variables 35, 219 interactive 198, 208, 210, 211
text messages 14 assigning a value to 108, 109, Python 89
text-based programming 113, 118, 136 Scratch 24, 82
languages 86 changing contents of 109 while loops 124–5
time limit 172–3 comparing 62, 63, 118 white-hat hackers 213
Time module 152 creating 50, 54, 77, 102, 108 Wikipedia 201
Tkinter module 152, 154–5, 156, deleting 51 Windows see Microsoft Windows
157, 158, 159, 162, 165, 176 and functions 138–9 windows
transistors 188 global 138, 139 code and shell 92, 93, 106–7
travel apps 206 lists in 136–7 making 152, 154–5, 165
Trojans 212, 213, 219 local 138, 139 word processing 86
true or false 62–3, 64, 111, loop variables 123 words, comparing 63
118–21, 125 naming 50, 109, 143 World Wide Web 201
tuples 134, 219 in Python 99, 101, 108–9, 116, worms 212, 213
Turing, Alan 200 138–9
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 for proofreading; Python is copyright © 2001–2013 Python Software Foundation; All
Helen Peters for the index; and Adam Brackenbury for creative Rights Reserved.
technical support.