100% found this document useful (10 votes)
3K views

Help Your Kids With Computer Coding - 2nd Edition - DK

Kids programming tools

Uploaded by

Res Nam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
3K views

Help Your Kids With Computer Coding - 2nd Edition - DK

Kids programming tools

Uploaded by

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

C 0m Uter

HELP YOUR KIDS WITH


p
CoDing
C 0m Uter
HELP YOUR KIDS WITH
p
CoDing
A UNIQUE STEP-BY-STEP VISUAL GUIDE,
FROM BINARY CODE TO BUILDING GAMES
DK UK
Project editor Ben Ffrancon Davies
Editor Sam Priddy
Designer Fiona Macdonald
Additional editors Sam Atkinson, Lizzie Davey, Daniel Mills, Ben Morgan
Additional designer Simon Murrell
Consultant editor Craig Steele
US editor Kayla Dugger
Managing editors Lisa Gillespie, Paula Regan
Managing art editor Owen Peyton Jones
Producers, pre-production Ben Marcus, Jacqueline Street
Senior producers Meskerem Berhane, Mary Slater
Jacket editor Emma Dawson
Jacket designer Surabhi Wadhwa
Jacket design development manager Sophia MTT
Publishers Sarah Larter, Andrew Macintyre
Art director Karen Self
Design director Phil Ormerod
Associate publishing director Liz Wheeler
Publishing director Jonathan Metcalf

DK INDIA
Senior editor Suefa Lee
Senior art editor Devika Dwarkadas
Project editor Tina Jindal
Project art editor Sanjay Chauhan
Editor Neha Pande
Art editors Rabia Ahmad, Simar Dhamija, Sonakshi Singh, Shreya Anand Virmani
Assistant art editor Vanya Mittal
Jacket designers Priyanka Bansal, Suhita Dharamjit
Jackets editorial coordinator Priyanka Sharma
Managing jackets editor Saloni Singh
DTP designers Jaypal Singh Chauhan, Sachin Gupta, Rakesh Kumar
Senior DTP designer Harish Aggarwal
Managing editor Rohan Sinha
Managing art editor Sudakshina Basu
Pre-production manager Balwant Singh
This American Edition, 2019
First American Edition, 2014
Published in the United States by DK Publishing
1450 Broadway, Suite 801, New York, NY 10018
Copyright © 2014, 2019 Dorling Kindersley Limited
DK, a Division of Penguin Random House LLC
19 20 21 22 23 10 9 8 7 6 5 4 3 2 1
001–308107–Aug/2019
All rights reserved.
Without limiting the rights under the copyright reserved above, no part of this
publication may be reproduced, stored in or introduced into a retrieval system, or transmitted,
in any form, or by any means (electronic, mechanical, photocopying, recording, or otherwise),
without the prior written permission of the copyright owner.
Published in Great Britain by Dorling Kindersley Limited.
A catalog record for this book is available from the Library of Congress.
ISBN 978-1-4654-7732-3
DK books are available at special discounts when purchased in bulk for sales promotions,
premiums, fund-raising, or educational use. For details, contact: DK Publishing Special Markets,
1450 Broadway, Suite 801, New York, NY 10018
[email protected]
Printed and bound in China
A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW

www.dk.com
CAROL VORDERMAN, MA(CANTAB), MBE is one of Britain’s best-loved TV
presenters and is renowned for her mathematical skills. She has hosted numerous
TV shows on science and technology, from Tomorrow’s World to How 2, and was
co-host of Channel 4’s Countdown for 26 years. A Cambridge University engineering
graduate, she has a passion for communicating science and technology and is
particularly interested in coding.

DR. JON WOODCOCK, MA(OXON) has a degree in Physics from the University of
Oxford and a PhD in Computational Astrophysics from the University of London.
He started coding at the age of 8 and has programmed all kinds of computers, from
single-chip microcontrollers to world-class supercomputers. His many projects
include giant space simulations, research in high-tech companies, and intelligent
robots made from junk. Jon has a passion for science and technology education,
giving talks on space and running computer programming clubs in schools. He has
worked on numerous science and technology books as a contributor and consultant.

CRAIG STEELE is a specialist in Computing Science education who helps people


develop digital skills in a fun and creative environment. He is a founder of CoderDojo
in Scotland, which runs free coding clubs for young people. Craig has run digital
workshops with the Raspberry Pi Foundation, Glasgow Science Centre, Glasgow
School of Art, BAFTA, and the BBC micro:bit project. Craig’s first computer was a
ZX Spectrum.

SEAN McMANUS learned to program when he was 9. His first programming


language was Logo. Today he is an expert technology book 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 BSc and PhD degrees. She has worked in the Computer Laboratory at
Cambridge University and Glasgow Science Centre, and is currently working on
a project to develop a music and technology resource for elemantary schools in
Edinburgh. She is a mentor at CoderDojo Scotland.

DANIEL McCAFFERTY holds a degree in computer science from the University of


Strathclyde. He has worked as a software engineer for companies big and small in
industries from banking to broadcasting. Daniel lives in Glasgow with his wife and
two children, and when not teaching young people to code, he enjoys bicycling
and spending time with his family.
Contents
8 F O R E W O R D b y C a ro l Vo rd e r m a n
10 HOW THIS BOOK WORKS

WHAT IS CODING? 64 Decisions and branches


66 Sensing and detecting
14 What is a computer program? 68 Complex loops
16 Thinking like a computer 70 Sending messages
18 Becoming a coder 72 Creating blocks
74 Project 3: Monkey mayhem

STARTING FROM SCRATCH 82 Time to experiment

22 What is Scratch? PLAYING WITH PYTHON


24 Installing Scratch
26 Scratch interface 86 What is Python?
28 Sprites 88 Installing Python
30 Colored blocks and code 92 Introducing IDLE
32 Project 1: Escape the dragon! 94 Errors
38 Making things move 96 Project 4: Ghost game
40 Costumes 98 Ghost game decoded
42 Hide and seek 100 Program flow
44 Events 102 Simple commands
46 Simple loops 104 Harder commands
48 Pens and turtles 106 Which window?
50 Variables 108 Variables in Python
52 Math 110 Types of data
54 Strings and lists 112 Math in Python
56 Coordinates 114 Strings in Python
58 Make some noise 116 Input and output
60 Project 2: Roll the die 118 Making decisions
62 True or false? 120 Branching
122 Loops in Python 188 Processors and memory
124 While loops 190 Essential programs
126 Escaping loops 192 Storing data in files
128 Lists 194 The internet
130 Functions
132 Project 5: Silly sentences PROGRAMMING IN THE
134 Tuples and dictionaries REAL WORLD
136 Lists in variables
138 Variables and functions 198 Computer languages
140 Project 6: Drawing machine 200 Coding stars
148 Bugs and debugging 202 Busy programs
150 Algorithms 204 Computer games
152 Libraries 206 Making apps
154 Making windows 208 Programming for the internet
156 Color and coordinates 210 Using JavaScript
158 Making shapes 212 Bad programs
160 Changing things 214 Mini computers
162 Reacting to events 216 Becoming a master programmer
164 Project 7: Bubble blaster
176 What next? 218 Glossary
220 Index

INSIDE COMPUTERS 224 Acknowledgments

180 Inside a computer


182 Binary and bases
184 Symbols and codes Find out more at:
186 Logic gates www.dk.com/computercoding
Foreword

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.

Everything computers do is controlled by lines of code that someone has


typed out on a keyboard. It might look like a foreign language, but it’s a
language anybody can pick up quite quickly. Many would argue that coding
has become one of the most important skills you can learn in the 21st century.
Learning to code is tremendous fun because you can get instant results, no
matter how much more you have to learn. In fact, it’s such fun creating games
and programs that it feels effortless once you’re hooked. It’s also creative—
perhaps the first science that combines art, logic, storytelling, and business.

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

How this book works


This book introduces all the essential 170 P L AY I N G W I T H P Y T

concepts needed to understand computer BUBBLE BLASTER


coding. Fun projects throughout put these Figuring out the distance
Pixel people give
ideas into practice. Everything is broken down hints and tips along
In this game, and lots of others, it is
between two objects. Here’s how to
into small chunks so that it’s easy to follow the way. formula to have the computer work

and understand. 11
This function calculates
the distance between two
objects. Add this bit of
from m
def di
code directly after the x1
code you wrote in step 9.
x2
Each topic is re
described in detail, “See also” boxes list
with examples other subjects that are
and exercises linked to the topic
Pop the bubbles
The player scores points by poppin
and fast bubbles are worth more po
42 S TA R T I N G F R O M S C R AT C H code works out when each bubble
radius (the distance from the cente

Hide and seek Sizes and effects Choose the type


SEE ALSO from the dr
When the submarine and a bubble cras
‹ 38–39 Making
things move
12 the
Code can be used to change menu.and
sizeneeds to pop the bubble
program The
effect makes t
of a sprite and add special effects to it.should come directly becom
bit of code after t
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
This variable keeps
to make sprites bigger
track of points scor
reappear, grow and shrink, and fade in and out. and negative numbers
change size by 10 to make them smaller change
def collision():
Use the “hide” block
Hiding sprites to make sprites
disappear in games
points = 0
Higher numbers make set col
for bub in range(len(bub_id)-1
To make a sprite disappear, use the “hide” block. The sprites bigger and
lower
if numbers make
distance(ship_id2, bub_
sprite is still on the stage, and it can still move around, them smaller. 100 is
but it can’t be seen unless the “show” block is used to set size to 100 % clear gr
points += (bub_r[bub]
normal size
make it visible again. del_bubble(bub)
△ Changing a sprite’s size Resets all △ Addin
return points
the effects
These two blocks can be used to The graph
make a sprite bigger or smaller, used to c
▷ Hide and show either by a set amount or by a Gives back orDeletes
distortt
Colorful To make a sprite vanish, use the “hide” hide percentage of its size.
the number
experime
of points.
illustrations block. When you’re ready for it to be
seen again, use the “show” block.
highlight These blocks are found in the “Looks”
show Using effects to teleport
section of the blocks palette.
different Add a ghost sprite from the “Fantasy” category
Y

programming of the sprites library, and create the code shown


▽ Disappearing cat below. It makes the ghost appear to teleport
concepts Try this code using the cat sprite. It when clicked.
disappears and reappears but it keeps
moving, even when you can’t see it. EXPERT TIPS
Showing sprites The “ghost” effect makes the
when this sprite clicked fade slightly; by repeating th
when clicked Select a sprite in the sprites list. You block 20 times the sprite fad
clear graphic effects away completely
will see an information panel above
Programming forever this list. There, you can use the “Show” This “Opera
icons to show or hide a sprite. repeat 20
code blocks wait 1 seconds This block hides
selects a ra
horizontal p
the cat change ghost effect by 5
are explained hide
This block
line by line turn 90 degrees rotates
Sprite Sprite1 x 0 y 0
the cat
glide 0.1 secs to x: pick random -150 to 150 y: pic
move 100 steps clockwise
Show Size 100 Direction 90
The cat still repeat 20
wait 1 seconds
moves even
when hidden Shows a hidden sprite change ghost effect by -5
show
This block
shows the Using this block makes the
cat again sprite fade back in

Instructions show what Labels help explain


to click, drag, or select each step
HOW THIS BOOK WORKS 11
Seven projects build up Simple step-by-step
coding skills. Project pages are instructions guide you
highlighted with a blue band through each project

THON BUBBLE BLASTER 171

e between points 13
Now update the main game loop to use the
functions you have just created. Remember that Each line of
s useful to know the distance the order is important, so make sure you put
o use a well-known mathematical everything in the right place. Then run the code. code is clearly
k it out. Bubbles should burst when they hit the sub.
Check the shell window to see the score.
labeled so
Loads the “sqrt” function
from the Math library. you can’t
Gets the position of Sets the score to zero
math import sqrt the first object. when the game starts. go wrong
istance(id1, id2): Gets the position of score = 0
1, y1 = get_coords(id1) the second object.
#MAIN GAME LOOP
2, y2 = get_coords(id2)
while True:
eturn sqrt((x2 - x1)**2 + (y2 - y1)**2)
if randint(1, BUB_CHANCE) == 1: Creates new bubbles.
Gives back the distance create_bubble()
between them.
move_bubbles()
clean_up_bubs() Adds the bubble
score to the total.
score += collision()
ng bubbles. Big bubbles print(score)
oints. The next section of Shows the score in the shell
window.update() window—it will be displayed
is popped
H I D E by
A Nusing
D S Eits
EK 43 sleep(0.01) properly later.
er to the edge). ▷ Collision sensing
e of effect If the distance between This pauses the action for
rop-down
sh into each other, the the center
Change the of the sub and a very short time—try
“pixelate”
update the score. This numbers in the
the center of a bubble is less than their removing this and see
the sprite blocks to set what happens.
the code in step 11. radiuses added together, they have collided.
me blurred how strong
the effect is
s This loop goes through the entire list of bubbles (it EXPERT TIPS
red. goes backwards to avoid errors when deleting bubbles).
pixelate effect by 25 Python shortcut Don’t forget to
save your work This icon
The code “score += collision()” indicates that
Checks for collisions is a shortcut for writing
lor
1, -1, -1):
effect to 0
between the sub “score = score + collision()”. It adds the project
and any bubbles. the collision score to the total
_id[bub]) < (SHIP_R + bub_r[bub]):
Each color is
represented by a score, then updates the total score.
continues on
raphic effects
+ bub_speed[bub]) number. Change Code like this is common, so a the next page
the number to shortcut is useful. You can also do
ng graphic effects set the color
the same thing using the “–”
hic effects in Scratch can be symbol. For example, “score –= 10”
change a sprite’s appearance is the same as “score = score – 10”.
tthe
itsbubble.
shape. They’re fun toCalculates the number of
points this bubble is worth
ent with. and adds it to “points”.

You’ll never know where


I’ll appear next!

Boxes give extra


information: tips,
definitions, and things
e sprite
his
to remember EXPERT TIPS
des

ators” block
andom
When to save
This block
position selects a random
vertical position
Read on and
This save icon appears
get coding! on the project spreads. It
ck random -150 to 150
reminds you when to save
This block makes the the work you’ve done,
ghost move slowly,
hidden from view so that nothing is lost if
the computer crashes.
Always remember to save
Don’t forget to
your work frequently. save your work
What is
coding?
14 W H AT I S C O M P U T E R C O D I N G ?

What is a computer SEE ALSO


Thinking like 16–17 ›
program?
a computer
Becoming 18–19
a coder

A computer program is a set of instructions that a
computer follows to complete a task. “Coding”, or
“programming”, means writing the step-by-step
instructions that tell the computer what to do.

Computer programs are everywhere


We are surrounded by computer programs. Many of
the devices and gadgets we use every day are controlled
by them. These machines all follow step-by-step
instructions written by a computer programmer.

◁ Mobile phones △ Computer software


Programs allow you to make a Everything a computer does, from
phone call or send text messages. browsing the internet to writing
When you search for a contact, documents or playing music, works
a program finds the correct because of code written by a
phone number. computer programmer.

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

Computers can’t think


1 A computer won’t do
anything by itself. It’s up to
Write a program
the computer programmer
to give it instructions.
2 You can tell a computer what to
do by writing a set of very detailed
instructions called a program. Each
instruction has to be small enough that
the computer can understand it. If the
Without instructions a instructions are incorrect, the computer
computer is clueless
This is a computer won’t behave the way you want it to.
program counting
down to launch
for count in range(10, 0, -1):

Programming languages print("Counting down", count)


3 Computers can only follow
instructions in a language they
understand. It’s up to the
programmer to choose which
language is best for the task.

for count in range(10, 0, -1):


print("Counting down", count) All programs are finally
converted into “binary code”,
a basic computer language
that uses only ones and zeroes

LINGO
Hardware and software
“Hardware” means the physical
parts of the computer that you
can see or touch (all the wires, the

BLAST OFF! circuits, the keyboard, the display


screen, and so on). “Software”
means the programs that run
on the computer and control how
it works. Software and hardware
work together to make computers
do useful things.
16 W H AT I S C O D I N G ?

Think like a computer SEE ALSO

‹ 14–15 What is a
computer program?
A programmer must learn to think like a computer. All
tasks must be broken down into small chunks so that
Becoming 18–19
a coder

they are easy to follow and impossible to get wrong.

Thinking like a robot LINGO


Imagine a café where the waiter is a robot. The robot has Algorithm
a simple computer brain, and needs to be told how to
get from the café kitchen to serve food to diners seated An algorithm is a set of simple
instructions for performing a task.
at tables. First the process has to be broken down into
A program is an algorithm that has
simple tasks the computer can understand. been translated into a language
that computers can understand.

Waiter robot program 1


1 Using this program the robot grabs the food from
the plate, crashes straight through the kitchen wall
into the dining area, and puts the food on the floor.
◁ Disaster!
This algorithm wasn’t detailed enough.
The instructions
weren’t clear: we
1. Pick up food forgot to tell the
robot to use the door.
2. Move from kitchen to diner’s table It might seem obvious
to humans but
3. Put food down computers can’t think
for themselves.

Waiter robot program 2


2 This time we’ve told the robot waiter to use the
kitchen door. It makes it through the door, but then hits
the café cat, trips, and smashes the plate on the floor.

1. Pick up a plate with food on it


2. Move from kitchen to diner’s table by:
Move to door between kitchen and dining area
△ Still not perfect
Move from door to the table The robot doesn’t know how to deal with
obstacles like the cat. The program needs
3. Put plate down on the table in front of the diner to give the robot even more detailed
instructions so it can move around safely.
THINK LIKE A COMPUTER 17
Waiter robot program 3
3 In this version of the program, the robot successfully
delivers the food to the diner avoiding any obstacles. But
after putting the plate down, the robot remains standing
at the table while food piles up in the kitchen.

1. Pick up a plate with food on it holding it level at all times


2. Move from kitchen to diner’s table by:
Move to door between kitchen and dining area
checking for obstacles and steering around them
Move from door to the table
△ Success at last?
checking for obstacles and steering around them Finally the robot can deliver the
food safely. But we forgot to give
it instructions to go back to the
3. Put plate down on the table in front of the diner kitchen and get the next plate.

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?

1. Wait until doors are closed


2. Wait for button to be pressed
If button pressed is higher than current floor:
Move lift upwards
If button pressed is lower than current floor: ◁ Elevator program
For the elevator to work
Move lift downwards correctly and safely, every
step has to be precise, clear,
3. Wait until current floor equals button pressed and cover every possibility.
The programmers have to
4. Open doors make sure that they create a
suitable algorithm.
18 W H AT I S C O D I N G ?

Becoming a coder SEE ALSO


What is 22–23
Scratch?

Coders are the people who write the programs behind
everything we see and do on a computer. You can create
What is 86–87
Python?

your own programs by learning a programming language.

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:

A powerful language for building Ideal for programs that need to


C computer operating systems. MATLAB carry out lots of calculations.

Ada Used to control spacecraft,


satellites, and airplanes. Ruby Automatically turns lots of
information into web pages.

Java Works on computers, mobile


phones, and tablets. JavaScript A language used to build
interactive websites.

A visual language that’s ideal A text-based language that can


Scratch for learning programming.
This is the first language Python be used to build all kinds of
things. It’s the second language
covered in this book. covered in this book.

What is Scratch? SCRATCH File Edit Tutorials Untitled Share See Project Page scratch-cat

Code Costumes Sounds

Scratch is a great way to start Motion


Motion
move 10 steps

coding. Programs are created Looks


turn 15 degrees
The program
by connecting together blocks appears on this
Sound turn 15 degrees

Events
side of the screen
of code, instead of typing it out.
go to random position

Control go to x: 0 y: 0

Scratch is quick and easy to use, Sensing


glide 1 secs to random position

glide 1 secs to x: 0 y: 0
when clicked

and also teaches you the key


forever
Operators
go to mouse pointer
point in direction 90 move 10 steps
Variables

ideas you need to use other My Blocks


point towards mouse-pointer Sprite Sprite2 x 0 y 0
Stage

programming languages.
Show Size 100 Direction 90
forever

next costume
Backdrops
play sound bubbles until done
1
Sprite1 Sprite2

Backpack

Code is made by connecting


colored blocks together
BECOMING A CODER 19
What is Python? ghostgame
People around the world use IDLE File Edit Format Run Window Help
Python to build games, tools, and # Ghost Game
websites. It’s a great language from random import randint
to master because it can help print("Ghost Game")
you build all kinds of different
feeling_brave = True
programs. Python looks like a
score = 0
mixture of recognizable words
and characters, so it can be easily while feeling_brave:
read and understood by humans. ghost_door = randint(1, 3)
print("Three doors ahead ...")

A program written
in Python

Getting started
It’s time to start programming. All you need
is a computer with an internet connection.
This book starts with Scratch—the perfect
language to help you on your way to
becoming a coding expert. Get ready to jump
into the exciting world of computer coding.

EXPERT TIPS
Enjoy experimenting
As a programmer, you should
experiment with the code and
programs you make. One of the
best ways to learn programming
is to play around and see what
happens when you change
different parts of the code. By
tinkering and fiddling, you’ll
discover new ways of doing
things. You’ll learn much more
about computer programming
and have even more fun.
Starting
from Scratch
22 S TA R T I N G F R O M S C R AT C H

What is Scratch? SEE ALSO


Installing and 24–25
launching Scratch

Scratch is a visual programming language that
makes coding simple. It can be used to make all
Scratch 26–27
interface

sorts of fun and interesting programs. Colored blocks 30–31 ›
and code

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

Start programming Put together


1 Scratch is a programming language. 2 programming blocks
There’s not much typing, and it’s easy Scratch uses colored blocks
to get started. of code. Blocks are selected
and joined together to
make code, which is a
Write your set of instructions.
first program
in Scratch!

LINGO
Why is it called Scratch?
“Scratching” is a way of mixing
different sounds to make new
music. The Scratch programming
language enables you to mix
Make sprites move and speak pictures, sounds, and code blocks
3 Objects such as people, vehicles, Sprites like me can be
programmed to talk
to make new computer programs.
and animals can be added to a program. in speech bubbles.
These objects are called sprites. Code
blocks make them move and speak.

Sprites can be
programmed
to walk, run,
and dance
W H AT I S S C R AT C H ? 23
A typical Scratch program
Here is an example of a Scratch program. All of the action takes ▷ Running a program
place in an area on the screen called the “stage.” Background Starting a program is called
“running” it. To run a
images and sprites can be added to the stage, and you can
program in Scratch, click the
write code (sometimes called scripts) to make things happen. green flag above the stage.

The green flag


runs a program

The red button


stops a program

Background image

Adding code makes


the shark sprite move

Several sprites can be


on the stage at once

▷ Code blocks make


REMEMBER
sprites move
when clicked
Scratch contains blocks Scratch programs
that can be used to make forever
code. This code 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 seconds backgrounds, sounds, and code
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

Installing and REMEMBER


Scratch website
launching Scratch Find the Scratch website at:
http://scratch.mit.edu/
To start programming in Scratch, you need to
have the Scratch software. It can be installed
on a computer, or it can be used online.

Create a Scratch account


A Scratch account can be used to share the programs you
make on the Scratch website. It’s also used to save work
online. Visit the Scratch website at: http://scratch.mit.edu/
and click “Join Scratch” to create your account.

▷ Getting started
The way Scratch is
set up depends on
whether it’s used over
the internet (online)
or from downloaded
software (offline).

1 Set-up 2 Launching Scratch

Visit http://scratch.mit.edu and click


Once you’ve joined the Scratch website,
“Join Scratch.” Fill in the form to create a
click “Sign in,” and enter your username
username and password. Make sure you
and password. Click “Create” at the top of
get permission from your parent or
the screen to begin a new program.
Online caregiver to join the website.

Download the software version of


Scratch at: http://scratch.mit.edu/ Double-click the icon on the desktop
download. Run the installation program and Scratch will start, ready to begin
and a Scratch icon will appear programming.
Offline on your desktop.
I N S TA L L I N G A N D L A U N C H I N G S C R AT C H 25
EXPERT TIPS Different versions of Scratch
Mouse control This book uses Scratch 3.0, the latest version of
Scratch. Use this version if possible. An older
The “click” instruction means press version will differ slightly.
the left mouse button if there is
more than one. “Right-click” means
use the right mouse button. If a
mouse only has one button, hold
the “CTRL” key on the keyboard
and press the mouse button to
perform a right-click.

△ Scratch 2.0 △ Scratch 3.0


The older version of Scratch The latest version of Scratch has
has the stage on the left of some new commands and the
the screen. stage is on the right of the screen.

3 Saving work 4 Operating systems

When you’re logged in, Scratch The web version of Scratch 3.0 works
automatically saves work for you. To find well on Windows, Ubuntu, and Mac
your work, click your username at the top operating systems. This version will Ready?
right of the screen and click “My Stuff.” also work on tablets. Let’s go!

Click the “File” menu at the top of The offline version of Scratch works well on
the screen and choose “Save to your computers with Windows and Mac operating
computer.” Ask the person who owns systems. It doesn’t work well on computers
the computer where you should save that use Ubuntu. If a computer uses Ubuntu,
your work. try the online version instead.
26 S TA R T I N G F R O M S C R AT C H

Scratch interface
This is Scratch’s screen layout, or
“interface.” The stage is on the right and Change
language
Menu
options
Costumes
tab
programs are created in the middle.

SCRATCH File Edit Tutorials

S TA G E A R E A Code Code Costumes Sounds


BLOCKS CODE tab
PA L E T T E AREA
Motion Sounds tab
Motion
SPRITES move 10 steps
LIST
Looks
turn 15 degrees

B A C K PA C K S TA G E I N F O
Sound turn 15 degrees
Select different
△ Scratch map types of blocks
The stage is where programs run. Events go to random position
Sprites are managed in the sprite
list and code blocks can be found Control go to x: 0 y: 0
in the blocks palette. Build code in
the code area. glide 1 secs to random position
Sensing

glide 1 secs to x: 0 y: 0
Operators

EXPERT TIPS
point in direction 90
Menu options Variables

point towards mouse-pointer


This is what the menu options My Blocks
at the top of the screen do.
Drag blocks
Save work or start
File from here
a new project. into the code
area to make
Undo any mistakes or some code
Edit speed up the time between
code blocks.
Backpack

If you get stuck, find


Tutorials
help here.
Store code blocks, sprites, sounds,
and costumes in the backpack
S C R AT C H I N T E R FA C E 27

▽ Experiment
Click the buttons and tabs to explore
and experiment with the Scratch
Program interface. The projects that follow
name box explain how to use them.

Untitled Share See Project Page scratch-cat

Current sprite
selected Click for full
screen view

when clicked

forever

go to mouse-pointer
Click a sprite on the
move 10 steps stage or in the sprites
list to select it

Blocks snap together—use


the mouse to move
them around

forever

next costume

play sound hoot until done

Stage
Sprite Owl x 20 y 80

These code blocks


control the owl sprite Show Size 100 Direction 90

Zoom in on Backdrops
code blocks
1
Owl Cat Turtle

Build Blue box around Button to add Button to change


code here the selected sprite new sprites the background
28 S TA R T I N G F R O M S C R AT C H

Sprites SEE ALSO

‹ 26–27 Scratch
interface
Sprites are the basic components of Scratch. Every Scratch
program is made up of sprites and the code that controls
Costumes 40–41 ›
them. The “Escape the dragon!” program on pages 32–37
Hide and seek 42–43 ›
uses the cat, dragon, and donut sprites.

What can sprites do?


Sprites are the images on the stage. Code blocks are We can make lots
programmed to make them do things. Sprites can be of different sounds.

instructed to react to other sprites and the user of the


program. Here are a few things sprites can do:

Move around the stage React when they touch things

Change their appearance Be controlled by the user

Play sounds and music Talk in speech bubbles

Sprites in the Scratch interface


Each project can have several sprites, and each one can The code being
shown belongs to the
have its own code. It’s important to add code to the sprite shown here
correct sprite, and to know how to switch between them.
SCRATCH File Edit Tutorials Untitled Share See Project Page scratch-cat

Code Costumes Sounds

Motion
Motion
move 10 steps when clicked

forever
Looks
turn 15 degrees
Select different types go to mouse-pointer

move 10 steps
turn 15 degrees
of blocks by clicking
Sound

on these icons Events go to random position


forever
Control go to x: 0 y: 0
next costume

glide 1 secs to random position play sound pop until done


Sensing

glide 1 secs to x: 0 y: 0
Operators

point in direction 90
Variables
Stage
point towards mouse-pointer Sprite Sprite1 x 0 y 0
My Blocks Select different
▷ Sprites and code sprites by clicking Show Size 100 Direction 90

A project can have lots on them Backdrops


1

of sprites, and each sprite


Sprite2 Sprite1 Sprite3

can have lots of code. Backpack


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.
▽ Create a sprite ▽ Copy or delete a sprite
Select “Choose a Sprite” in the sprites list and use the To copy a sprite and its code, right-click on
buttons in the pop-up menu to add or create a sprite for it in the sprites list and choose “duplicate.”
your program.
Select a picture
from your computer Sprite Sprite1 x 20 y 80
Add a
random Show Size 100 Direction 90
sprite
Create a
new sprite
Choose from
duplicate This option
the library
Sprite1
copies a sprite
delete
Choose a Sprite
export
This option
deletes a sprite

Naming a sprite 1 Select the sprite


Select a sprite in the sprites list
When you start a new program in by clicking on it.
Scratch the cat sprite is called “Sprite1.”
It’s easier to write programs if you give Sprite Sprite3 x 20 y 80
your sprites more meaningful names.
It also makes it easier to understand Show Size 100 Direction 90

and manage their code.

Sprite1 Sprite2 Sprite3

Change the name


2 In the information panel, click on the text
Click on a sprite
to select it
box and use the keyboard to change the name
of the sprite. The sprite has now been renamed.

Sprite Sprite3 x 20 y 80
Type the
sprite’s new Show Size 100 Direction 90
name here
Spike The sprite’s new
name appears in
Sprite1 Sprite2 Sprite3 the sprites list
30 S TA R T I N G F R O M S C R AT C H

Colored blocks SEE ALSO

‹ 26–27 Scratch

and code
interface
Escape the 32–37
dragon!

Blocks are color coded depending on what they do.
Putting them together builds code that runs in the
order in which they are placed.

Colored blocks Functions of blocks


There are nine different types of blocks in Different types of blocks do different things
Scratch. Switch between them using the in programs. Some of them make sprites
buttons in the blocks palette. Click on a move, some manage sounds, and some
color to see all the blocks in that section. decide when things happen.
Detects when
the green flag
Code is clicked
when clicked
Checks
Motion whether the
Motion
move 10 steps key space pressed? spacebar
is pressed
Looks
turn 15 degrees △ Events and sensing
Yellow “Events” blocks make things happen. Light
Sound turn 15 degrees
blue “Sensing” blocks detect information about the
keyboard, mouse, and what a sprite is touching.
Events go to random position

This block
Control go to x: 0 y: 0 rotates the
turn 15 degrees sprite
glide 1 secs to random position
Sensing This block
glide 1 secs to x: 0 y: 0 think Hmm... for 2 seconds shows a
thought
Operators bubble

point in direction 90 start sound Meow ▾ This block


Variables
plays a sound
point towards mouse-pointer recording
My Blocks pen down This block draws a line
as a sprite moves
Button to show the
orange “Variables” blocks △ Motion, looks, sound, and pen
These blocks control what a sprite does on
screen—this is called the output of a program.
Pick a sprite and try each block to see what it does.
COLORED BLOCKS AND CODE 31
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

△ Variables and operators △ Control


Orange “Variables” 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.

Flow of code
When a program runs, Scratch carries out the
instructions on the blocks. It starts at the top
of the code and works its way down.

◁ The thoughtful cat


when clicked
When this code is used with the cat sprite, the
wait 2 seconds cat will wait 2 seconds, think for a moment,
pause 1 second, and then move.
think Hmm... for 2 seconds

wait 1 seconds Programs run


from top REMEMBER
move 100 steps to bottom
Stopping the code
This instruction
is run last To stop any code blocks in a
program that are running, click the
red stop button above the stage.
Running the code It’s shaped like an octagon. You’ll
When the code is running, it glows. Use the green find it beside the green flag button
used to start your program.
flag button on the stage to run the code or click
a line or block of code to make it run.
The glowing outline
means this code
is running Press this button to
when clicked stop a program

wait 2 seconds

think Hmm... for 2 seconds


◁ Testing code
wait 2 seconds Test whether your
code is working
move 100 steps properly by
clicking on it.
32 S TA R T I N G F R O M S C R AT C H

PROJECT 1

Escape the dragon! SEE ALSO

‹ 24-25 Installing and


launching Scratch
This project introduces some basic Scratch
coding. It shows how to make a game to help
‹ 26–27 Scratch
interface
the cat sprite dodge a fire-breathing dragon.

Make the cat move Code

This stage explains how to make the cat sprite


Control
move around and chase the mouse-pointer. Motion

Follow the instructions carefully because otherwise Looks


wait 1 seconds

the game might not work.


repeat 10
Sound
Open Scratch. Click “File” on Click the orange
1 the menu and select “New” to 2 “Control” button in Events
start a new project. The cat the blocks palette.
sprite appears. Then click the Control
forever
“forever” block, keep
the mouse button Sensing

Every new project in pressed down, and


Scratch includes me, drag the block into Operators

the cat sprite. the code area Click this block


on the right. Release Variables and drag it to
the button to drop the code area
My Blocks
the block.
Blocks palette

Click the blue “Motion” button in the blocks Click the “Events” button in the blocks palette.
3 palette. The blue “Motion” commands will 4 Drag the “when green flag clicked” block into
appear. Drag the “point towards” block the code area. Join it to the top of your code.
into the code area and drop it inside the This block snaps to
“forever” block. the top of the code

Drop this when clicked The menu shows


block inside the “mouse-pointer”
forever “forever” block forever has been chosen

point towards mouse-pointer point towards mouse-pointer


ESCAPE THE DRAGON! 33

Try running the program by clicking the


5 green flag at the top of the stage. As you move
the mouse around the stage, the cat turns to
face the mouse-pointer.

Move the mouse


and watch the cat
spin around
following it
Run the Stop the Use the
program program full screen

Click the “Motion” button again, and drag the The picture behind the sprites is called a backdrop.
6 “move 10 steps” block into the code area. Drop 7 To the right of the sprites list is a button to add a
it inside the “forever” block. Click the green flag backdrop from the library. Click it, select the “Space”
button so the cat chases the mouse-pointer! theme from the list, and then click the “Stars” image
to select this backdrop.

when clicked

forever

point towards mouse-pointer


Choose a backdrop
from the library
move 10 steps

The “forever” block Drop this block inside Choose a Backdrop


automatically stretches the “forever” block
to make room

SCRATCH File Edit Tutorials Untitled Share See Project Page scratch-cat
◁ Cat in space
Code Costumes Sounds
The Scratch interface
Motion
now looks like this. Run
Motion
move 10 steps the program and the cat
Looks
turn 15 degrees chases the mouse-pointer
Sound turn 15 degrees
through space.
when clicked
Events go to random position
forever

go to x: 0 y: 0 go to mouse-pointer
Control
move 10 steps
glide 1 secs to random position
Sensing

glide 1 secs to x: 0 y: 0
Operators

point in direction 90
Variables
Stage
point towards mouse-pointer Sprite Sprite1 x 0 y 0
My Blocks
Show Size 100 Direction 90

Backdrops Scratch automatically saves


Sprite1
2
work if you’re online. To save work
while offline, click “File” and
Backpack select “Save to your computer.”
34 S TA R T I N G F R O M S C R AT C H

ESCAPE THE DRAGON!


Add a fire-breathing dragon
Now that the cat can chase the mouse, make a dragon to chase
the cat. Don’t let the dragon catch the cat, or it will get scorched.

Below the sprites list is a button to add a Add this code to the dragon sprite. Click the
8 sprite from the library. Click it, choose the 9 color-coded buttons in the blocks palette to
“Fantasy” category from the menu on top, select the blocks below, and then drag them into
and select “Dragon”. the code area. The dragon will now chase the cat.

The dragon is
highlighted in when clicked
Use the menu to
blue to show it’s make the dragon
your current sprite set size to 50 % point towards the
cat (“Sprite1”)
Add a forever
sprite from
the library point towards Sprite1

move 10 steps
Choose a Sprite
Dragon

Click the blue “Motion” button and drag the “go to With the dragon sprite highlighted, add this
10 x:0 y:0” block into the code. Click the number boxes 11 second bit of code to the code area. The “wait
in the block and change them to -200 and -150. until” block is found in the “Control” section, and
Click the purple “Looks” button and add the “switch the “touching” block is in the “Sensing” section. The
costume to” block to your code. dragon now breathes fire when it touches the cat.
Use the menu to
choose “Sprite1”
when clicked when clicked (the cat)
Place this block
set size to 50 % here to make the wait until touching Sprite1 ?
dragon start in
go to x: -200 y: -150 the corner
switch costume to dragon-c
switch costume to dragon-a
stop all Drag this
forever block inside
Use the menu to This “Control” block the “wait
choose “dragon-a”. stops the program until” block
point towards Sprite1 The dragon will start
in this costume
move 4 steps Costume
“dragon-c” makes
the dragon
Change 10 to 4 to make breathe fire
the dragon move slower
than the cat
ESCAPE THE DRAGON! 35

In coding, a “variable” is used to store information. Type in the variable name “Time” and make sure
12 This step uses a variable to create a timer to measure 13 the “For all sprites” button is selected underneath,
how long a player survives before getting toasted. then click “OK.” This means that the cat, dragon,
Click the “Variables” button and then click “Make and any other sprites can use the variable.
a Variable.”
New Variable
Variables
Click to
create
Make a Variable
a variable New variable name:
Select Time
my variable this option
then click
set my variable to 0 “OK” For all sprites For this sprite only

change my variable by 1 Cancel OK

The variable name and the number in it appear EXPERT TIPS


14 on the stage in a small box. Right-click it and
Make the game harder
choose “large readout.” This shows just the
number in the box.
Try changing the speed or size of your sprites.
The number in your
“Time” variable Make the dragon faster:
Time 0 move 5 steps
normal readout
Make the dragon larger or smaller:
large readout
Change the value inside the
slider number box to make a sprite Size 100
larger or smaller. See how big
you can make each sprite.

Making a variable adds


15 new blocks to the “Variables” when clicked
This resets the
section of the blocks palette. timer to 0 when
Drag the “set my variable to 0” set Time ▾ to 0 the game starts
and “change my variable by 1”
blocks from the “Variables” forever Choose from the
section to the code area to “Control” section.
wait 1 seconds Adds a 1 second delay
make this new code. Click
the drop-down menu in both change Time by 1
blocks and choose “Time”.
You can give this code to Increases the Don’t forget to
any sprite. timer by 1 save your work
36 S TA R T I N G F R O M S C R AT C H

ESCAPE THE DRAGON!


Add a delicious donut
Scratch comes with lots of sprites in its library. Make the
game trickier by adding a donut sprite to the program
for the cat to chase.
Click the button below the sprites list to Add this code to the donut. The “mouse down?”
16 add a new sprite from the library. Search 17 block can be found in the “Sensing” section, and
for “Donut” and select it. the “go to mouse-pointer” block in the “Motion”
section. This code makes the donut follow the
mouse-pointer when the mouse button is clicked.

This is a
when clicked “Sensing”
block
Add a forever
sprite from Donut
the library wait until mouse down?

The donut go to mouse-pointer


is now your
Choose a Sprite
selected sprite
Click the drop-down
menu and select
“mouse-pointer”

Select the cat in the sprites list so its code appears. Click the green flag button to run the program.
18 Click the arrow in the “point towards mouse-pointer” 19 Press the mouse button and the donut moves
block and choose “Donut”. Do this so that the cat to the mouse-pointer. The cat follows the
follows the donut instead of the mouse-pointer. donut, and the dragon chases the cat.

Click to open Save the cat


when clicked the menu from the
dragon!
forever

point towards Donut

move 10 steps mouse-pointer

Dragon

Donut
Choose the
donut from
Move the
the drop-
donut using the
down menu
mouse-pointer
ESCAPE THE DRAGON! 37

Now add some music. Click the “Sounds” tab Search for the “Drip Drop” sound
20 above the blocks palette. Each sprite has its own 21 and select it. The sound is added to
sounds, and they are managed here. Click the the cat sprite, and appears in the
button on the bottom left to add a sound from “Sounds” area.
the library.

Add a Delete
sound from sounds here
the library Drip Drop
2.86

Choose a Sound
This is how long
the sound lasts

Click the “Code” tab to go back to the


22 code area. Add this code to the cat sprite, Congratulations!
so it plays the music all the time. Run the You’ve written your
program and have fun! first computer game.

Choose “Drip
when clicked Drop” from the
drop-down menu
forever

play sound Drip Drop until done


Don’t forget to
save your work
Use the “Sound” button
to find this block

REMEMBER
Achievements
This project has shown some of Made sprites move: You’ve made sprites
the things Scratch can do. Here’s chase each other.
what you’ve achieved. Used a variable: You’ve created a timer for
your game.
Created a program: By combining blocks of Used costumes: You’ve changed the dragon’s
code into code, you’ve put together a game. appearance using different costumes.
Added pictures: You’ve used both backdrops Added music: You’ve added a sound, and
and sprites. made it play when your program runs.
38 S TA R T I N G F R O M S C R AT C H

Making things move SEE ALSO

‹ 28–29 Sprites
Computer games are all about firing, dodging, catching, Coordinates 56–57 ›
and escaping. Characters might run, fly spaceships, or
drive fast cars. To create great games in Scratch, you first
need to learn how to make sprites move.

Motion blocks
The dark blue “Motion” blocks make sprites move. Start a new project
by clicking the “File” menu and choosing “New.” The new project
begins with the cat in the middle of the stage, ready for action. Add this block to tell
Scratch when to start
running the code
First steps
1 Drag the “move 10 steps” block from the “Motion”
when clicked
Click the white
section of the blocks palette and drop it into the code window on the
area to its right. Drag an orange “forever” block from block and type
forever in a different
the “Control’’ section of the blocks palette and drop it
number to
around this block. Click the green flag on the stage move 10 steps change how far
to run the program. The cat moves until it hits the the cat moves
edge of the stage.
The “forever” block
repeats anything
inside it endlessly

Bouncing Rotating
2 Drag an “if on edge, bounce” block inside your 3 Drag the blue “set rotation style” block into the
“forever” block. Now the cat bounces when it hits the “forever” block and drop it below the “if on edge, bounce”
edge of the stage. The cat is upside down when block. Now the cat will face the right way up after
it walks to the left. bouncing off the edge of the stage.

Try changing
when clicked 10 to 30 to make when clicked
the cat sprint!
forever forever The cat faces left or
right, and is always
move 10 steps move 10 steps the right way up

if on edge, bounce if on edge, bounce

This block makes set rotation style left-right


the cat turn around
when it hits the left-right
edge of the stage
don’t rotate The cat doesn’t
The cat faces the direction rotate at all
it’s walking in, sometimes all around
upside down
MAKING THINGS MOVE 39
Which direction? The direction -90°
means “left”

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 Type in a new number
the cat change direction to change the direction

Heading the
of the cat 180°
4 right way
point in direction -90 △ Compass
Drag the “point in direction” Directions are measured in
block into the code area. degrees, from 0° at the top.
Click on the number in the Move the You can use any number
white window and type in arrow on the between -179° and +180°.
a new direction. drop-down
compass to The cat will follow
select a the mouse-pointer
direction for
the cat

Click the green flag


Cat and mouse to start the program
5 Remove the “move
when clicked
10 steps” and “if on edge,
bounce” blocks from the forever
code. Now drag a “point
toward” block into the point towards mouse-pointer
“forever” block. Open
the menu and choose
“mouse-pointer”. REMEMBER
As the mouse-pointer moves,
the cat turns to face it Sprites
Chase the mouse
6 Can the cat catch the mouse? Drag a “move 10
steps” block into the “forever” loop. Now the cat walks
toward the mouse-pointer.

when clicked Sprites are objects in a Scratch


program that you can move
forever around (see pp.28–29). Every new
project stars the cat sprite, but you
point towards mouse-pointer can add cars, dinosaurs, dancers,
and all sorts of other sprites from
move 10 steps the library. You can even have a go
Adjust the number of steps at designing your own.
to change the cat’s speed
40 S TA R T I N G F R O M S C R AT C H

Costumes SEE ALSO

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

Changing costumes Code Costumes Sounds


Different costumes can make your sprite
Costume costume2
look like it’s moving its arms and legs. When
you switch between the cat’s two costumes, Outline 4
Fill
it looks like it’s walking. Start a new project costume 1
96 x 101

and try this example.

One of the costume2


cat’s costumes 93 x 106

Different costumes
1 Click the “Costumes” tab to see the cat’s
costumes. They show the cat with its legs and
arms in two different positions.

Make the cat walk Change the cat’s costume


2 Add this code to make the cat walk. 3 Add the “next costume” block from the
When it moves, it slides across the screen without “Looks” section of the blocks palette, so the cat
moving its legs, because its picture always stays changes its costume with each step. This makes
the same. its legs and arms move.

when clicked when clicked


This picks the
forever forever next costume

move 10 steps next costume

if on edge, bounce wait 0.5 seconds Pauses so


the costumes
move 10 steps don’t change
too quickly
if on edge, bounce
The colors remind
you where to find
the blocks
COSTUMES 41
Dancing ballerina The green flag starts
the ballerina’s dance
Now try making a ballerina dance. Add
the ballerina sprite from the library. Select when clicked
your cat in the sprites list and drag its forever
Ballerina
code on to the ballerina in the sprites list.
This copies the code to the ballerina. next costume

wait 0.5 seconds

Drop the code on to the move 10 steps


ballerina in the sprites list
if on edge, bounce

△ Ballerina’s code
The same code works for the ballerina and
the cat. The ballerina has four costumes, and
she uses them all as she dances on the stage.

EXPERT TIPS
Switching
You can choose to show a specific
switch costume to ballerina-a
costume for your sprite using
the “switch costume to” block.
Switch costumes: Use the menu in the block to choose a costume.
You can use this block to
choose a particular position
for your sprite. switch backdrop to backdrop1

Switch backdrops: Change the picture on the stage with this block.

Adding speech bubbles


when clicked The ballerina
You can add speech bubbles to make your stands up
sprites talk when they change costumes. forever
Use the “say Hello! for 2 seconds” block and
switch costume to ballerina-a
change the text in it to make your sprite
say something else. say Up! for 1 seconds

switch costume to ballerina-b


The ballerina
says “Up!” say Down! for 1 seconds

She crouches
and says “Down!”
42 S TA R T I N G F R O M S C R AT C H

Hide and seek SEE ALSO

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

▷ Hide and show


To make a sprite vanish, use the “hide” hide
block. When you’re ready for it to be
seen again, use the “show” block.
These blocks are found in the “Looks”
show
section of the blocks palette.

▽ Disappearing cat
Try this code using the cat sprite. It
disappears and reappears but it keeps
moving, even when you can’t see it. EXPERT TIPS
Showing sprites
when clicked Select a sprite in the sprites list. You
will see an information panel above
forever this list. There, you can use the “Show”
icons to show or hide a sprite.
wait 1 seconds This block hides
the cat
hide
This block
turn 90 degrees rotates
Sprite Sprite1 x 0 y 0
the cat
move 100 steps clockwise
Show Size 100 Direction 90

wait 1 seconds The cat still


moves even
when hidden Shows a hidden sprite
show
This block
shows the
cat again
HIDE AND SEEK 43
Sizes and effects Choose the type of effect
from the drop-down Change the
Code can be used to change the size menu. The “pixelate” numbers in the
effect makes the sprite blocks to set
of a sprite and add special effects to it. become blurred how strong
the effect is
Type in positive numbers
to make sprites bigger
and negative numbers
change size by 10 to make them smaller change pixelate effect by 25

Higher numbers make set color effect to 0


sprites bigger and
lower numbers make Each color is
them smaller. 100 is represented by a
set size to 100 % normal size clear graphic effects number. Change
the number to
△ Changing a sprite’s size Resets all △ Adding graphic effects set the color
These two blocks can be used to the effects The graphic effects in Scratch can be
make a sprite bigger or smaller, used to change a sprite’s appearance
either by a set amount or by a or distort its shape. They’re fun to
percentage of its size. experiment with.

Using effects to teleport


You’ll never know where
Add a ghost sprite from the “Fantasy” category I’ll appear next!
of the sprites library, and create the code shown
below. It makes the ghost appear to teleport
when clicked.

The “ghost” effect makes the sprite


when this sprite clicked fade slightly; by repeating this
block 20 times the sprite fades
clear graphic effects away completely

This “Operators” block


repeat 20 selects a random This block
horizontal position selects a random
change ghost effect by 5
vertical position

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

Events SEE ALSO


Sensing 66–67
and detecting

The yellow “Events” blocks in Scratch start code
when certain things happen—for example, when
Sending 70–71
messages

the user presses a key, clicks a sprite, or uses
a webcam or microphone.

Clicking LINGO
Code can be added to a sprite that makes What is an event?
it do something if the sprite is clicked while
the program is running. Experiment with An event is something that
happens, such as a key being
different blocks to see what a sprite can
pressed or the green flag being
do when clicked. clicked. The blocks that look for
Drag this block events go at the top of the code.
from the “Events” The code waits until the event
menu to start happens, and then it runs.
the code
when this sprite clicked

play sound Meow until done


The cat sprite
△ Click a sprite already has this
This code makes the cat sprite sound effect
meow when you click it. attached to it

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

say Hello! for 1 seconds say Goodbye! for 1 seconds

△ Say hello △ Say goodbye


Add this code to a sprite and when the This code uses the G key to make a sprite
H key is pressed, the sprite says “Hello!” say “Goodbye!”
EVENTS 45
Sound events EXPERT TIPS
If your computer has a microphone, sprites can Asking permission
detect how loud the sounds in a room are on a
scale of 0 (very quiet) to 100 (very loud). Use the Scratch asks for permission
to use your webcam and
“when loudness” block to make the code start
microphone. When the box
when the sounds are loud enough. pops up, click “Allow.”

Make the cat sensitive to noise Shout at the cat


1 Start a new project, and add the “Room 2” 2 Shout into the microphone—the cat will
backdrop image from the backdrop library. jump out of its seat with fright and meow. It
Drag the cat sprite on to the chair and add will also respond to music and other sounds
the code shown here. if they are loud enough.
Change the
number to 40

when loudness > 40 This makes the


cat jump up
go to x: 145 y: 130

play sound Meow until done

go to x: 145 y: 0 This makes the cat


fall back down

Change the
Webcam motion detector number to 40

If you have a webcam, it can be used with when video motion > 40
Scratch too. Add this code to the cat, and
play sound Meow until done
when you wave at it through the webcam,
it will meow back. To use the webcam △ Detect motion
blocks, click “Add Extension” at the bottom Use the “when video motion” block. The code
left, then choose “Video Sensing”. will start when you’re moving around enough.

EXPERT TIPS
Backdrop changes
Choose the
A sprite can react to the backdrop backdrop here
changing. For example, you can have a
backdrop that makes the sprite disappear.
when backdrop switches to Desert
Upload a new backdrop from the stage
list in the bottom right of the screen, and hide
then add the “when backdrop switches Hides the sprite when
to” block to do this. the backdrop changes
46 S TA R T I N G F R O M S C R AT C H

Simple loops SEE ALSO


Complex 68–69
loops

A loop is a part of a program that repeats itself. The
loop blocks (from the “Control” section) tell Scratch
Loops 122–123
in Python

which blocks to repeat, and how many times. They save
us from adding the same blocks over and over again.
Drop blocks inside this loop
to repeat the actions forever

Forever loop forever


Whatever you put inside the “forever” block move 10 steps
repeats itself forever. There’s no option to
join anything at the bottom, because a if on edge, bounce
“forever” loop never ends.

No option to add △ Looping forever


When the actions
more Scratch blocks When the last block inside the finish the program
loop ends, the loop goes back goes back to the start
to the start again. of the loop again

Repeat loop
To repeat an action a certain number of times, use a
“repeat 10” block. Change the number in it to set how
many times the loop will repeat itself. Add the “Dinosaur4” REMEMBER
sprite to a new project and build it this code. Loop block shape
The loop blocks are shaped like
when clicked
jaws. Drop the blocks that you
repeat 3 Change the number to 3 want to repeat into the jaws, so
the loop wraps around them. As
switch costume to dinosaur4-d you add more blocks, the jaws
stretch to make room for them.
wait 0.5 seconds The sprite stands
on one leg
switch costume to dinosaur4-c
The sprite stands
wait 0.5 seconds
up straight

You can add more blocks


△ Dancing dino after a “repeat” loop
When the green flag is clicked,
the dinosaur dances. He repeats
his dance moves three times.
SIMPLE LOOPS 47
Nested loops
Loops can also be “nested,” which means they can be put
inside each other. In this code, the dinosaur finishes his
dance by walking right and left and then thinking for a Try giving
me some
moment. When he’s got his breath back, he dances again looping music!
and stops only when you click the red stop button.

Click on the green flag above


the stage to start the code

▷ Loops in loops
This “forever” loop when clicked
has several repeat
loops inside it. Make forever
sure the blocks are
inside the right loops, repeat 3
otherwise the program
won’t work properly. switch costume to dinosaur4-d

wait 0.5 seconds

The “forever” switch costume to dinosaur4-c


block surrounds
everything wait 0.5 seconds

The previous
dance move repeat 3
(see opposite)
move 20 steps

wait 0.5 seconds

The dinosaur
moves three
steps to the right wait 1 seconds
This block creates
repeat 3 a short pause

move -20 steps

wait 0.5 seconds


The dinosaur
moves three
steps to the left

think I love to dance! for 2 seconds

Type in what you want the dinosaur to


think—it will appear in a thought bubble
48 S TA R T I N G F R O M S C R AT C H

Pens and turtles SEE ALSO

‹ 44–45 Events
Each sprite has a pen tool that can draw a line behind ‹ 46–47 Simple loops
it wherever it goes. To create a picture, turn on the pen
and then move the sprite across the stage, like moving
a pen across paper. To use the pen blocks, click “Add
Extension” at the bottom left, then choose “Pen”.

Pen blocks pen down pen up


The dark green blocks are used to
Turns the Turns the
control the pen. Each sprite has its own pen on pen off
pen that can be turned on by using the
“pen down” block and turned off using
erase all stamp
the “pen up” block. The size and color
of the pen can also be changed. Clears all Leaves a
drawings picture of
the sprite
△ Playing with pens
Experiment with how you can use
the pen blocks to make drawings.

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

Draws a line pen down


Turns the
of the square
pen on
repeat 4
Turns the
▷ Change the shape corners
move 100 steps
This code will draw a
square. To draw a triangle, turn 90 degrees
change the “repeat” loop
to repeat three times wait 1 seconds
for the three sides, and Makes it easier
change the turn from to see what’s
90 to 120 degrees. happening
PENS AND TURTLES 49
Skywriting You can only use
colors that appear
In this program, you control a plane. As you fly it will leave on the Scratch
interface. To select
a smoke trail, so you can draw in the sky. Start a new project red, click in the oval
and upload a plane sprite, then add this code. and then move the
button for “Color” to
▷ Flying high the extreme left or
when clicked extreme right
Use the left and right keys to turn the
to choose red
plane. Switch on the smoke with the “a” set size to 20 %
key and turn it off with the “z” key. Press
the spacebar to clear the sky. set pen color to

set pen size to 3

forever Makes the


line thicker
move 2 steps

if on edge, bounce
Keeps the
Keeps the plane
plane moving
on the stage

LINGO when right arrow key pressed


Turtle graphics turn 10 degrees
Rotates
Using sprites to draw pictures right
is called “turtle graphics.”
That’s because there’s a type of when left arrow key pressed
robot called a turtle that can be
moved around the floor to draw turn 10 degrees
pictures. The first programming Rotates
left
language to use turtle graphics
was called LOGO.
when a key pressed

pen down
Turns the pen on

when z key pressed

pen up
Turns the pen off

when space key pressed

erase all
Clears the pen trail
50 S TA R T I N G F R O M S C R AT C H

Variables SEE ALSO


Math 52–53 ›
In coding, a variable is the name for a place Variables 108–109
in Python

where you can store information. Variables are
used to remember things such as the score, a
player’s name, or a character’s speed.

Creating a variable ◁ Storing data


You can create a variable to use in your program Variables are like
boxes where you can
using the “Variables” section of the blocks palette. store different bits of
Once a variable has been created, new blocks information for use
appear in the blocks palette ready for you to use. in your program.

Make a variable Name the new variable


1 First, click the “Variables” button in 2 Give the variable a name that will help you
the blocks palette. Then select the “Make to remember what it does. Select which sprites
a Variable” button. will use the variable, then click “OK.”
Click here to
create a variable
New Variable
Variables
New variable name:
Make a Variable
Type in a
steps
name for
my variable your variable
For all sprites For this sprite only here

Choose whether the Cancel OK


variable will be used
by all sprites or just
the one selected

Check to show the The variable block can be


variable on the stage used inside other blocks

A new variable is created


3 Once a new variable has been
steps Use this block to give
the variable a value
created, new blocks appear in the blocks
palette. The menus inside these blocks let set steps to 0 Change the value of a
you select which variable they apply to, if variable using this block.
you have created more than one. A negative number will
change steps by 1 decrease its value
VA R I A B L E S 51
Using a variable
Variables can be used to change a sprite’s speed.
This simple bit of code shows you how.

Set the value of a variable Changing the value of a variable


1 Create this code. Use the “set steps to 0” block 2 Use the “change steps by 1” block to increase
and change the number to 5. Drag the “move 10 steps” the value of the variable “steps” by 1. Put it inside the
block into the code, but drop the “steps” variable block “forever” block, so the cat keeps on getting faster.
over the “10.”
This sets the value
of the “steps” The “steps”
when clicked variable to 5 when clicked variable keeps
on increasing as
set steps to 5 set steps to 0 the “forever” loop
goes around
Here, “steps” means 5, as the and around
forever value has been set above forever

move steps steps change steps by 1

if on edge, bounce move steps steps

if on edge, bounce
Set my speed using
the “set steps to 0”
block.

EXPERT TIPS
Read-only variables
Deleting variables Some variables are set by Scratch and can’t
When you no longer want a variable, be changed. They’re still variables, though,
right-click on it in the blocks palette and because their values vary. These blocks are
then select “Delete the variable.” You’ll lose known as sensing blocks.
any information that was in it.
Tracks the distance to
Variables distance to ▾
something, such as the
mouse-pointer.
Make a Variable Variables can
be renamed
Reports the number of
here costume #
my variable the costume a sprite is
wearing.
steps
Rename variable Tells you which direction
direction a sprite is traveling in.
Delete the “steps” variable
52 S TA R T I N G F R O M S C R AT C H

Math SEE ALSO

‹ 50–51 Variables
As well as storing numbers in variables (see pp.50–51), Math 112–113
in Python

Scratch can be used to carry out all sorts of calculations
using the “Operators” blocks.

Doing sums
There are four “Operators” blocks
that can be used to do simple 7 + 22 64 – 28
calculations. These are addition, △ Addition △ Subtraction
subtraction, multiplication, The “+” block adds the two The “–” block subtracts the
and division. numbers in the block together. second number from the first.

The “think” block is used


here to print the result

think 2 + 5 11 * 10 120 / 4

△ Printing results △ Multiplication △ Division


Drag a “think” block into the code area and Computers use the “*” There’s no division sign on
drop a “+” block inside it. Now add two numbers symbol for multiplication, the keyboard, so Scratch
together and watch your sprite think the answer. because “x” looks like a letter. uses the “/” symbol instead.

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.

Create variables Set the price


1 Go to the “Variables” section of 2 Select the “set price”
set price to 50
the blocks palette and create two block and set the price of Use the drop-down
variables—“sale price” and “price”. an item to 50. menu to select “price”

Calculate the sale price


3 Use this code to calculate set sale price to price / 2
half the price of an item and
set it as the sale price. Drag the “price” variable
into the window to Add the “/” block inside
divide the price by 2 the “set sale price” block
M AT H 53
Random numbers EXPERT TIPS
The “pick random” block can be used to select a Gaming
random number between two values. This block
is useful for rolling die in a game or for when Computers often use random
numbers to add surprises to
you want to mix up a sprite’s costumes.
games. For example, an alien can
be made to appear in a random
◁ Pick a random number
pick random 1 to 10 place, or after a random amount
To pick a random month,
of time. It can be used to select
You can change change the numbers to
choose a number between
a random value, as if you were
the numbers
1 and 12. rolling a die, or a random costume
in the block
for a sprite.

This block makes the


when clicked sprite wait for two Chooses a costume
seconds before switching between 1 and 3
forever to another costume at random

wait 2 seconds
◁ Switching costumes
switch costume to pick random 1 to 3
This code changes a sprite’s
costume at random every
two seconds.

◁ Random costumes
Costumes can make a sprite
appear to move its body,
or might give it different
clothes, as shown here.

Hard math 10 mod 3 Divides 10 by 3 and gives


Simple “Operators” blocks can do most the remainder—the
Gives nearest whole number that is left over
calculations, but Scratch can also do number to 44.7
more complex math. The “mod”
block divides two numbers and gives round 44.7
the remainder, which is the number ◁ More math
Choose different functions
that is left over. The “round” block from the drop-down menu The “Operators” section
has blocks of advanced
rounds to the nearest whole number, sqrt of 9 math functions that
and the “sqrt” block gives the square can be used to do
root of a number. Calculates the square root of 9 complex calculations.
54 S TA R T I N G F R O M S C R AT C H

Strings and lists SEE ALSO

‹ 50–51 Variables
In programming, a sequence of letters and symbols Strings 114–115
in Python

is called a “string”. Strings can contain any character
on the keyboard (including spaces) and be of any length.
Strings can also be grouped together in lists. Keyboard characters are
lined up as if they were
hanging from a string

A B C D E F G H I
Working with words 1 Create a new variable
Click the “Variables” button in the blocks
Programs often need to remember words, palette and click the “Make a Variable” button.
such as a player’s name. Variables can be Create a variable called “greeting”.
created to remember these words. Scratch
Variables
programs can also ask the user questions,
which they answer by typing into a text Make a Variable
box that pops up. The following code asks
Name your
for the user’s name, and then makes a greeting
variable
sprite say “Hello” to them. “greeting”
my variable

This block puts “Hello ” into the variable


“greeting”. Leave a space at the end of “Hello ”
Asking a question
2 This code makes the
when clicked
to make the output of the program neater

sprite ask a question. The “ask” box (from the “Sensing”


Whatever the user types set greeting to Hello section of the blocks palette) makes
into the text box that pops a text box appear, which the user
up on the screen is stored ask What’s your name? and wait types their answer into
in a new variable called
“answer”. The code then say join greeting answer
combines the strings
contained in the “greeting”
and “answer” variables to The “answer” variable
greet the user. (from the “Sensing”
The “say” bubble The “greeting” section) contains
creates a speech variable holds the whatever the user
bubble for the sprite string “Hello ” typed into the text box
STRINGS AND LISTS 55
Making lists
Variables are perfect if you just want to remember one thing. To remember
lots of similar things, lists can be used instead. Lists can store many items of
data (numbers and strings) at the same time—for example, all of the high
scores in a game. The following program shows one way of using a list.

Create a list Using your list


1 Start a new project. Go into the 2 This code asks the user to type words into
“Variables” section of the blocks palette a list. Each word appears in the sprite’s speech
and click the “Make a List” button. Give bubble as it is added to the list.
your list the name “sentence”. This block makes sure the
list is empty at the start
Call your list of the program
“sentence” when clicked

New List delete all of sentence The “ask” block asks the
user to type in a word
forever
New list name: This adds the user’s
ask Add a word and wait answer to the list
sentence
add answer to sentence
For all sprites For this sprite only
think sentence for 2 seconds
Cancel OK

Adding “sentence” here


means that the list will be
The “think” block makes a shown in the thought bubble
thought bubble appear

Seeing the list


3 If you check the box beside the list in
EXPERT TIPS
the blocks palette, the list is shown on the Playing with lists
stage. You can see each new word as it’s
added to the list. These blocks can be used to change the contents of a list.
Each item in a list has a number—the first item is number 1,
and so on. These numbers can be used to remove, insert,
sentence or replace items.
Deletes the first
item in the list
1 apple Scratch
keeps track delete 1 of sentence Adds “cherry” as the
2 pear of how first item in the list
many words
3 banana are added Replaces the
to the list insert cherry at 1 of sentence
first list item
4 orange with “cherry”

replace item 1 of sentence with cherry


+ length 4 =
56 S TA R T I N G F R O M S C R AT C H

Coordinates SEE ALSO

‹ 38–39 Making
things move
To put a sprite in a particular spot, or to find out its
exact location, you can use coordinates. Coordinates
‹ 52–53 Math
are a pair of numbers that pinpoint a sprite’s position
on the stage using an x and y grid. Type in these boxes to change
the sprite’s current coordinates

x and y positions Sprite Sprite1 x 0 y 0


The x and y positions of a sprite are
shown on the Scratch interface. It can be Show Size 100 Direction 90

helpful to know a sprite’s coordinates


when writing a code.
Sprite 1

◁ Show coordinates
x position
on the stage
Check the boxes beside
y position the “x position” and △ Position of a sprite
“y position” blocks to You can see a sprite’s current coordinates in
show a sprite’s position the information panel above the sprites list.
on the stage.

x and y grid
To pinpoint a spot, count the number of
steps left or right, and up or down, from 180
y
the middle of the stage. Steps to the left
or right are called “x”. Steps up or down are 120
called “y”. Use negative numbers to move
left and down. (x: –100, y: 100)
60
(x: 180, y: 50)

–180 –120 –60 60 120 180 x


The stage is based
upon an x and y grid –60

–120

(x: 90, y: –130)


(x: –190, y: –150) –180
This sprite is 190 steps left (–190)
and 150 steps down (–150) from
the middle of the stage
C O O R D I N AT E S 57
Moving the sprite +y Positive numbers
Coordinates are used to move a sprite to a particular move sprites up
and right, negative
spot on the stage. It doesn’t matter how near or far numbers move
away the spot is. The “glide 1 secs to x:0 y:0” block from them down and left
the “Motion” section of the blocks palette makes the
sprite glide there smoothly. -x +x
Change the coordinate
numbers to make the sprite
go somewhere else
when clicked Moves the -y Moves to the
middle of the stage
sprite left
glide 1 secs to x: 150 y: 100

glide 1 secs to x: -150 y: -100 change x by -10 set x to 0

glide 1 secs to x: -200 y: 100

glide 1 secs to x: 0 y: 0 change y by 125 set y to 180

△ Control the sprite with a code △ Change x and y separately


Can you figure out the path the sprite These blocks can be used to change Moves up
to the top
will take when you run this code? x without changing y, and the other
of the stage
Try it and see! way around.

Crazy horse’s trip


Try this fun code to test out coordinates.
Select the “Horse” sprite from the sprites
library and give it the code shown below.
This program uses the “go to x:0 y:0” block
to keep moving the horse to a random
position, drawing a line behind it as it goes.

when clicked

pen down This block leaves a line


when the horse moves
forever

go to x: pick random -240 to 240 y: pick random -180 to 180

wait 0.2 seconds


This block from the “Operators” menu Selects a random
selects a random horizontal position vertical position
58 S TA R T I N G F R O M S C R AT C H

Make some noise! SEE ALSO


Sensing 66–67
and detecting

Scratch programs don’t have to be silent. Use the pink
“Sound” blocks to try out sound effects and create music.
Monkey 74–81
mayhem

You can also use sound files you already have or record
brand new sounds for your program.

Adding sounds to sprites


To play a sound, it must be added to a sprite. Each Upload a recording
sprite has its own set of sounds. To control them, from the computer
click the “Sounds” tab above the blocks palette.

Record a sound
using the computer’s
Click here to select a microphone
sound effect from
Scratch’s library

Choose a Sound

Playing a sound Turn up the volume


There are two blocks that play sounds: “start Each sprite has its own volume control,
sound” and “play sound until done.” “Until which is set using numbers. 0 is silent
done” makes the program wait until the and 100 is the loudest.
sound has finished before it moves on.
100 is the maximum volume
Use the menu to choose
which sound to play
set volume to 100 %

This block makes a sprite louder


start sound Meow or quieter—use a negative
number to make it quieter

change volume by -10


play sound Meow until done

Checking this box


The next block in the code will makes the sprite’s
not run until after the meow volume show on volume
sound has finished playing the stage
MAKE SOME NOISE! 59
Making your own music
Scratch has blocks that can be used to invent musical sounds.
You have a whole orchestra of instruments to conduct, as well
as a full drum kit. The length of each note is measured in
beats. To use the music blocks, click “Add Extension” at the
bottom left, then choose “Music”.
This decides how low or high
the pitch of a note is

play note 60 for 0.5 beats set instrument to (1) Piano

Big numbers make a note Click here to choose


longer. It can also be shorter an instrument from a
than a beat, as shown here drop-down menu

play drum (1) Snare Drum for 0.25 beats rest for 0.25 beats

Use this menu to choose This block adds a silent break


between different types in the music. Higher numbers
of drum will give you a longer break

EXPERT TIPS
Playing music Tempo
Connecting notes together makes a tune. Create a new
variable called “note” (see pp.50–51), and then add the The speed of music is called its
following code to any sprite to create a piece of music. tempo. The tempo decides how
long a beat is within a piece of
music. There are three blocks for
Set the value of the managing the tempo.
when clicked variable “note” first
set tempo to 60
set note to 1 Choose an instrument

set instrument to (1) Piano The tempo is measured in beats per


minute, or “bpm.”
forever Add a “forever” loop
around these two blocks change tempo by 20
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 “Variables” section
tempo
△ Rising scale of the blocks palette
This code makes a series of notes that play when the Checking this box makes the sprite’s
green flag is clicked. The pitch of each note gets higher tempo show on the stage.
one step 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

Roll the die SEE ALSO

‹ 40–41 Costumes
Simple programs can be both useful and fun. ‹ 46–47 Simple loops
This program creates a die that can be rolled. Play ‹ 50–51 Variables
it to see who can get the highest number, or use it ‹ 52–53 Math
instead of a real die when you play a board game.

How to create EXPERT TIPS


a rolling die Changing colors
The die in this program uses six Above the painting area are the color controls. Click
costumes. Each costume shows the solid rectangle to draw a block of solid color. Click
a face of the die with a different the empty rectangle to draw an outline of a square or
number on it—from one to six. rectangle. Use the spinner buttons to change the thickness
of the square’s lines. To choose a color, click on the “Fill”
tab. A color palette will appear in the drop-down menu.
Select the “Paint” icon in the
1 “Choose a Sprite” menu to Click for block
of solid color
Click for outline
of block
draw a new sprite.

Fill Outline 2
Paint

Change the line


Draws a width using the
Fill spinner buttons
new sprite

Choose a
Color 72
color from
the color bar

Select “Convert to Bitmap”. Click the


2 rectangle button on the left of the painting
Saturation 60
area. To make your die colorful, select Use this bar
Change the
a solid color from the palette (see box to change
brightness of a
right). Then in the painting area hold down the intensity
color by moving
the “shift” key, press the left mouse button, of a color Brightness 100
this slider
and then drag the mouse-pointer to make
a square in the middle.

Use this to select


The rectangle button
a color already
makes a square when
on the drawing
the “shift” key is pressed
ROLL THE DIE 61

Right-click on your
EXPERT TIPS
3 costume to the 1 Use the menu
to duplicate
left of the painting
the die Rotation tool
area, and choose costume
“duplicate”. Repeat To make the die appear to roll
this step until you costume1
123 x 123
when the code is run, you can
have six costumes. duplicate rotate each costume to a different
delete angle. Click on the “Convert to
Vector” button in the bottom
left-hand corner and select the
“Select” tool. When you click back
Select a costume. Click the circle button
on to the painting area, a rotation
4 on the painting area and choose a solid
tool will appear.
white color from the palette. Add spots
to each of the six costumes until you
have made all six sides of a die.

The circle button makes a


perfect circle when the “costume5”
“shift” key is pressed has 5 spots

Add the code below to the die sprite. Press


5 the spacebar to roll the die. Try it a few times
to check that you can see all of the costumes. Click and drag
this control to
Clicking the spacebar rotate the die
rolls the die
when space key pressed

switch costume to pick random 1 to 6

Sometimes you’ll roll the same number twice, and it looks like This block selects
6 the program isn’t working because the image doesn’t change. This a random costume
code makes the die change costumes five times before it stops.
Each time you press the spacebar, it looks like it’s rolling.

when space key pressed Each costume is a


different die number
repeat 5

switch costume to pick random 1 to 6

wait 0.2 seconds

Add a short pause to Don’t forget to save


see the die rolling your work
62 S TA R T I N G F R O M S C R AT C H

True or false? SEE ALSO


Decisions and 64–65
branches

Computers decide what to do by asking questions
and determining whether the answers are true or false.
Making 118–119
decisions

Questions that only have two possible answers are
called “Boolean expressions”.

Comparing numbers =
◁ The “=” block
This block will give one of two answers:
You can compare numbers using the “true” if the two numbers in the boxes
“=” block from the “Operators” section are equal, and “false” if they aren’t.
of the blocks palette.
The numbers are These numbers
equal, so “true” true are not equal, so false
appears in the “false” appears in
speech bubble the speech bubble

say 3 = 3 say 3 = 2

△ True answer △ False answer


Using an “=” block inside a speech block will make If the numbers in the block are different, the sprite’s
“true” or “false” appear in a sprite’s speech bubble. speech bubble will contain the word “false”.

Comparing variables This sign means “equals”, so the


block is asking if “age” is equal
You can use variables inside to 7. The answer here is “false”,
because “age” is 10
comparison blocks. It’s not worth age = 7
comparing fixed numbers
This sign means “more than”,
because the result will always be so the block is asking if “age” is
the same, whereas the value of greater than 11. The answer
is “false”, because 10 is not
variables can change. bigger than 11
age > 11

set age to 10
This sign means “less than”, so the
block is asking if “age” is less than
△ Create a variable 18. The answer will be “true”, as 10
Click the “Variables” button in the blocks age < 18 is smaller than 18
palette and create a new variable called
“age”. Set its value to 10 (click on the △ Comparing numbers
block to make sure the value has Find the green comparison blocks in the “Operators” menu.
changed). Drag the “age” variable into As well as checking whether two numbers are equal, you can
the comparison blocks. check whether one is greater or less than another.
T R U E O R FA L S E ? 63
EXPERT TIPS
Comparing words
The “=” block is not just used for numbers; The variable “name”
contains “Lizzie”, so the
it can also be used to check whether two answer is true
strings are the same. It ignores capital
letters when comparing strings. name = Lizzie

set name ▾ to Lizzie Drag and drop the The answer is false
variable into the because the variable
comparison block doesn’t contain “Dan”
△ Create a variable
To experiment with comparing strings,
create a new variable called “name” and name = Dan
set its value to “Lizzie”.

Not!
◁ The “not” block
The “not” block can simplify things by reversing not
The “not” block changes the
the answer of a Boolean expression. For example, answer around, from true to
it’s easier to check if someone’s age is not 10 false and from false to true.
than to check every other possible age.

age = 7 not age = 7

△ Without the “not” block △ With the “not” block


Here, 10 isn’t equal to 7, so the Adding the “not” block to the same question changes the
answer is false. answer. Because 7 does not equal 10, the answer is now true.

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.

Here, the answer is true The answer here is true


when either the left or only when both the left ◁ In practice
the right side is true and right sides are true
The top block checks whether
someone is younger than 18 or older
age > 10 and age < 15 than 65. The bottom block checks if
they are aged 11, 12, 13, or 14.
64 S TA R T I N G F R O M S C R AT C H

Decisions and branches SEE ALSO

‹ 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

The “if” blocks use Boolean if then else


expressions to decide what to If false, blocks in the
do next. To use them, put other “else” jaws will run
blocks inside their “jaws”. The
blocks inside the “if” blocks will
run only if the answer to the △ “if-then” block △ “if-then-else” block
Boolean expression is true. If a Boolean expression is If the Boolean expression is
true, the blocks between the true, the first set of blocks runs.
“if-then” block’s jaws will run. If not, the second set runs.

Using the “if-then” block


The “if-then” block lets you choose whether or not to run a
specific bit of code depending on the answer to a Boolean
expression. Attach this code to the cat sprite to try it out.

Drag the “=” block from the Is answer yes?


when clicked “Operators” section into the
“if-then” block. Then put the
ask Do you want me to meow? and wait “answer” variable (from the True False
“Sensing” section) inside it
if answer = yes then
This block is inside the jaws
play sound Meow until done of the “if-then” block, so the
cat will meow only if the
answer is true (“yes”)
Play Skip
This is the end of the
think Hmm... for 2 seconds “if-then” block meow meow
think Time to eat some fish! for 2 seconds △ How it works
The program checks
△ Meowing cat These “think” blocks are
outside the “if-then”
whether the Boolean
This program checks the Boolean expression and will run loop, so they will run expression is true. If it is,
only the part between the “if-then” block’s jaws if it is true. whatever the answer it runs the blocks inside
This means that the cat meows only when you tell it to. to the question is the “if-then” block’s jaws.
DECISIONS AND BRANCHES 65
Branching instructions
Often you want a program to do one thing if a condition is true,
and something else if it is not. The “if-then-else” block gives a
program two possible routes, called “branches”. Only one branch
will run, depending on the answer to the Boolean expression. Is answer yes?
▽ Branching program
True False
This program has two branches: one
will run if the answer is “yes”, and the
when clicked other will run if it is not.

ask Do you like me? and wait

if answer = yes then


say say
This branch “I like “That’s not
will run if the
say I like you too! for 2 seconds
answer to you too!” very friendly!”
the question
else is “yes” △ How it works
The program checks whether
say That’s not very friendly! for 2 seconds
you typed in “yes”. If so, it
shows the first message. If not,
it shows the second.

This branch will run if the


EXPERT TIPS answer to the question is
anything except “yes”
Boolean shapes
The Boolean expression blocks in Scratch
have pointed ends. You can put them into
some nonpointed shaped holes too.

mouse down?

△ ”Sensing” blocks
These blocks can test whether a sprite is touching
another sprite, or whether a button is pressed.

repeat until

△ ”Control” blocks ▷ Branches


Several “Control” blocks have Boolean-shaped Like the branches of a tree,
holes in them for Boolean expressions. branches of a program split
and go in different directions.
66 S TA R T I N G F R O M S C R AT C H

Sensing and detecting SEE ALSO

‹ 40–41 Costumes
The “Sensing” blocks enable your program to see what is ‹ 56–57 Coordinates
happening on your computer. They can detect keyboard
controls, and let sprites react when they touch each other. This block checks if a key is
being pressed. You can choose
which key to check for
Keyboard controls
Using “Sensing” blocks with “if-then” blocks allows you key space pressed?
to move a sprite around the screen using the keyboard. This block checks if the mouse
The “key pressed?” block has a menu of most of the button is being pressed
keys on the keyboard, so a sprite can be programmed
to react to almost any key. You can also link actions to mouse down?
the click of a mouse button. △ “Sensing” blocks
Putting everything inside Adding these blocks into an “if-then” block
a “forever” block means the
allows the program to detect if a mouse
code repeatedly checks for
key presses button or key is being pressed.
when clicked

forever The code checks to see if the up


arrow is pressed. If it is, the sprite
moves upward on the screen
if key up arrow pressed? then

change y by 10

if key down arrow pressed? then

change y by -10

if key left arrow pressed? then

change x by -10
△ Controlling sprites
Keyboard controls give you
precise control over your
if key right arrow pressed? then sprites, which is especially
useful in games.
change x by 10
◁ Movement code
This code lets you move sprites up,
down, left, or right using the arrow
keys on the keyboard.
SENSING AND DETECTING 67
Sprite collisions Use this block to identify when
a sprite touches another sprite
It can be useful to know when
one sprite touches another—in touching frog ?
games, for example. Use “Sensing” This block senses when a
blocks to make things happen sprite touches an area of
a particular color
when sprites touch each other, or
when a sprite crosses an area that
touching color ?
is a certain color.

Using “Sensing” blocks


Use the “Sensing” blocks to turn your controllable cat
into a game. Start by adding the movement code
created on the opposite page to the cat sprite, then
add the “Room 1” backdrop and the elephant sprite.
Using the “Sounds” tab, add the “Trumpet2” sound
effect to the elephant, then build it the code below.

▽ Find the elephant


This code uses “Sensing” blocks to control the
relationship between the cat and the elephant. As
the cat gets nearer, the elephant grows. When the
cat touches it, the elephant switches costume,
makes a sound, and hides somewhere else.

The “forever” loop keeps This checks how far the


when clicked sensing and adjusting the cat is from the elephant
elephant’s size and position
forever

set size to 200 – distance to Sprite1 %

if touching Sprite1 ? then The farther away


the cat is, the smaller
the elephant will be
switch costume to elephant-b
If the sprites touch,
play sound Trumpet2 until done the blocks inside the
“if-then” block run
switch costume to elephant-a

go to x: pick random -240 to 240 y: pick random -180 to 180

This block selects a


random place for the
elephant to hide
68 S TA R T I N G F R O M S C R AT C H

Complex loops SEE ALSO

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

Looping until something happens repeat until


Add the “Dog1” sprite to a project, and then give the
code below to the cat sprite. When you run the code, the
“repeat until” block makes sure the cat keeps moving until
it touches the dog. It will then stop and say “Ouch!”
△ “Repeat until” block
This block stops the cat The blocks inside the “repeat
from standing on its head until” block keep repeating until
the condition is true (the cat
when clicked touches the dog).
Select “Dog1” from
set rotation style left-right the drop-down menu

repeat until touching Dog1 ?

move 10 steps Ouch!


These instructions keep on repeating
if on edge, bounce until the cat touches the dog

say Ouch!
This will happen only when
the cat touches the dog
△ Testing the program
Move the dog out of the cat’s way and run
the program. Then drag and drop the dog
into the cat’s path to see what happens.

Stop! This stops all


the code in
This stops only the
code this block is in
Another useful “Control” a program
block is the “stop all” block, stop all
This stops the sprite’s other
which can stop code from code blocks, but continues to
all run the code this block is in
running. It’s useful if you
want to stop sprites from this script ◁ Stopping code
moving at the end of a game. Use the drop-down menu to
other scripts in sprite
choose what code to stop.
COMPLEX LOOPS 69
Waiting wait 1 seconds
◁ Waiting blocks
The “wait seconds” block
It’s easier to play a game or see what’s waits a set amount of
going on in a program if you can make wait until time. The “wait until”
the code pause for a moment. Different block responds to what’s
happening in the program.
blocks can make the code wait a number
of seconds or until something is true.
Sprite waits 5 when clicked Sprite waits until
seconds and then the mouse button
says something is pressed
forever
when clicked
wait until mouse down?
wait 5 seconds
go to mouse-pointer
say I’m tired of waiting
As soon as the
△ ”wait seconds” block condition is true, the
With the “wait seconds” block you △ ”wait until” block sprite moves to the
can enter the number of seconds This block waits until the Boolean mouse-pointer
you want a sprite to wait. expression in it is true.

Magnetic mouse The code repeats until the


mouse button is released
Different loops can be used when clicked The “not” block detects
together to make programs. when the mouse button
forever is not being pressed
This program starts once
the mouse button is wait until mouse down?
pressed. The sprite follows
the mouse-pointer until the repeat until not mouse down?
mouse button is released. It
then jumps up and down five go to mouse-pointer ▾
times. The whole thing then
repeats itself because it’s all
inside a “forever” loop. repeat 5

change y by 20

wait 0.25 seconds This makes the


sprite jump up
change y by -20

wait 0.5 seconds This makes the


sprite drop down
▷ Nested loops
Pay careful attention to how The “repeat 5” block
the loops are nested inside makes the sprite jump
the “forever” block. up and down five times
70 S TA R T I N G F R O M S C R AT C H

Sending messages SEE ALSO

‹ 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

Broadcasting broadcast message1


This block starts the code 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.

This message starts the code


that makes the starfish swim
away from the shark

when I receive shark_here


when clicked
switch costume to starfish-b
forever
glide 1 secs to x: 133 y: 91
show

broadcast shark_here Choose “New message” The starfish glides out of


from the menu to create the shark’s way, showing
glide 5 secs to x: 150 y: -150 this name its scared costume

hide This message tells the


starfish that the shark is
broadcast shark_gone gone, so it’s safe to return

glide 5 secs to x: -150 y: 150


when I receive shark_gone

△ Shark danger switch costume to starfish-a


Choose two sprites—a shark and a starfish. Give the shark glide 1 secs to x: 0 y: 0
the code above, and the starfish the two code blocks on
the right. When the shark arrives it sends a message, The starfish glides back to the middle of
which makes the starfish swim away. the screen, showing its happy costume
SENDING MESSAGES 71
Conversations
To create a conversation between sprites use
“broadcast message and wait” blocks with “say”
blocks, which make your sprites talk using broadcast message1 and wait
speech bubbles. Start a new project and add
△ Waiting blocks
two monkey sprites to it. Give the code on the This block sends a message, then waits for all the
left to one monkey, and the two code blocks code that reacts to the message to finish before
on the right to the other. the program continues.

The first Hello!


monkey starts
the conversation
Hi!

“Say” blocks let your


sprites talk using
speech bubbles
The “hello”
message triggers
The second
when clicked the second
monkey responds
monkey’s code
to the first one
say Hello! for 2 seconds

broadcast hello and wait when I receive hello

say How are you? for 2 seconds say Hi! for 2 seconds

broadcast howareyou

When the second when I receive howareyou


monkey’s code ends,
the first monkey’s say Great, thanks! for 2 seconds
How are you? code continues

The “howareyou”
message starts
this third section
of code Great, thanks!

△ Chatty monkeys
This program works because it uses the “broadcast message
and wait” block. If the “broadcast message” block was used,
the monkeys would talk over each other.
72 S TA R T I N G F R O M S C R AT C H

Creating blocks SEE ALSO

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

Making your own block


You can make your own blocks in Scratch that run code when
they’re used. Try this example to see how they work. Programmers
call these reusable pieces of code “subprograms” or “functions”.
Create a new block New block appears
1 Click on the “My Blocks” button, and 2 Your new block “jump” appears
then select “Make a Block”. Type the word in the blocks palette, and a “define”
“jump” and click “OK”. block appears in the code area.
Code Costumes Sounds
My Blocks
Motion Make a Block
Make a Block
Looks

Sound
define jump
jump
Events

Control

Click here Sensing

to make
a new
Operators
The new block Define the
block Variables
“jump” block in
the code area
My Blocks

Define the block Use the block in the code


3 The “define” block tells Scratch which 4 The new block can now be used in
blocks to run when using the new block. the code. It’s as if those jumping blocks
Add this code to define the block. were in the code individually.
Starts your
block
definition
define jump when clicked

forever The new block runs


change y by 50
the jumping code that
Jumps up
jump has already been defined
wait 1 seconds
wait 1 seconds
change y by -50
Drops Waits 1 second before
down repeating the loop
C R E AT I N G B L O C K S 73
Blocks with inputs
Windows in a new block can be used to
Make a Block
give it numbers and words to work with.
These holes can be used to change
how far the block moves a sprite. slide steps and shout greeting

Click here to add a


number or a string
text

Make a new block


1 Make a new block called “slide”. Now select
Add an input
number or text
Add an input
boolean
Add a label

“Add an input number or text” and type “steps”. Run without screen refresh
Select “Add a label” and change it to “and shout”.
Click “Add an input number or text” again and call Cancel OK

it “greeting”. Then click “OK”.


The steps The greeting
variable variable

Define the block


2 In the “define” block, define slide steps and shout greeting
the holes are replaced with
variables called “steps” and change x by steps Drag variables from
“greeting”. Drag these the “define” block
variables from the “define” into the code
say greeting for 1 seconds
block into the code wherever
you need them. Add this code
to your sprite. change x by 0 – steps

This block makes the


number of steps negative
Use the block in the code
3 Now add the below code to a sprite.
By putting different numbers of steps and Starts the code Use a sensible name
greetings into the block, you can make when the spacebar for a new block so the
your sprite behave differently. is pressed program will be easier
to read and change.

The sprite slides


when space ▾ key pressed 20 steps and
shouts “hello”
slide 20 and shout hello

wait 1 seconds Now the sprite slides


80 steps and shouts
slide 80 and shout how’s it going? “how’s it going?”
74 S TA R T I N G F R O M S C R AT C H

PROJECT 3

Monkey mayhem SEE ALSO

‹ 40–41 Costumes
This exciting, fast-paced game brings together all of the ‹ 38–39 Making
things move
Scratch skills you’ve learned so far. Follow these steps to
create your very own “Monkey mayhem” and see if you
‹66–67 Sensing and
detecting
can hit the bat with the bananas!
EXPERT TIPS
Getting started Avoiding errors
Start a new Scratch project. The cat sprite isn’t needed
This is the biggest Scratch
for this project. To remove it, right-click on it in the program you’ve tried so far, so you
sprites list and then click “delete” in the menu. This will might find that the game doesn’t
leave you a blank project to work on. always work as you expect it to.
Here are some tips to help things
run smoothly:
Add a new backdrop from the Click here to
1 backdrop library. This button is add a new
backdrop from
Make sure you add the code to the
correct sprite.
found to the right of the sprites list.
the backdrop Follow the instructions carefully.
library
Remember to make a variable before
using it.
Check that all the numbers in the
Choose a Backdrop blocks are correct.

Search for the “Wall 1” backdrop and select


2 it. The brick wall works well for this game,
but if you prefer, you could use a different
backdrop instead.

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

Go to the sprites library to


3 add a new sprite to the game.
Search for “Monkey” and
select it. The user will control
this sprite in the game. Monkey

Click here to choose a new


Choose a Sprite
sprite from the library

Give the monkey the code below. Remember—all of the different


4 blocks can be found in the blocks palette, organized by color. In
this code, “Sensing” blocks are used to move the monkey around
the stage using the keyboard arrow keys. Run the code when
you’ve finished to check it works.

This “Motion” block keeps


the monkey upright
when clicked
The arrow keys on the
set rotation style left-right keyboard will make the
monkey run left and right
go to x: 0 y: -90 Moves the monkey to
his start position at the This “Sensing” block detects when
bottom of the stage the left arrow key is pressed
forever

if key left arrow pressed? then

point in direction -90 –90 makes the monkey


point to the left
move 10 steps
This block makes the monkey look like it’s
next costume walking by switching between its costumes

if key right arrow pressed? then

point in direction 90 90 makes the monkey


point to the right
move 10 steps
Moves the
next costume monkey 10 steps

Don’t forget to save


your work
76 S TA R T I N G F R O M S C R AT C H

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!

This makes the


Add the “Bananas” sprite from the sprites
when clicked bananas stay upright 5 library, then give it this code. When the
game starts, the monkey will be holding
set rotation style left-right the bananas. When the spacebar is
pressed, they will shoot vertically up
point in direction 0 Sets the bananas’ the stage. The bananas then reappear
direction to up at one side of the stage, where they can
show This block makes the bananas be picked up again.
visible on the stage—they’ll
forever be hidden later

repeat until key space pressed?

go to Monkey The bananas will stick


to the monkey until the
spacebar is pressed

repeat 35 This loop moves the


bananas up the stage
move 10 steps

if pick random 1 to 2 = 1 then

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

wait until touching Monkey ?

This makes the code wait until the


monkey picks up the bananas
M O N K E Y M AY H E M 77

The next step is to add a flying bat and make it drop


6 to the ground if it’s hit by the bananas. Add “Bat” from New Variable
Name the
the sprites library, then create a new variable called
new variable
“Speed” (for the bat sprite only). To create a new New variable name:
“Speed”
variable, first click the “Variables” button in the blocks
palette, and then select the “Make a Variable” button. Speed
Uncheck the box by the “Speed” variable in the This variable
“Variables” section so it doesn’t appear on the stage. For all sprites For this sprite only will be used
only with the
Add the below code to the bat. In the main “forever” bat sprite
7 loop, the bat moves to a random position on the left Cancel OK

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.

This keeps the bat


when clicked sprite upright
The bat starts off on
set rotation style left-right the left of the stage,
at a random height
forever Start of the bat’s main loop

go to x: -300 y: pick random 1 to 100

point in direction 90 Sets the bat’s direction to right

Picks a random speed


set Speed to pick random 1 to 20

repeat until touching Bananas ?


This makes the bat keep
move Speed steps moving until it’s hit

Drag the “Speed” variable from the


if on edge, bounce “Variables” section into this block

broadcast hitbybananas Create this “broadcast” block to tell


other sprites that the bat has been hit.
point in direction 180 This will be useful later in the project
Sets the direction of
repeat 40 the bat to down

move 10 steps Makes the bat


fall down and
off the stage

Don’t forget to save


your work
78 S TA R T I N G F R O M S C R AT C H

MONKEY MAYHEM
The finishing touches 8
Create a new variable called “Time”. Make sure it’s
available for all sprites in the game by selecting the
To make the game even more exciting, you “For all sprites” option. Check that the box next to
can add a timer, use a variable to keep score the variable in the blocks palette is checked, so that
of how many bats the player hits, and add a players can see the time displayed on the stage.
game-over screen that appears once the
player is out of time. Time

Click on the small picture of the


9 stage in the stage list, then select
the “Backdrops” tab above the
blocks palette. Right-click the
existing backdrop and duplicate
it. Add the words “GAME OVER”

GAME OVER
to the new backdrop.
Use the text tool
to write on the
duplicate backdrop

Your “game over” screen will


look something like this

Click the “Code” tab and when clicked


10 add this code to the stage
to set up the timer. When switch backdrop to Wall 1
the timer begins, it starts a This sets the time
count-down loop. When set Time to 30 limit to 30 seconds
the loop finishes, the
“GAME OVER” screen is repeat until Time = 0
shown and the game ends.
wait 1 seconds Counts down until the
timer reaches zero
change Time by -1

switch backdrop to Wall 2 Switches to the “GAME


OVER” backdrop
Ends the game
stop all
M O N K E Y M AY H E M 79

Click the bananas sprite in Check the box to


11 the sprites list. Create a new show the score
variable called “Score” and on the stage
make it available for all sprites.
Move the score to the top right Score
of the stage by dragging it.

Add this short bit of code to the bananas Add this code to the bananas sprite too. When the
12 sprite. It sets the score to 0 at the beginning 13 bananas hit the bat, it plays a sound, increases
of the game. the score by 10, and hides the bananas.

Makes the
when clicked bananas when I receive hitbybananas
disappear
Add the “Pop” sound
set Score to 0 hide
from the sound library
to the banana sprite
start sound Pop (see pp.58–59)
This resets the score
change Score by 10

Each time the bat


is hit the player
Next add some music to the scores 10 points
14 game. Click on the stage and 2

select the “Sounds” tab above the


blocks palette. Load the “Eggs” REMEMBER
music from the sound library.
Eggs Achievements
15.25
Congratulations—you’ve built
Add the “Eggs” music
from the “Sounds” tab a complete Scratch game. Here
are some of the things you have
achieved so far:
Add the code below to the stage. It plays the “Eggs”
15 music on a loop, but will stop when the “stop all” Made a sprite throw objects at
block ends the game. another sprite.
Made a sprite fall off the stage
once hit.
The background
when clicked music is repeated Added a time limit to your game.
in an endless loop Added background music that plays
forever as long as the game continues.
play sound Eggs until done Added a game-over screen that
appears at the end of the game.
Don’t forget to save
your work
80 S TA R T I N G F R O M S C R AT C H

MONKEY MAYHEM
Time to play To make the game last
You can edit the
program to give the
Now the game is ready to play. Click the longer, try increasing player more points for
the time limit each successful hit
green flag to start and see how many
times you can hit the bat with the
bananas before the time runs out.

Left cursor key Right cursor key


Time 30

Score 0

Spacebar
Space
△ Controls
Steer the monkey left and right with To make the
the keyboard cursor keys. Tap the game harder,
spacebar to fire bananas at the bat. make the bat
move faster

EXPERT TIPS
Adding more sprites
To add more bats to aim at, right-click the bat in
the sprites list and select “duplicate”. A new bat
will appear with the same code as the first one.
Try adding some other flying sprites:

1. Add a sprite from the sprites library. The flying


hippo (“Hippo1”) is great for this game.
2. Click on the bat in the
sprites list.
3. Click the bat’s code
and hold the mouse
button down.
4. Drag the bat’s code
on to the new sprite in
the sprites list.
5. The code will copy
across to the new sprite.
M O N K E Y M AY H E M 81

Try out different


backdrops and see
how the game looks

Click this icon to make


your game fill the screen

To make the game harder,


try changing the code to
make the bananas move
more slowly

Try changing the


monkey into a
different sprite

◁ 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

Time to experiment SEE ALSO


What is 86–87
Python?

Now you’ve learned the basics of Scratch, you can
experiment with some of its more advanced features. The
Simple 102–103
commands

more you practice, the better your coding will become.

Things to try ◁ Join a coding club


Is there a coding club in
Not sure what to do next with your school or local area?
Scratch? Here are a few ideas. They’re great places to
If you don’t feel ready to write meet other Scratch users
and share ideas.
a whole program on your own
yet, you can start with one
that has already been written
and change parts of it.

Scratch allows you to


look at the coding of all
projects on its website

△ Look at code ▷ Remix existing projects


Looking at other programs is a great Can you improve the projects on
way to learn. Go through projects the Scratch website? Scratch lets
shared on the Scratch website. What you add new features and then
can you learn from them? share your version.

Backpack Drag and drop


to copy code or
The backpack enables you to store useful sprites into the when clicked
backpack
code, sprites, sounds, and costumes and
forever
move them from project to project. It’s
found at the bottom of the Scratch screen. Backpack
say hello!

move 10 steps

▷ Drag and drop


You can drag sprites and code into
A sprite in the Sprite
your backpack, and then add them Sprite 1
backpack
to other projects.
TIME TO EXPERIMENT 83
Choose a tutorial
Tutorials 1 Click the tutorials icon. Look through the
Scratch has built-in tutorials for learning list of projects that appear to see what you’d
more of the basics. A tutorial is a step-by-step like to work on. There are lots to choose from.
lesson that teaches you how to do something.
Tutorials
Select this icon to open
Start learning
2 Click on a tutorial to get
the tutorial library

started. Scratch will tell you what


Total number of
to do at each step. screens in a tutorial End the lesson

Click here to Tutorials Close


go back to the
tutorial library

Every tutorial
is a video Click here
that explains to go to the
a concept next screen
step by step

Learn another language


You’re now on your way to mastering your first
programming language. Learning other languages will
enable you to write different types of programs. Why not
try Python next? What you’ve already learned about
Scratch will help you pick up Python quickly.

▷ 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

What is Python? SEE ALSO


Installing 88–91
Python

Python is a text-based programming language.
It takes a bit longer to learn than Scratch, but can
Simple 102–103
commands

be used to do much more. Harder 104–105 ›
commands

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.

Easy to learn and use Contains ready-to-use code


1 Python programs are written in a 2 Python contains libraries of
simple language. The code is quite easy to preprogrammed code that you can
read and write, compared to many other use in your programs. It makes it easier
programming languages. to write complex programs quickly.

Python contains
lots of programs
you can use and
build on

Useful for big organizations


3 Python is powerful. It can be used EXPERT TIPS
to write real-world programs. It is used by
Google, NASA, and Pixar, among others. Getting started
Before learning how to program in Python, it’s
useful to get familiar with how it works. The next
few pages will teach you how to:

Install Python: Python is free, but you’ll have to


install it yourself (see pp.88–91).
Use the interface: Make a simple program and save
it on the computer.
Experiment: Try some simple programs to see how
they work.
W H AT I S P Y T H O N ? 87
Scratch and Python
Lots of elements that are used in Scratch are also
used in Python—they just look different. Here are
a few similarities between the two languages.

when clicked print("Hello World!")

say Hello World! Type the message


you want here
This block displays
the message in a
speech bubble

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.

Turns the pen on

pen down Repeats the blocks


inside it 24 times to
repeat 24 draw a circle
from turtle import *
move 10 steps Moves the sprite pendown()
forward This starts
for n in range(24): a loop
turn 15 degrees
forward(10)
Turns the sprite
right(15)
pen up penup()
Turns the
pen off Turns the
turtle clockwise
15 degrees

△ Turtle graphics in Scratch △ Turtle graphics in Python


The code above uses the “pen down” block There’s also a turtle in Python. The code above
to move the cat sprite and draw a circle. can be used to draw a circle.
88 P L AY I N G W I T H P Y T H O N

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.

What is IDLE? EXPERT TIPS


When you install Python 3, you’ll also get a free program Saving code
called IDLE (Integrated DeveLopment Environment).
Designed for beginners, IDLE includes a basic text editor When saving work in Python, you
will need to use the “File > Save
that allows you to write and edit Python code. As...” menu command so you can
name your files. First create a
folder to keep all your files in. Give
WINDOWS the folder a clear name, like
“PythonCode”, and agree with the
△ Windows person who owns the computer
Before you download Python, check where to keep it.
what kind of operating system your
computer has. If you have Windows,
find out whether it’s the 32-bit or
64-bit version. Click the “Start”
button, right-click “This PC,” and
then left-click “Properties.”

MAC UBUNTU
△ Mac △ Ubuntu
If you use an Apple Mac, find out which Ubuntu is a free operating system that
operating system it has before you install works just like Windows and Macs. To
Python. Click the apple icon in the top find out how to install Python on
left and choose “About This Mac.” Ubuntu, turn to page 91.
I N S TA L L I N G P Y T H O N 89
Python 3 on Windows
Before you install Python 3 on a Windows PC, make sure you get
permission from the computer’s owner. You may also need to
ask the owner to provide an admin password during installation.

Go to the Python website Download Python


1 Type the address below into your Internet 2 Click on the latest version of Python for Windows,
browser to open the Python website. Click on beginning with the number 3. You can choose either the
“Downloads” to open the download page. web-based installer or the executable installer.
Choose this if you have a
http://www.python.org 32-bit version of Windows

• Python 3.7.0 - 2019-02-15


This is the URL (web Don’t worry • Download Windows x86 web-based installer
address) for Python about the exact • Download Windows x86-64 web-based installer
number, as
long as it has a
3 at the front Choose this if you have a
64-bit version of Windows

Install Run IDLE


3 The installer file will download automatically. 4 Now check that the program installed
When it finishes, double-click it to install Python. correctly. Open the Windows “Start” menu,
Choose “install for all users” and click “next” at each choose “All Apps”, then select “IDLE”.
prompt, without changing the default settings.

The Windows installer Double-click this


icon appears while icon to run the
Python is installing IDLE application

5 A Python window opens


A window like the one below should open
up. You can now start coding—just type into the
window after the angle brackets (>>>).

Python 3.7.0 Shell


IDLE File Edit Shell Debug Window Help
Python 3.7.0 (v3.7.0:5fd3365926, Feb 15 2019, 13:38:16) [MSC v.1900 32
bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> Begin typing code here
90 P L AY I N G W I T H P Y T H O N

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.

Go to the Python link Download Python


1 Type the address below into your web 2 Check which operating system your Mac has
browser to open the Python website. Click on (see page 88) and click on the matching version of
“Downloads” in the navigation panel to go to Python 3. You’ll be prompted to save a .dmg file. Save
the download page. it on your Mac desktop.

http://www.python.org
• Python 3.7.0 - 2019-02-15
Don’t worry about the • Download macOS 64-bit/32-bit installer
exact number, as long
as it has a 3 at the front
This version runs
on most Macs

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 installer file

Python.pkg

A Python window opens


5 A window like the one below should
open. You can now start coding—just type
into the window after the angle brackets.

Python 3.7.0 Shell


IDLE File Edit Shell Debug Window Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Feb 15 2019, 13:38:16)
[Clang 6.0 (clang-600.057)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>>
I N S TA L L I N G P Y T H O N 91
Python 3 on Ubuntu
Most recent versions of Ubuntu come with Python and IDLE
pre-installed. If you can’t fine IDLE on your machine, you can
download it without having to use a browser—just follow the
steps below. If you have a different version of Linux, ask the
computer’s owner to install Python 3 for you.

Go to Ubuntu Software Center Enter “Terminal” into the search bar


1 Find the Ubuntu Software 2 You will see a search icon in the top right.
Center icon in the Dock or the Dash Type “Terminal” in the box and press enter to
and double-click it. open Ubuntu’s command line.
This is what the
>_ Terminal app
thumbnail looks like

3 Install IDLE
Type the commands shown below into 4 Run IDLE
After the installation is complete, enter
the Terminal window one at a time. Make sure “IDLE” into the search bar and double-click on
you start typing after the “$” sign. the blue-and-yellow “IDLE icon.
This updates the system
so you can install the latest
version of any software

$ sudo apt-get update

$ sudo apt-get install idle3


IDLE icon

This installs the latest


version of IDLE

A Python window opens


5 A window like the one below should
open. You can now start coding—just type
into the window after the angle brackets.

Python 3.7.0 Shell


IDLE File Edit Shell Debug Window Help
Python 3.7.0 (default, Feb 15 2019, 18:25:56)
[Open Watcom] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>>
92 P L AY I N G W I T H P Y T H O N

Introducing IDLE SEE ALSO

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

Working in IDLE EXPERT TIPS


Follow these steps to make a Python Different windows
program using IDLE. It will teach you
how to enter, save, and run programs. Python uses two different windows—the “shell”
window and the “code” window (see pages
106–107). We’ve given them different colors
to tell them apart.
Start IDLE
1 Start up IDLE using the instructions for your
Shell window
computer’s operating system (see pp.88–91). The
shell window opens. This window shows the
program output (any information the program Code window
produces) and any errors.

Python 3.7.0 Shell


IDLE File Edit Shell Debug Window Help
Python 3.7.0 (v3.7.0:1bf9cc5093, Jan 15 2019, 13:38:16)
[Clang 6.0 (clang-600.057)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> What appears here will
Messages from depend on which operating
Python appear here system you’re using

Open a new window


2 Click the “File”
Python 3.7.0 Shell
IDLE File Edit Shell Debug Window Help
menu at the top of the
shell window and select New File
“New File”. This opens
the code window. Open...

Open Module... Click here to open


the code window
Recent Files ▶
This is the
shell window Module 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


Use double
words “Hello World!” quote marks

Save the code window


4 Click the “File” menu and select
Untitled

“Save As...”. Enter the file name IDLE File Edit Format Run Window Help
“HelloWorld” and click “Save”. prin New File

Open...

Open Module...

Recent Files ▶
If you get an error message,
check your code carefully Module Browser
to make sure you haven’t
made any mistakes. Path Browser

Close

Save
Click here to
save the file
Save As...

Run the program


5 In the code window, click the “Run”
Hello World

menu and select “Run Module”. This will IDLE File Edit Format Run Window Help
run the program in the shell window. print("Hello World!") Python Shell

Check Module
Click here to
run the program Run Module

Output in the shell window


6 Look at the shell window. The “Hello
REMEMBER
World!” message should appear when the How IDLE works
program runs. You’ve now created your
first bit of code in Python! Always follow these three steps in IDLE: write the code, save it,
and then run it. Remember, code that hasn’t been saved won’t
>>> run. A warning will come up if you try.
Hello World!
>>>
Enter code Save Run
The message will appear
without quote marks
94 P L AY I N G W I T H P Y T H O N

Errors SEE ALSO


Bugs and 148–149
debugging

Sometimes programs don’t work the first time, but
they can always be fixed. When code for a program
What next? 176–177 ›
isn’t entered correctly, Python will display an error
message telling you what has gone wrong.

Errors in the code window


When trying to run a program in the code window,
you might see a pop-up window appear with an error
message (such as “SyntaxError”) in it. These errors stop
the program from running and need to be fixed.

Syntax error Error highlighted


1 If a pop-up window appears with 2 Click “OK” in the pop-up window and
a “SyntaxError” message, it often means you’ll go back to your program. There will
there’s a spelling mistake or typing be a red highlight on or near the error.
error in the code. Check that line for mistakes carefully.

SyntaxError print("Hello World!)

There is a missing The error is


invalid syntax quote mark here highlighted

EXPERT TIPS

OK There is a Classic errors


typing error
in the code Some mistakes are particularly easy to make.
Keep an eye out for these common problems:
SyntaxError
Upper vs lower case: The case has to match exactly.
If you write “Print” instead of “print”, Python won’t
understand the instruction.
unexpected indent Single and double quotes: Don’t mix up single and
double quotes. All opening quotes need a matching
closing quote.
OK Minus and underscore: Don’t confuse the minus sign
(-) with the underscore sign (_).
Different brackets: Different-shaped brackets, such
There is incorrect as (), {} and [], are used for different things. Use the
spacing in the code,
correct ones, and check there’s a complete pair.
which is preventing the
program from running
ERRORS 95
Errors in the shell window
Sometimes, an error message will appear in red Red text means there’s
something wrong!
text in the shell window. This will also stop the
program from working.
Name error
1 If the error message “NameError” appears, it means Python
can’t understand one of the words that has been used. If the error is The line in the code
in code entered in the code window, right-click on the error message (in the code window)
in the shell window and select “Go to file/line”. where the error was found

>>>
Traceback (most recent call last):
File "C:\PythonCode\errors.py", line 1, in <module>
pront("Hello World!")
Cut
NameError: name "pront" is not defined
Copy
The word Python
doesn’t understand Paste Click here to highlight the
line where the error appears
Go to file/line in the code window

Fix the error


2 The line with the error is highlighted
pront("Hello World!")

in the code window. The word “pront” has


been typed instead of “print”. You can then Change this
edit the code to fix the error. to read “print”

Spotting errors ERROR BUSTING


Use the tips on these two pages to find Check your code for the following points
the line in the code where the errors Have you copied exactly what you were asked to enter?
appear, then double-check that line. Go
through the checklist on the right to help Have you spelled everything correctly?
you find out what has gone wrong.
Are there two quote marks (‘) around the expression you
want to print?
Do you have extra spaces at the beginning of the line?
Spacing is very important in Python.
▷ When things Have you checked the lines above and below the
go wrong highlighted line? Sometimes that’s where the problem is.
There are some Have you asked someone else to check the code against the
methods you can book? They might spot something you have missed.
use to find errors
more easily. Here’s Are you using Python 3 not Python 2? Programs for Python
3 don’t always work in Python 2.
a handy checklist.
96 P L AY I N G W I T H P Y T H O N

PROJECT 4
Ghost game SEE ALSO
Ghost game 98–99
decoded

This simple game highlights some of the things
to watch out for when writing programs in
Program 100–101
flow

Python. Once the code has been typed in, run
the program to play the game. Can you escape
the haunted house?

Use double quotes

Start IDLE, and use the


# Ghost Game
1 “File” menu to open a new
window. Save the game as from random import randint
“ghost game.” Arrange the print("Ghost Game") Use capital letters only
windows so you can see where they are shown
feeling_brave = True
them both, then type this
into the code window. score = 0
Make sure to add
while feeling_brave: a colon here
These must be ghost_door = randint(1, 3)
underscores, not
minus signs print("Three doors ahead ...")
print("A ghost behind one.")

This section needs to be print("Which door do you open?")


indented by four spaces.
door = input("1, 2, or 3?")
If this doesn’t happen
automatically, check that door_num = int(door)
there is a colon after
“feeling_brave” if door_num == ghost_door:
Use two equals
print("GHOST!") signs here

This indent will start feeling_brave = False


at eight spaces and
else:
needs to be reduced
to just four spaces print("No ghost!")
print("You enter the next room.")
Delete all
indents here score = score + 1
print("Run away!")
print("Game over! You scored", score)

There should be no quotes


around “score” here
GHOST GAME 97

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

Run Ghost Game


Python Shell Three doors ahead ...
A ghost behind one.
Check Module
Which door do you open?
Run Module
1, 2, or 3?

Choose “Run Module”


from the “Run” menu
in the code window Type in your guess

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.

Ghost Game Ghost Game


Three doors ahead ... Three doors ahead ...
A ghost behind one. A ghost behind one.
Which door do you open? Which door do you open?
1, 2, or 3?3 1, 2, or 3?2
The number you type
No ghost! in appears here GHOST! This is what appears if the
Run away! ghost is behind your door
This is what you’ll
Game over! You scored 0
see if there is no
ghost behind the
door you choose

The score shows


how many rooms
you survived

1 2 3
98 P L AY I N G W I T H P Y T H O N

Ghost game decoded SEE ALSO

‹ 96–97 Ghost game


The ghost game displays some of the key features Program 100–101
flow

of Python. You can break down the code to see how
the program is structured and what the different
parts of it do.
# Ghost Game

Code structure from random import randint


1
print("Ghost Game")
feeling_brave = True
Game set-up
Python uses spaces at the start of lines score = 0
while feeling_brave:

to figure out which instructions belong ghost_door = randint(1, 3)


print("Three doors ahead ...")
The main loop
together. These spaces are called “indents.” 2
print("A ghost behind one.")
print("Which door do you open?")
door = input("1, 2 or 3?")
For example, the code after “while door_num = int(door)
if door_num == ghost_door:
◁ Code key
feeling_brave” is indented by four spaces print("GHOST!")
feeling_brave = False
This diagram shows the
to show it’s all part of the main loop. else:
3
print("No ghost!")
structure of the ghost
print("You enter the next room.") game. The numbered
score = score + 1
Branching part parts are explained in
4
print("Run away!")
print("Game over! You scored", score)
more detail below.
This is a “comment.” It’s not
shown when the game is run
Game ending

Game setup
1 These instructions run
# Ghost Game This sets up the “randint”
command, which generates
only once—at the beginning from random import randint
random numbers
of the game. They set up print("Ghost Game")
the title, variables, and the The “print” command
feeling_brave = True
“randint” command. displays text when
score = 0 the game is run

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 This selects a
2 This loop tells the story
while feeling_brave: random number
ghost_door = randint(1, 3) between 1 and 3
and receives the player’s guess.
It keeps on going as long as there print("Three doors ahead ...")
isn’t a ghost behind the door The “print”
print("A ghost behind one.") command displays
that’s picked. When a ghost
print("Which door do you open?") the text onscreen
appears, the “feeling_brave”
variable changes to “False” and door = input("1, 2 or 3?")
the loop stops repeating. This line asks for
door_num = int(door) the player’s answer
if door_num == ghost_door:
Branching part This branch runs
3 The program takes a
print("GHOST!") if there’s a ghost
behind the door
different path depending on feeling_brave = False
the player picks
whether or not there was a else:
ghost behind the door that was
print("No ghost!") If there’s no ghost,
picked. If there was a ghost, the
the player sees
“feeling_brave” variable is set to print("You enter the next room.")
this message
“False” but if not, the player’s score = score + 1
score increases by one.

The score increases by one


each time the player enters a
room without meeting a ghost
This shows a message
telling the player to run
away from the ghost

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

Program flow SEE ALSO

‹30–31 Colored blocks


and code
Before learning more about Python, it’s important to
understand how programs work. The programming basics
Simple 102–103
commands

learned in Scratch can also be applied to Python. Harder 104–105 ›
commands

From input to output


A program takes input (information in), processes it
(or changes it), and then gives back the results (output).
It’s a bit like a chef taking ingredients, turning them
into cakes, and then giving you the cakes to eat.

Input Processing Output


Input command Variables Print command
Keyboard Math Screen
Mouse Loops Graphics
△ Program flow in Python
Branches In Python, the keyboard and
mouse are used to input
information, which is processed
Functions using elements such as loops,
branches, and variables. The
output is then displayed on
the screen.
PROGRAM FLOW 101
Looking at the Ghost game through EXPERT TIPS
Scratch goggles One code at a time
Program flow works the same in most programming There’s an important difference
languages. Here are some examples of input, processing, between Scratch and Python.
and output in Python’s Ghost game—and what they In Scratch, lots of code can
might look like in Scratch. run at the same time. In Python,
however, the program is made
up of only one code.
Python and Scratch
are more similar
than they appear.

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

door = input("1, 2 or 3?") ask 1, 2 or 3? and wait

The question “ask and wait” Scratch block


appears on screen

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.

score = 0 set score ▾ to 0

Sets the variable “set score to 0” Scratch block


“score” to 0

ghost_door = randint(1, 3) pick random 1 to 3

“pick random” Scratch block


Selects a random
This Scratch block
whole number
selects a random
between 1 and 3
number
Output
3 The “print()” function is used to Shows a speech bubble
output things in Python, while the “say” Displays “Ghost game” containing the words
block does the same thing in Scratch. on the screen “Ghost game”

print("Ghost game") say Ghost game

“say” Scratch block


102 P L AY I N G W I T H P Y T H O N

Simple commands SEE ALSO

‹86–87 What is
Python?
At first glance, Python can look quite scary,
especially when compared to Scratch. However,
Harder 104–105
commands

the two languages aren’t actually as different as
they seem. Here is a guide to the similarities
between basic commands in Python and Scratch.
Command Python 3 Scratch 3.0

Run program “Run” menu or press “F5” (in code window)

Stop program Press “CTRL-C” (in shell window)

Write text print("Hello!") say Hello!


to screen

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

Read text from ask age? and wait


age = input("age?")
keyboard into
variable print("I am " + age) say join I am answer

cats = cats + 1
Add a number
or change cats by 1
to a variable
cats += 1

Add a + 2 a + 2

Subtract a - 2 a – 2

Multiply a * 2 a * 2

Divide a / 2 a / 2
SIMPLE COMMANDS 103
Command Python 3 Scratch 3.0

forever
while True:
Forever loop jump
jump()

repeat 10
for i in range (10):
Loop 10 times jump
jump()

Is equal to? a == 2 a = 2

Is less than? a < 2 a < 2

Is more than? a > 2 a > 2

NOT not not

OR or or

AND and and

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

Harder commands SEE ALSO

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

Command Python 3 Scratch 3.0

repeat until roll = 6


Loops with while roll != 6:
conditions jump() jump

from time import sleep


Wait wait 2 seconds
sleep(2)

Random from random import randint


set roll ▾ to pick random 1 to 6
numbers roll = randint(1, 6)

Define a def jump(): define jump


function or
print("Jump!")
subprogram
think Jump!

Call a function
jump() jump
or subprogram

Define a define greet who


function or def greet(who):
subprogram print("Hello " + who)
with input say join Hello who

Call a function
greet("chicken") greet chicken
or subprogram
HARDER COMMANDS 105
Command Python 3 Scratch 3.0

from turtle import * erase all

clear() pen down


Turtle pendown()
move 100 steps
graphics forward(100)
right(90) turn 90 degrees

penup() pen up

Join strings print(greeting + name) say join greeting name

Get one letter


name[0] letter 1 of name
of a string

Length of
len(name) length of name
a string

Create an menu = list() Make a List


empty 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?

Value of 5th say item 5 of menu


menu[4]
item on list

Delete 2nd
del menu[1] delete 2 of menu
item on list

if menu contains olives then


if "olives" in menu:
Is item on list? say Oh no!
print("Oh no!")
106 P L AY I N G W I T H P Y T H O N

Which window? SEE ALSO

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

The code window ▽ Running programs


So far in this book, the code window has been used to This process is used for
write programs. You enter the program, save it, run it, running Python programs.
Programs always have to be
and the output appears in the shell window. saved before running them.

Enter code Save Run module Output

Enter a program in the code window Output in the shell window


1 Enter this code in the code window, save it, 2 When the program runs, its output
and then click on “Run module” in the “Run” menu (the results of the program) is shown in
to run the program. the shell window.

Give “a” the value 10


a = 10 >>>
b = 4 Give “b” the value 4 14 The answers to the sums
print(a + b) The “print” command 6 appear in the shell window
print(a - b) shows the answers to
these sums

The shell window


Python can also understand commands that are
typed in the shell window. They run as soon as they
are typed in, and the result is shown straight away.

The first two commands have


>>> a = 10 no output because they are just
assigning values to “a” and “b”
>>> b = 4
>>> a + b ◁ Code and output together
Output appears The shell window shows the code △ Test your ideas
14
immediately and the output together. It’s easier The shell window gives you an
>>> a - b to tell which answer belongs to immediate response, which makes
6 which sum when the commands it ideal for testing instructions and
are typed in the shell window. exploring what they can do.
WHICH WINDOW? 107
Python playground EXPERT TIPS
The shell window can be used to try out all sorts of Colors in the code
Python commands, including drawing. The turtle is
used to draw on screen in the same way that the pen IDLE color codes the text.
The colors give you some clues
is used in Scratch.
Loads all the commands about what Python thinks each
that control the turtle piece of text is.

>>> from turtle import *


◁ Enter the code ◁ Built-in functions
Type these Commands in Python, such as
>>> forward(100) instructions in the “print”, are shown in purple.
>>> right(120) shell window. They
run after each one ◁ Strings in quotes
>>> forward(100)
is typed. As the Green indicates strings. If the
turtle moves, it brackets are green too, there’s
Moves the turtle forward draws a line. a missing quote mark.

◁ Most symbols and names


Most code is shown in black.
◁ Turtle graphic
Can you figure out how to ◁ Output
draw other shapes, such as Python’s output in the shell
a square or a pentagon? window is shown in blue.
To start over, type “clear()”
into the shell window. ◁ Keywords
Keywords, such as “if” and “else”,
are orange. Python won’t let you
Which window should you use? use keywords as variable names.
Should you use the code window or the
◁ Errors
shell window? It depends on the type of
Python uses red to alert you
program you’re writing, and whether it has to any error messages in the
to be repeated. shell window.

▷ Code window
The code window is ideal
Code vs Shell ◁ Shell window
The shell window is perfect
for longer pieces of code for quick experiments, such
because they can be saved as checking how a command
and edited. It’s easier than works. It’s also a handy
retyping all the instructions calculator. It doesn’t save the
if you want to do the same instructions though, so if you’re
thing again or try something trying something you might
similar. It needs to be saved want to repeat, consider using
and run each time, though. the code window instead.
108 P L AY I N G W I T H P Y T H O N

Variables in Python SEE ALSO


Types of data 110–111 ›
Variables are used to remember pieces of information Math in 112–113
Python

in a program. They are like boxes where data can be
stored and labeled.
Strings in 114–115
Python

Input and 116–117
output

Creating a variable
When a number or string is put into a variable
Functions 130–131 ›
it’s called assigning a value to the variable.
You use an “=” sign to do this. Try this code in
the shell window. REMEMBER
Variable Value assigned Variables in Scratch
name to the variable
The command to assign a variable in Python does
>>> bones = 3
the same job as this Scratch block. However, in
Python you don’t have to click a button to create
△ Assign a number a variable. Python creates the variable as soon as
To assign a number, type in the variable name, you assign a value to it.
an equals sign, and then the number.
set bones to 3
Variable String assigned
name to the variable
Scratch block for giving
a value to a variable
>>> dogs_name = "Bruno"

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

>>> print(bones) >>> print(dogs_name)


No quote
3 Variable name Bruno marks here

△ Number output △ String output


The variable “bones” contains the The variable “dogs_name” contains a string, so the
number 3, so that’s what the shell string is printed. No quote marks are shown when
window prints. you print a string.
VA R I A B L E S I N PYT H O N 109
Changing the contents >>> gifts = 2

of a variable >>> print(gifts)


Changes the value
To change the value of a variable, 2
of the variable
simply assign a new value to it. >>> gifts = 3
Here, the variable “gifts” has the >>> print(gifts)
value 2. It changes to 3 when it’s 3
assigned a new value.

Using variables EXPERT TIPS


The value of one variable can be assigned to another Naming variables
one using the “=” sign. For example, if the variable
“rabbits” contains the number of rabbits, we can use There are some rules you have to
it to assign the same value to the variable “hats”, so that follow when naming your variables:
each rabbit has a hat. All letters and numbers can be used.
You can’t start with a number.
1 Assign the variables
This code assigns the number 5 to
Symbols such as -, /, #, or @ can’t
be used.
the variable “rabbits”. It then assigns the
same value to the variable “hats”. Spaces can’t be used.
An underscore ( _ ) can be used
Variable Value assigned instead of a space.
name to the variable
Uppercase and lowercase letters are
different. Python treats “Dogs” and
>>> rabbits = 5 “dogs” as two different variables.
>>> hats = rabbits Don’t use words Python uses as a
“hats” now has the command, such as “print”.
same value as “rabbits”

2 Print the values


To print two variables, put them both in brackets
3 Change the value of “rabbits”
If you change the value of “rabbits”, it doesn’t
after the “print” command, and put a comma between affect the value of “hats”. The “hats” variable changes
them. Both “hats” and “rabbits” contain the value 5. only when you assign it a new value.
Give “rabbits”
>>> rabbits = 10 a new value
>>> print(rabbits, hats)
>>> print(rabbits, hats)
5 5 Value for
10 5
Leave a space “hats” remains
after the comma the same
110 P L AY I N G W I T H P Y T H O N

Types of data SEE ALSO


Math in 112–113
Python

There are several different types of data in Python.
Most of the time, Python will figure out what type
Strings in 114–115
Python

is being used, but sometimes you’ll need to Making 118–119 ›
change data from one type to another. decisions
Lists 128–129 ›
Numbers
Python has two data types for numbers. “Integers” are whole numbers,
(numbers without a decimal point). “Floats” are numbers with a
decimal point. An integer can be used to count things such as sheep,
while a float can be used to measure things such as weight.

>>> sheep = 1 >>> sheep = 1.5


An integer 1.5 is
>>> print(sheep) is a whole >>> print(sheep) a float
1 number 1.5

△ Integers △ Floats
An integer is a number without A float is a number with a decimal
a decimal point, such as the 1 point, such as 1.5. They aren’t normally
in the variable “sheep”. used to count whole objects.

Strings
Just like in Scratch, a piece of text in Python is called
a “string.” Strings can include letters, numbers, spaces, Always remember that
and symbols such as full stops and commas. They are strings need quote
marks at the start
usually put inside single quote marks. and the end.

▷ Using a string >>> a = "Coding is fun!"


To assign a string to
a variable, put the >>> print(a)
text inside single Coding is fun!
quote marks.
The value of the variable The string
“a” printed out in quotes
T Y P E S O F D ATA 111
Booleans EXPERT TIPS
In Python, a Boolean always has a value Spotting data types
that is either “True” or “False.” In both cases,
the word begins with a capital letter. In Python, there are many data types. To find out
what data type something is, you can use the
No quote “type” command.
marks
“type” command
▷ True >>> a = True
When the value
>>> print(a) >>> type(24)
“True” is put into
a variable, it will be True <class "int"> 24 is an
a Boolean variable. >>> type(24.3) integer (“int”)
Boolean value
<class "float">
printed
>>> type("24")
▷ False >>> a = False <class "str"> 24.3 is a float
When the value (“float”)
“False” is put into >>> print(a)
a variable, it will False “24” is a string
be a Boolean (“str”) because it is
variable too. Boolean value in quote marks
printed

Converting data types


Variables can contain any type of data. Problems
occur if you try to mix types together. Data types
sometimes have to be converted; otherwise, an
error message will appear.
Variable name String in quote marks
shown on screen
▷ Mixed type
>>> apple = input("Enter number of apples ")
The “input” command
Enter number of apples 2 Type in “2”
always gives a string, Tries to add
even if a number is >>> print(apple + 1) the number 1
entered. In this example, to the variable
TypeError
since “apple” actually “apple”
contains a string, an error
The program gives an error message
message is displayed. as Python doesn’t know how to add
a number to a string
▷ Converting data types
>>> print(int(apple) + 1)
To convert the string into
a number, the “int()” 3
command is used to turn
it into an integer. The program now works The variable turns from a string into an
and shows the result integer, so a number can be added to it
112 P L AY I N G W I T H P Y T H O N

Math in Python SEE ALSO

‹ 52–53 Math
Python can be used to solve all sorts of ‹ 108–109 Variables
in Python
mathematical problems, including addition,
subtraction, multiplication, and division.
Variables can also be used in sums.

Simple calculations
In Python, simple calculations can be made by typing them
into the shell window. The “print()” function is not needed
You can’t divide by zero,
for this—Python gives the answer straight away. Try these so you’ll always get an error
examples in the shell window: if you try to do so.

Use the shell window


>>> 12 + 4 >>> 12 - 4
to get instant results
16 8
The answer
△ Addition appears when △ Subtraction
Use the “+“ symbol to add you press “Enter” Use the “-” symbol to subtract the
numbers together. second number from the first one.

Computers use the “*” symbol,


not “x”, for multiplication

Division in Python gives an


>>> 12 * 4 >>> 12 / 4 answer as a float (a number
48 3.0 with a decimal point)

△ Multiplication △ Division
Use the “*” symbol to multiply two Use the “/” symbol to divide the
numbers together. first number by the second one.

Using brackets First it figures out


that 6 + 5 = 11, then
First it figures out
that 5 * 3 = 15, then
Brackets can be used to instruct 11 is multiplied by 3 15 is added to 6

Python which part of a sum to


do first. Python will always >>> (6 + 5) * 3 >>> 6 + (5 * 3)
figure out the value of the sum 33 21 Different
answer
in the bracket, before solving
△ Addition first △ Multiplication first
the rest of the problem. In this sum, brackets are Brackets here are used to do the
used to instruct Python multiplication first, in order to
to do the addition first. end up with the correct answer.
M AT H I N P Y T H O N 113
Putting answers in variables 1 Do a simple addition
This program adds together the
If variables are assigned number values, you variables “ants” and “spiders,” and puts
can use them within sums. When a sum is the answer into the variable “bugs”.
assigned to a variable, the answer goes into
>>> ants = 22
the variable, but not the sum.
>>> spiders = 35
>>> bugs = ants + spiders
>>> print(bugs) Adds the values of
57 the two variables
together
Prints the value in “bugs”

Change the value of a variable Skipping the assignment


2 Change the value of the “ants” or “spiders” 3 If the sum is not assigned to the variable
variable. Add the variables together again and put “bugs,” even if the value of “ants” and “spiders”
the answer in the variable “bugs”. changes, the value of “bugs” won’t.
Change
>>> ants = 22 the value
>>> ants = 11 Prints the
in “spiders”
value in “bugs”
>>> spiders = 18 >>> spiders = 17
Add the
>>> bugs = ants + spiders variables >>> print(bugs)
together
>>> print(bugs) 40
again
40
The answer The answer hasn’t changed
changes (it’s still 18 + 22)

Random numbers REMEMBER


To pick a random number, you first need to load the Random block
“randint” function into Python. To do this, use the “import”
command. The “randint()” function is already programmed The “randint()” function works like
the “pick random” block in Scratch.
with code to pick a random integer (whole number). In Scratch, the lowest and highest
possible numbers are typed into
the windows in the block. In
Adds the Python, the numbers are put in
Picks a random
“randint()” function
number between brackets, separated by a comma.
1 and 6
>>> from random import randint
pick random 1 to 6
>>> randint(1, 6)
3 3 has been picked at random △ Whole numbers
Both the Python “randint()” function
△ Roll the die and the Scratch block pick a random
The “randint()” function picks a random number between whole number—the result is never
the two numbers in the brackets. In this program, in decimals.
“randint(1, 6)” picks a value between 1 and 6.
114 P L AY I N G W I T H P Y T H O N

Strings in Python SEE ALSO

‹54–55 Strings
and lists
Python is excellent for using words and sentences
within programs. Different strings (sequences of
‹ 110–111 Types
of data
characters) can be joined together, or individual
parts of them can be selected and pulled out.

Creating a string
A string might include letters, numbers, symbols,
or spaces. These are all called characters. Strings
can be placed in variables.
The quote marks indicate the
variable contains a string
▷ Strings in variables >>> a = "Run! "
Variables can store strings.
Type these two strings into
the variables “a” and “b”. >>> b = "Aliens are coming."

Adding strings
Adding two numbers together creates a new number.
EXPERT TIPS
In the same way, when two strings are added together,
one string simply joins on to the other one. Length of a string
The “len()” function is used to find
out the length of a string. Python
>>> c = a + b The variables “a” counts all of the characters,
>>> print(c)
and “b” combine to including spaces, to give the total
become variable “c” number of characters in a string.
Run! Aliens are coming.
Calculates the
△ Adding strings together length of the string
The “+” symbol joins one string to another. in variable “a” (“Run! “)
and the answer becomes the variable “c”.
A new string is added
to variable “c” >>> len(a)
4
>>> c = b + " Watch out! " + a
The new string >>> len(b)
>>> print(c)
appears in the middle 18
Aliens are coming. Watch out! Run! of the message

The string in variable “b”


△ Adding another string in between
(“Aliens are coming.”) is
A new string can also be added between 18 characters long
two strings. Try the example above.
STRINGS IN PYTHON 115
Numbering the characters
Each character in a string is allocated a number
according to its position. This position number
can be used to look at individual letters or
symbols, or to pull them out of a string.

Count begins from zero Counting the characters


1 When counting the positions, Python 2 The position number is called
starts at 0. The second character is in position an “index.” It can be used to pull out
1, the third in position 2, and so on. a particular letter from a string.

>>> a = "FLAMINGO" The sixth letter, >>> a[3]


“N”, is in position 5 "M" Square brackets go
around the index

F L A M I N G O The character in position 3


from the variable “a”

0 1 2 3 4 5 6 7 The last character,


“O”, is in position 7

The first character,


“F”, is in position 0

“Slicing” From the start or the end


3 Two indexes can be used to pull out 4 If you leave off the start or end
a part of the string or “slice” it. The letter in index, Python will automatically use the
the last position isn’t included. first or the last character of the string.

>>> a[1:7] >>> a[:3]


Colon defines
"LAMING" the range of "FLA"
characters >>> a[3:]
Starts at
A slice from index 1 to index 0 "MINGO" Ends at index 7
index 6 of variable “a”

Apostrophes >>> print('It\'s a cloudy day.')


Strings can go in single or double It's a cloudy day.
quotation marks. However, the string
should start and end with the same type △ Escaping the apostrophe
of quotation mark. This book uses double So Python doesn’t read an
apostrophe as the end of the
quotes. But what happens if you want to The apostrophe
is included in string, type a “\” before it.
use an apostrophe in your string? the string This is called “escaping” it.
116 P L AY I N G W I T H P Y T H O N

Input and output SEE ALSO

‹ 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

Input The “input()” function allows


The “input()” function is used to accept input from the users to interact with a program
using their keyboard
keyboard into a program. It waits until the user finishes
typing and presses the “return” or “Enter” key.

Adding a space

1 Using input
A program can prompt the
after the colon
makes the output 2 Output in the shell window
When the program is run, the message
look tidier
user what to type. The message is “Enter your name: ” and its response appear
put inside the brackets of “input()”. in the shell window.

name = input ("Enter your name: ") Enter your name: Jina
print("Hello", name) Hello Jina

What the program outputs depends Program outputs User types in


on what name the user types message their name

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

Using the “print()” function


1 Create some variables
Set up three variables for this simple 2 You can put several items inside the brackets
experiment. Two are strings and one is an of the “print()” function. You can combine variables of
integer (whole number). different types, and even combine strings and variables.

>>> a = "Dave" >>> print(a, b, c)


Quote marks
>>> b = "is" Dave is 12
show these
>>> c = 12 are strings >>> print("Goodbye", a)
Goodbye Dave

No quote marks as Comma separates


this is an integer the different items
INPUT AND OUTPUT 117
Two ways to separate strings
So far, the output has been printed on one The separator
line with a space between the items. Here
are two other ways of separating strings. >>> print(a, b, c, sep="\n")
Dave
>>> print(a, b, c, sep="-") is Each variable
Dave-is-12 The character 12 starts on a
between the new line
outputs
△ Hyphenate the outputs △ Outputs on new lines
A hyphen can be put between the variables The space or character between the 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.

Three ways to end output EXPERT TIPS


There are several different ways you Options at the end
can signal the end of the output of
a “print” function. The “end” and “sep” labels tell Python that the
next item in the program isn’t just another
string. Remember to use them; otherwise, the
program will not work correctly.
>>> print(a, ".") Full stop added
Dave . as a string

>>> print(a, end=".")


Full stop added
as an “end”
end sep
character
Dave.

△ Add a full stop 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.

Space >>> print(a, end="\n\n\n\n")


Loop to print as “end”
character Dave Each “\n” starts
three times
a new line

>>> for n in range(3):


Blank space
print("Hurray!" end=" ") before the
prompt
Hurray! Hurray! Hurray! >>>
Output is
△ Output on one line all printed △ Blank lines at the end
on one line
Usually, each new “print” command starts Using “\n” starts each output from a new
on a new line. To get the output all on one line. Several of them can be used together
line use a space as the “end” character. to add blank lines at the end of a program.
118 P L AY I N G W I T H P Y T H O N

Making decisions SEE ALSO

‹ 62–63 True or
false?
Programs make decisions about what to do
by comparing variables, numbers, and strings
‹ 108–109 Variables
in Python
using Boolean expressions. These give an
answer of either “True” or “False.”

Logical operators
Logical operators are used to compare variables against
numbers or strings, or even against other variables.
The resulting answer is either “True” or “False.”

“Equals”
== operator

“Not equal
!= to” operator
This checks This checks
whether “toys” whether “toys”
“Less than”
is equal to 1 is more than 1
< operator

>>> toys = 10 This checks


“Greater than” whether “toys”
>>> toys == 1
> operator
False
is less than 1

“Less than or >>> toys > 1 This checks if

<= equal to” operator


True “toys” is not
equal to 1
>>> toys < 1
“Greater than or This checks if
>= equal to” operator False
>>> toys != 1
“toys” is less than
or equal to 10

△ Types of comparison operators True The “not” logical


operator reverses the
There are six comparison operators. Python >>> toys <= 10
answer (in this example,
uses two equals signs to compare if two True from “False” to “True”)
things are the same. (A single equals sign
is used to assign a value to a variable.) >>> not toys == 1 The “or” logical
operator checks if
True
“toys” is 9 or 10
>>> toys == 9 or toys == 10
▷ Use the shell to check
True The “and” logical operator
Logical operators also work in the is used to check if “toys” is
shell window. Use this example to >>> toys == 9 and toys == 10 both 9 and 10. This can
try out several logical operators, never be true, so the
False
including “not,” “or,” and “and.” answer is “False”
MAKING DECISIONS 119
Is it Ella’s birthday? 1 Check for the birthday
Create variables for a day and a month.
Ella’s birthday is July 28th. This Use the “and” logical operator to check
program takes a day and a month whether it is July 28th.
and uses logical operators to check
>>> day = 28 Remember
whether it’s Ella’s birthday. to use two
>>> month = 7 equals signs
>>> day == 28 and month == 7
True

It’s Ella’s The “and” operator checks to


birthday! see if both conditions are true

Not the birthday detector Birthday or New Year’s Day?


2 You can reverse the answer using the “not” 3 Use the “or” logical operator to check whether
logical operator. You will get the answer “True” on it’s Ella’s birthday or New Year’s Day. Use brackets to
every day, except for Ella’s birthday. combine the correct days and months.
This character
>>> day = 28 is used to make >>> day = 28 Checks for the
code go over 28th of July
>>> month = 7 >>> month = 7
two lines
>>> not (day == 28 and \ >>> (day == 28 and month == 7) \
The answer will
month == 7) be “True” if it’s or (day == 1 and month == 1)
It’s Ella’s birthday, so Ella’s birthday or
False True
the answer is “False” New Year’s Day

Strings EXPERT TIPS


Two strings can be compared using the Operator for strings
“==” operator or the “!=” operator. Strings
have to match exactly to get a “True” output. The “in” operator can be used to see
whether one string is inside another
string. Use it to check if a string
>>> dog = "Woof woof" The strings match contains a particular letter or a
exactly, so the
>>> dog == "Woof woof" answer is “True”
group of letters.
This checks
True whether “a”
The strings don’t is in “abc”
>>> dog == "woof woof" match because there
isn’t a capital “W”
False >>> "a" in "abc"
>>> dog == "Woof woof " The strings don’t True
False match because there’s >>> "d" in "abc"
extra space before
the quotation mark False
△ Exactly the same
Strings must match for them to be equal. That “d” is not in “abc”, so
means they must use capital letters, spaces, the answer is “False”
and symbols in exactly the same way.
120 P L AY I N G W I T H P Y T H O N

Branching SEE ALSO

‹64–65 Decisions
and branches
Boolean expressions can be used to determine which
route a program should follow, depending on whether
‹118–119 Making
decisions
the answer to the expression is “True” or “False.” This is
known as “branching.”

Do or do not
The “if” command means that if a condition is “True,” then the program runs
a block of commands. If the condition isn’t “True,” the block is skipped. The
block after the “if” command is always indented by four spaces.

“if” condition
1 This code asks the user
ans = input("Is it your birthday? (y/n)") Prompts users
what to type in
if it’s their birthday. It checks if ans == "y":
whether the answer is “y”. If so, print("Happy Birthday!")
a birthday message is printed.
This part of the
Indented by four spaces program runs only
Type in “y”
if the user types “y”
Output if condition is “True”
2 Run the program and enter “y”.
Is it your birthday? (y/n)y The message
appears
The message is printed. It doesn’t Happy Birthday!
appear if anything else is entered.

Do this or that
The “if” command can be combined with an
“else” command. This combination means that
if something is “True,” one thing happens, and if
not, something else happens.

“if-else” condition
1 If “y” is entered, the program
ans = input("Is it New Year? (y/n)") Remember the colon

prints a special message for New if ans == "y":


This message
Year. It shows a different message print("Happy New Year!") appears only if
if anything else is entered. the user enters “y”
print("Time for Fireworks.")
else: Remember to put
a colon here too
print("Not yet!")
Runs only if user
does not enter “y”
BRANCHING 121
Output if condition is “True”
2 Run the program and type in “y”. The program 3 “else” condition output
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.

Is it New Year? (y/n)y Is it New Year? (y/n)n Type in “n”

Happy New Year! Type in “y” Not yet!


Time for Fireworks. A different
message appears

Do one of these things


The “elif“ command is short for “else-if”. It means that
if something is “True,” do one thing; otherwise, check if
something else is “True” and do something else if it is.
The following calculator program uses the “elif“ command.

“if-elif-else” condition
1 This program checks what is typed 2 Output for the condition that’s “True”
Test the program. Enter two numbers and
in. If it’s “add”, “sub”, “mul”, or “div”, the type in “sub”. The answer will be the first number
result of the sum is shown. minus the second number.
Remember to Enter two numbers
Asks the user to add quote marks a = 7
input a number and brackets
b = 5
Type in “sub”
add/sub/mul/div:sub
a = int(input("a = ")) to subtract
Answer = 2 5 from 7
b = int(input("b = "))
op = input("add/sub/mul/div:")
Answer is calculated
if op == "add": by subtracting variable
Type “add” “a” from variable “b”
c = a + b to add the
elif op == "sub": variables
together
c = a - b
“else” condition output
elif op == "mul": 3 The “else” condition runs if something other than
c = a * b “add”, “sub”, “mul”, or “div” is typed in, and an error message
is displayed.
elif op == "div": Type “div” to
c = a / b divide the a = 7
variables
else: b = 5
Type something
c = "Error" add/sub/mul/div:try different here

print("Answer = ",c) Answer = Error

Shows the answer Shows an error message in “c” Error message


or error message if something else is typed in displays
122 P L AY I N G W I T H P Y T H O N

Loops in Python SEE ALSO

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

Program the turtle


1 A “for” loop can also be used to shorten the
from turtle import *
Loads all the
code. This program allows the user to control a turtle forward(100)
commands
that draws a line as it moves around the screen. The right(120) that control
user can draw shapes on the screen, such as a triangle, the turtle
forward(100)
by directing the turtle’s movements.
right(120)
This command
forward(100) moves the turtle
This makes the
forward
turtle turn 120 right(120)
degrees to the right

The turtle draws a triangle Use a “for” loop


2 The program tells the turtle how to draw a 3 The program above gives the turtle the same two
triangle by giving it the length of the three sides and commands, “forward(100)” and “right(120)”, three times –
the angles between them. The turtle will appear in once for each side of the triangle. An alternative to this
a separate window when you run the program. is to use these two commands inside a “for” loop. Try
drawing a triangle simply using the code shown below.

for i in range(3): The “for” loop tells the


program to repeat
forward(100) the instructions
The turtle right(120) three times
in Python

The program The block of instructions


makes the turtle in a loop is indented by
draw a triangle four spaces
LOOPS IN PYTHON 123
Loop variables The loop variable The loop repeats ten times

A loop variable counts the number of times for i in range(10):


a loop has repeated itself. It starts at the first print(i, end=" ")
value in the range (0) and stops one before
the last value. >>> 0 1 2 3 4 5 6 7 8 9
Python stops
counting one before
the last value △ Simple loop variable
Here, the loop’s range doesn’t state what the starting
value should be. So Python starts counting from 0, the
This tells the same way as it does with strings.
program to
count in twos This tells the program
to count backward

for i in range(2, 11, 2): for i in range(10, 0, -1):


print(i, end=" ") print(i, end=" ")

>>> 2 4 6 8 10 The output >>> 10 9 8 7 6 5 4 3 2 1


appears in twos
△ Counting in twos △ Counting backward
This loop has a third value in its range, which tells the This time the program counts backward from 10, like in
loop to count in twos. It stops at 10, which is one loop a rocket launch. The loop variable starts at 10 and takes
before the loop variable gets to 11. steps of -1 until it reaches 1.

Nested Loops
Loops inside a loop are called “nested loops.” >>> The value of “a”
In nested loops, the outer loop repeats only 1 x 1 = 1
The value First time around
after the inner loop has gone around its of “b” 2 x 1 = 2 the outer loop (the
required number of times. inner loop repeats
3 x 1 = 3 three times)
To make the loops repeat “n” number of times, 1 x 2 = 2
the last number in the range must be “n + 1” Second time around
2 x 2 = 4 the outer loop
n = 3 Outer loop 3 x 2 = 6
for a in range(1, n + 1): 1 x 3 = 3
Third time around
for b in range(1, n + 1): 2 x 3 = 6 the outer loop
print(b, "x", a, "=", b * a) 3 x 3 = 9

△ Loops inside a loop Inner △ What happens


In this example, each time the outer loop The nested loops print the first three lines
loop goes around once, the inner loop This sum will be
of the 1, 2, and 3 times tables. The value
goes around three times. So in total, the printed nine times of “a” changes only when the outer loop
outer loop is executed three times and repeats. The value of “b” counts from 1
the inner loop is executed nine times. to 3 for each value of “a”.
124 P L AY I N G W I T H P Y T H O N

While loops SEE ALSO

‹118–119 Making
decisions
“For” loops are useful when you know how many times a
task needs to be repeated. But sometimes you’ll need a
‹ 122–123 Loops
in Python
loop to keep repeating until something changes. A “while” Escaping 126–127 ›
loop keeps on going around as many times as it needs to. loops

While loops ▷ How it works


A while loop No
A while loop keeps repeating as long as a certain checks if the Monster friendly?
condition is true. This condition is called the condition is true.
If it is, it goes Yes
“loop condition” and is either true or false.
around the loop
Create a while loop again. If it’s not,
1 Set the starting value of the “answer” variable in it skips the loop.
Stay very still

the loop condition. The loop condition has to be true


to start with or the program will never run the loop. The “answer” variable is set to “y”

The code answer = "y" Run away!


inside the
loop must while answer == "y": The while loop runs only
be indented if the condition is true
four spaces print("Stay very still")
answer = input("Is the monster friendly? (y/n)")
print("Run away!")

If the condition is false, unindented code after


the loop runs and a different message appears
REMEMBER

2 What the program looks like “repeat until” block


The value entered is stored in the variable “answer”.
The loop condition is “answer == ‘y’”. If you type “y”, Python’s “while” loop is similar to
the loop keeps going. If you type “n”, the loop stops. the “repeat until” block in Scratch.
Both keep on repeating until
>>> something different happens in
Stay very still Answer is “y”, the program.
so the loop
Is the monster friendly? (y/n)y keeps running
repeat until
Stay very still
Is the monster friendly? (y/n)y
Stay very still
Is the monster friendly? (y/n)n Answer is “n”, so the Repeats blocks inside it
Run away! loop ends and a new until condition is true
message appears
WHILE LOOPS 125
Forever loops
Some loops run forever. If you set the condition in a “while”
loop to be “True,” it can never be false and the loop will △ Going loopy
never end. This can either be useful or very annoying. A loop with the
condition “True” is
Create a forever loop called an “infinite”
1 The loop condition here is set to
loop. If something is
infinite it has no end.
“True.” Nothing that happens inside the
loop will make “True” equal anything The loop is always “True”
but “True,” so the loop runs forever. so will never end

while True:
answer = input("Type a word and press enter: ")
The typed word
print("Please do not type \"" + answer + "\" again.") is stored in the
variable “answer”

What the program looks like


2 On the opposite page the monster program’s loop condition
checked to see what the user’s answer was. If the answer isn’t “y”,
the loop will stop. The loop shown above doesn’t check the
answer, so the user can’t make it stop.

>>>
Type a word and press enter: tree No matter what
is typed, this REMEMBER
Please do not type "tree" again loop just keeps
Type a word and press enter: hippo
on going “forever” block
Please do not type "hippo" again Remember the “forever” block in
Scratch? It repeats the code inside
Type a word and press enter: water
it until the red stop button is
Please do not type "water": again clicked. A “while True” loop does
Type a word and press enter exactly the same thing. It can be
used to make a program keep
doing something, such as asking
questions or printing a number, as
EXPERT TIPS long as the program is running.
Stop the loop
If you get stuck in an infinite loop, you can forever
stop it from IDLE. Click in the Python shell
window, then hold down the “CTRL” key and
press the “C” key. This asks IDLE to stop the
Ctrl-C
program. You might have to press “CTRL-C”
a few times. This is similar to clicking the red The “forever” block keeps
stop button in Scratch. the sprite moving endlessly
126 P L AY I N G W I T H P Y T H O N

Escaping loops SEE ALSO

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

The variable “i” will


Inserting breaks count from 1 to 12
Putting a break into a loop makes
the program jump out of the table = 7
loop at once—even if the loop for i in range(1, 13):
condition is true. Any commands print("What's", i, "x", table, "?")
inside the loop that come after guess = input()
the break are ignored. ans = i * table “i” is the loop
if int(guess) == ans: variable
Write a simple program
1 This program tests the user on the
print("Correct!")
else:
7 multiplication table. The program
continues looping until all 12 questions are print("No, it's", ans)
answered. Write this program in the code print("Finished")
window because it will be edited later.

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 == "stop":
If “guess” equals “stop”, the break
program skips the rest of the
loop and prints “Finished” ans = i * table
if int(guess) == ans:
print("Correct!")
else:
print("No, it's", ans)
print("Finished")

The “ans” variable holds the


correct answer to the question
ESCAPING LOOPS 127
How it works
>>>
The first time
3 If the user decides not to carry on after
What's 1 x 7 ? around the loop the third question and types “stop”, the break
1 “i” is equal to 1 command is executed and the program
leaves the loop.
No, it's 7
What's 2 x 7 ?
The value of “i”
14 changes to 2 next
time around the loop
Correct!
What's 3 x 7 ?
stop
Finished
This executes the break
command and the
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 to
for i in range(1,13): see if the user answered “skip”. If so, the program
print("What's", i, "x", table, "?") will print “Skipping” and execute a “continue”
to skip to the next go around the loop.
guess = input()
Asks the question
if guess == ‘stop’: “What’s 1 x 7?” first
time around the loop
break
What happens
if guess == "skip": 5 If the user doesn’t want to answer
print("Skipping") a question, he or she can type “skip” and
Skips straight continue to the next question.
continue to the next loop
ans = i * table >>>
if int(guess) == ans: What's 1 x 7 ?
Type “skip” to go to
print("Correct!") skip the next question
else: Skipping
print("No, it's", ans) What's 2 x 7 ? The loop goes around
print("Finished") again as normal when
14
the answer is correct
Correct!
What's 3 x 7 ?
128 P L AY I N G W I T H P Y T H O N

Lists SEE ALSO

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

>>> mylist = ["apple", "milk", "cheese", "icecream", "lemonade", "tea"]

The items in the list sit inside The items in a list are
a pair of square brackets separated by commas

Just like with strings, Python starts counting


the items in a list from zero. So, here, the

[0] position (or “index”) of “apple” is “0”

▷ How it works
You can think of a list as a row Typing “mylist[1] = "cake"”

[1]
of shelves in a kitchen. Each would replace “milk” on shelf 1
shelf holds one item from the with “cake” instead
list. To make changes to an
item, you must refer to the
shelf it is on. The value of “mylist[2]”

[2] is “cheese”

You could add an orange in front of the ice


cream by typing “mylist.insert(3, "orange")”.

To get to an item
on the list, you
[3] The ice cream would then move to position
4, and so on

must go to the Writing “del mylist[4]” would delete


right shelf “lemonade” from the list, and move
[4] “tea” into position 4 instead

You could add a new item, “pie”, at


The position the end of the list by writing “mylist.
of an item in
a list is called
its “index”
[5] append(‘pie’)”. This will then be
added after “tea”, in position 6
LISTS 129
Using lists LINGO
Once a list has been created, you can write programs to Mutable objects
manipulate the data inside it—in a loop, for example.
You can also combine lists to make new lists. Lists in Python are “mutable.”
This means that they can change.
You can add or delete items, or
switch around their order. Other
The list is stored in the variable “names”
functions in Python, such as tuples
The body of (see pp.134–135), can’t be altered
>>> names = ["Simon", "Kate", "Vanya"] once you create them. These are
the loop must
be indented by >>> for item in names: called “immutable.”
four spaces
print("Hello", item)

◁ Lists in loops
Hello Simon
You can use a loop to work through
When run, this program
Hello Kate every item in a list. This program
displays “Hello”, followed
Hello Vanya by each name on the list says “Hello” to a series of names,
one after the other.

Remember, lists are contained


within square brackets
▷ Adding lists x = [1, 2, 3, 4]
Two lists can be
y = [5, 6, 7, 8] This adds the
added together.
lists together
The new list will z = x + y
contain the items
print(z)
from both of the
old lists. z = [1, 2, 3, 4, 5, 6, 7, 8] The new list contains
everything from list “x”
followed by everything
▽ Lists in lists from list “y”

The items in a list can be lists


Because the list is inside
themselves. The “suitcase” list below square brackets, it
contains two lists of clothes—it is like becomes an individual
a suitcase shared by two people, item within the “suitcase”
where they each pack three items. list—“suitcase[0]” “suitcase[1]”

>>> suitcase=[["hat", "tie", "sock"],["bag", "shoe", "shirt"]]


>>> print(suitcase) This will print the whole suitcase list
[["hat", "tie", "sock"],["bag", "shoe", "shirt"]]
>>> print(suitcase[1]) This will print everything in the
second list, “suitcase[1]”
["bag", "shoe", "shirt"]
This prints the item at index 2 in
>>> print(suitcase[1][2])
“suitcase[1]”—remember, Python
shirt starts counting the items from 0
130 P L AY I N G W I T H P Y T H O N

Functions SEE ALSO


Silly 132–133
sentences

A function is a piece of code that performs a specific task.
It bundles up the code, gives it a name, and can be used
Variables and 138–139
functions

any time by “calling” it. A function can be used to avoid
entering the same lines of code more than once.

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.

print() input() randint()


△ “print()” function △ “input()” function △ “randint()” function
This function lets the program This function is the opposite of the This function gives a random
send output to the user by “print()” function. It lets the user number (like throwing a die).
printing instructions or results give instructions or data to the It can be used to add an element
on the screen. program by typing them in. of chance to programs.

Making and calling functions


The functions that come with Python aren’t the only ones that
can be used. To make a new function, collect the code you want
to use in a special “wrapper” and give it a name. This name
allows the function to be called whenever it is needed.

Define a function Call the function


1 The definition of a function will always 2 Typing the function name followed
have the keyword “def” and the function’s by parentheses into the shell window calls
name at the beginning of the code. the function and shows the output.

def greeting(): A colon marks the end >>> greeting()


of the function’s name
print("Hello!") and the start of the Hello!
code it contains

This is the code


within the function The “greeting” Parentheses
function is called show that this is
and the output a function call,
is displayed not a variable
FUNCTIONS 131
Passing data to functions
A function has to be told which values to work with.
For example, in “print(a, b, c)”, the function “print()” is being
passed the values “a”, “b”, and “c”. In “height(1, 45)”, the values
1 and 45 are being passed to the function “height”.

Add parameters to the function Values are defined


1 Values passed to a function are called “parameters.” 2 The code inside the function
Parameters are put inside the parentheses next to the uses the values that are passed to it.
function’s name in its definition.
Calls the function to give
“m” and “cm” are the parameters the answer when “m” = 1
and “cm” = 45

def height(m, cm): >>> height(1, 45)


total = (100 * m) + cm 145 cm tall
print(total, "cm tall")

Shows that 1 m 45 cm
To figure out the total in is equal to 145 cm
Prints the value of “total” “cm”, the value of “m” needs
followed by “cm tall” to be multiplied by 100
(because 1 m = 100 cm)

Getting data back from functions


Functions are most useful when they send some data
back to the program—a return value. To make a
function return a value, add “return” followed by the
value to be sent back.

Define a function that returns a number Number as output


1 Python’s “input()” function always returns a string, 2 If the program used the function
even if a number is entered. The new function below “input”, “a + b” would put the strings “10”
gives back a number instead. and “7” together to give “107”.
The number
def num_input(prompt): is stored as a string Enter a 10
typed = input(prompt) in the variable “typed” Enter b 7 Type in a number

num = int(typed) This converts the string a + b = 17


into a number and stores
return num it in the variable “num”

Returns the value


a = num_input("Enter a") stored in the variable Adding “a + b” outputs
“17” because the
b = num_input("Enter b") function “num_input”
print("a + b =", a + b) gives back numbers,
not strings
132 P L AY I N G W I T H P Y T H O N

PROJECT 5

Silly sentences SEE ALSO

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

Make silly sentences


This program will make sentences by using three separate
lists of words. It will pick one word from each list and put
them together randomly in a silly sentence. Try using different words from
the ones shown here to create
your own silly sentences.
Enter the three lists shown below
1 into a new code window. This Double quotes show
that each item in the
defines the lists that will be used
list is a string
to make the sentences.

name = ["Neha", "Lee", "Sam"]


verb = ["buys", "rides", "kicks"] Square brackets
noun = ["lion", "bicycle", "plane" mean that this
is a list

Each sentence is made up of words picked at


2 random from the lists you have created. Define
a function to do this, because it will be used This loads the function
several times in the program. for generating a random
number (“randint”)

from random import randint


Finds out how many def pick(words):
words are in the list
(the function works num_words = len(words)
for lists of any length) num_picked = randint(0, num_words - 1)
word_picked = words[num_picked] Picks a random number
return word_picked that refers to one of the
items in the list
Stores the random word
that has been picked in the
variable “word_picked”
S I L LY S E N T E N C E S 133

Print a random silly sentence by running


3 the “pick” function once for each of the This adds a full stop at
the end, while the “\n”
three lists. Use the “print” command to starts a new line
show the sentence on the screen.

print(pick(name), pick(verb), "a", pick(noun), end=".\n")

Add an “a” so that the sentence


makes sense (see below)
Save and run the program to get
4 a silly sentence made from the lists
of names, verbs, and nouns.

Neha kicks a bicycle.

The sentence is randomly selected


each time the program is run

Silly sentences forever! EXPERT TIPS


A forever loop can be added to the silly sentences Readable code
program to keep it running forever, or until the user
presses “Ctrl-C” to escape the loop. It’s very important to write
a program that can be easily
understood. It makes the program
easier to change in the future
because you don’t have to start by
The program keeps printing silly solving the puzzle of how it works!
1 sentences if the “print” command Wraps the print
is wrapped in a “while True” loop. command in a loop

while True:
print(pick(name), pick(verb), "a", pick(noun), end=".")
input()

Prints a new sentence every time


the “Enter” key is pressed The program will keep on
creating random sentences
The “input()” function
2 waits for the user to press Sam rides a lion.
the “Enter” key before Neha kicks a plane.
printing another sentence.
Without this it would print Lee buys a bicycle.
them too fast to read.
134 P L AY I N G W I T H P Y T H O N

Tuples and dictionaries SEE ALSO

‹ 110–111 Types
of data
Python uses lists for keeping data in order. It also has
other data types for storing information called “tuples”
‹ 128–129 Lists
and “dictionaries.” Data types such as these, which hold
lots of items, are called “containers.”

Tuples
Tuples are a bit like lists, but the items inside them
can’t be changed. Once a tuple is set up it always
stays the same. Tuples are surrounded
by brackets

>>> dragonA = ("Sam", 15, 1.70)


◁ What is a tuple?
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.

▷ Grabbing an item from a tuple >>> dragonB[2]


To get an item from a tuple, use
its position in the tuple (its index). 1.68
Tuples count from zero, just like
lists and strings. This selects the item
from position 2

>>> name, age, height = dragonA


◁ Splitting a tuple into variables
Assign three variables to the tuple
>>> print(name, age, height) “dragonA”—“name“, “age“, and “height“.
Sam 15 1.7 Python splits the tuple into three items,
putting one in each variable.
The items that make up the tuple
“dragonA” are displayed separately
Create a list of tuples Lists go in
called “dragons” square brackets

▷ Putting tuples in a list >>> dragons = [dragonA, dragonB]


Tuples can be put into a list
because containers can go inside >>> print(dragons)
each other. Use this code to [("Sam", 15, 1.7), ("Fiona", 16, 1.68)]
create a list of tuples.
Each tuple is surrounded Python displays all the items
by round brackets inside that are in the list, not just
the list’s square brackets the names of the tuples
TUPLES AND DICTIONARIES 135
Dictionaries
Dictionaries are like lists but they have labels. These labels, called “keys,”
identify items instead of index numbers. Every item in a dictionary has
a key and a value. Items in a dictionary don’t have to stay in a particular
order, and the contents of a dictionary can be changed.
Dictionaries Items in a dictionary
use curly are separated
Use a colon between
brackets by commas
▷ Create a dictionary a key and a value
This program creates a
dictionary called “age”. >>> age = {"Mary": 10, "Sanjay": 8}
The key for each item
is the name of a person. A key works in A value stored in
The value is their age. the same way as the dictionary (always
an index number comes after a colon)

>>> print(age)
◁ Print the dictionary
Name of the dictionary
The order of the items
{"Sanjay": 8, "Mary": 10} can change, because the
positions of items in a
The value of “Mary” is 10
The key for this dictionary are not fixed.
item is “Sanjay” Dictionary
name New key
▷ Add a new item >>> age["Owen"] = 11
A new value can be Adds a new item
>>> print(age) to the dictionary.
added to the dictionary
by labeling it with the {"Owen": 11, "Sanjay": 8, "Mary": 10}
new key.
The new value is now The existing values
in the dictionary are still there
Assign a new value to
the item labelled “Owen”

>>> age["Owen"] = 12
◁ Change a value
Assign a new value to
>>> print(age) an existing key to change
{"Owen": 12, "Sanjay": 8, "Mary": 10} its value.

The value for “Owen”


has changed This deletes the item
labelled “Owen”

▷ Delete an item
>>> del age["Owen"] The item labelled
Deleting an item in a dictionary “Owen” no longer
doesn’t affect other items because >>> print(age) appears in the
they are identified by their key, not {"Sanjay": 8, "Mary": 10} dictionary
by their position in the dictionary.
136 P L AY I N G W I T H P Y T H O N

Lists in variables SEE ALSO

‹ 108–109 Variables
in Python
There’s something about how Python stores lists
in variables that might seem a bit odd at first. But
‹ 128–129 Lists
take a look at what’s going on behind the scenes
and it all makes sense.

2
Remember how variables
only store values? a b
Variables are like boxes that hold values. △ How variables work
The value in one variable can be copied Each variable is like a box containing a
and stored in another. It’s like photocopying piece of paper with a value written on it.
the value contained in box “a” and storing
a copy in box “b.” This copies the contents
of “a” into “b”
Assign a value to a variable
1 Assign the value 2 to variable
>>> a = 2

“a”, then assign the value in “a” to >>> b = a


variable “b”. The value 2 is copied >>> print("a =", a, "b =", b)
and stored in “b”.
a = 2 b = 2

This prints out the


Now “a” and “b” both variable names
contain the value 2 with their values
Change the value
in “a” to 100
Change a value
2 If you change the value stored
>>> a = 100

in one variable it won’t affect the value >>> print("a =", a, "b =", b)
stored in another variable. In the same a = 100 b = 2
way, changing what’s written on a piece
of paper in box “a” won’t affect what’s on Now “a” contains 100,
the paper in box “b”. but “b” still contains 2

Change a different value


3 Change the value in “b” to 22.
>>> b = 22

Variable “a” still contains 100. Even though >>> print("a =", a, "b =", b)
the value of “b” was copied from “a” a = 100 b = 22
at the start, they are now independent—
changing “b” doesn’t change “a”.
“b” now contains 22,
but “a” is still 100
L I S TS I N VA R I A B L E S 137
What happens if a list is put in a variable?
Copying the value in a variable creates two independent
copies of the value. This works if the value is a number, but
what about other types of value? If a variable contains a list
it works a bit differently. Use square brackets
to create a list

Copy a list This prints out


1 Store the list [1, 2, 3] in
>>> listA = [1, 2, 3] the variable
>>> listB = listA names alongside
a variable called “listA”. Then
their values
store the value of “listA” in >>> print("listA =", listA, "listB =", listB) to see what’s
another variable called “listB”. inside them
listA = [1, 2, 3] listB = [1, 2, 3]
Now both variables contain
[1, 2, 3].
“listA” and “listB” both
hold the same value This changes the second item in
the list because lists count from 0

Change list A
2 Change the value in
>>> listA[1] = 1000

“listA[1]” to 1,000. “listB[1]” >>> print("listA =", listA, "listB =", listB)
now contains 1,000 as well. listA = [1, 1000, 3] listB = [1, 1000, 3]
Changing the original list has
changed the copy of the list too. The second item of
This is the third both “listA” and “listB”
item in the list has been changed

Change list B
3 Change the value of
>>> listB[2] = 75

“listB[2]” to 75. “listA[2]” is now >>> print("listA =", listA, "listB =", listB)
75 as well. Changing the copy listA = [1, 1000, 75] listB = [1, 1000, 75]
of the list has changed the
original list as well. The third item of both “listA”
and “listB” has been changed

[1, 2, 3] EXPERT TIPS


Copying lists
To make a separate copy of a list, use the
“copy” function. “listC” will contain a
link to a completely new list whose values
listA listB are copies of those in “listA”. Changing
“listC” won’t change “listA”, and changing
“listA” won’t change “listC”.
△ What’s going on?
A variable containing a list doesn’t hold the list itself, >>> listC = listA.copy()
just a link to it. Copying the value in “listA” copies the link.
So both “listA” and “listB” contain a link to the same list.
138 P L AY I N G W I T H P Y T H O N

Variables and functions SEE ALSO

‹ 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

Local variables exist only inside a single function, so


the main program and other functions can’t use them.
If you try to use a local variable outside of the function,
an error message appears.

Variable inside the function Variable outside the function


1 Create a local variable called “a” 2 If you try to print “a” directly The main program doesn’t
inside “func1”. Print out the value of “a” by from the main program, it gives an know what “a” is, so it
calling “func1” from the main program. error. “a” exists only inside “func1”. prints an error message

>>> def func1(): >>> print(a)


a = 10 Traceback (most recent call last):
print(a) File "<pyshell#6>", line 1, in <module>
>>> func1() print(a)
Calling “func1” prints
10 the value given to “a” NameError: name "a" is not defined

Global variables
A variable created in the main program is
called a global variable. Other functions Global variables
can read it, but they can’t change its value. are like people
walking along the
street—everyone
can see them

1 Variable outside the function


Create a global variable called “b” in the 2 Same global variable
We can also print “b” directly from the
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.

>>> b = 1000 “func2” can see >>> print(b)


the value of “b”
>>> def func2(): because “b” is a 1000
global variable
print(b)
>>> func2() Printing “func2” Global variable “b” can
1000 gives you the be used anywhere in
value stored in “b” the main program
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 value >>> print(z) Prints the value in global
passed to it when variable “z” after “func3”
print(y) “func3” is called butter
has finished running
y = "bread"
print(y) Here “y” contains “bread” Local variable “y” of “func3” holds a
copy of the value in “z”. Although “y”
>>> z = "butter" has been changed to “bread”, the
This creates a global
>>> func3(z) value in global variable “z” isn’t
variable called “z”
affected and is still “butter”
butter The input “y” now contains
bread the value of “z” passed to it
when “func3” is called

Masking a global variable


A global variable can’t be changed by a function. A function trying to
change a global variable actually creates a local variable with the same
name. It covers up, or “masks,” the global variable with a local version.

EXPERT TIPS
Changing a
1 global variable
>>> c = 12345 Initial value
in global Calling functions
Global variable “c” is given >>> def func4(): variable “c”
There are two different ways of
the value 12345. “func4” c = 555
gives “c” the value 555
calling functions.
print(c)
and prints it out. It looks
like our global variable >>> func4() Prints the function(a)
“c” has been changed. value of “c”
555 In Python, items of data are called
inside “func4”
“objects.” Some functions are called
by passing them the data object (“a”).
Print variable
2 If we print “c” from
>>> print(c)
a.function()
outside the function, we 12345
see that “c” hasn’t changed Other functions are called by adding
at all. “func4” prints only The value in global their name at the end of the data
the value of its new local variable “c” hasn’t object (“a”) after a period.
variable—also called “c”. been changed
140 P L AY I N G W I T H P Y T H O N

PROJECT 6
Drawing machine SEE ALSO

‹ 122–123 Loops
in Python
It’s time to try a more complex project. This program, the
drawing machine, turns a string of simple instructions
Libraries 152–153 ›
into turtle commands to draw different shapes. The skills
used in planning this program are essential for any coder.

Choose a test shape


To write a program that can draw any shape, from turtle import *
it’s useful to choose a shape to start with. Use reset() Loads all the commands
that control the turtle
this house shape as an example to test the left(90)
program at each stage. By the end of the forward(100) Resets the turtle’s
project it will be possible to draw this house position and puts the
right(45)
with far less code—by using a single string pen down ready to draw
containing several short drawing commands forward(70)

(for example, “F100”). right(90)


forward(70)
right(45) Moves the turtle
forward by 70
forward(100)
right(90) Makes the turtle turn
90 degrees to the right
▷ Turtle draws a house forward(100)
The arrow shows the final
direction and position of the △ Program to draw a house
turtle. Starting at the bottom The turtle This code tells the turtle to draw a house.
left, it has moved clockwise It requires lots of lines of code for what is
around the house. actually quite a simple program.

Three parts Function 1 Function 2 Main program


of the program △ Turtle controller △ String artist △ User interface
The drawing machine will This function takes a In this program, the The String artist needs
be a large program. To help simple command from user enters a string to get its input from
with the planning, it can be the user and turns it into of instructions. This somewhere. The User
a turtle command. The function splits the string interface allows the user
broken down into three user command will into smaller units, which to type in a string of
parts, each one related to come as a single letter are then fed to the commands for the String
a different task. and a number. Turtle controller. artist to work on.
D R AW I N G M AC H I N E 141

Draw a flowchart EXPERT TIPS


Coders often plan programs on paper, to help them write Squares and diamonds
better code with fewer errors. One way to plan is to draw
a flowchart—a diagram of the steps and decisions that Flowcharts are made up of squares
and diamonds. The squares
the program needs to follow.
contain actions that the program
performs. The diamonds are points
This flowchart shows the plan for the where it makes a decision.
1 Turtle controller function. It takes a
letter (input “do”) and number (input
“val”) and turns them into a turtle
command. For example, “F” and “100”
will be turned into the command
“forward(100)”. If the function doesn’t
recognize the letter, it reports an Action Decision
error to the user.
inputs – do and val
Each command has two variables:
“do” (a string) tells the turtle what If “do” = F, the turtle
to do, and “val” (an integer, or moves forward
whole number) tells the turtle
how much or how far to do it
Y
do == F? forward(val)

The function has to


decide if the “do” value
is a letter it recognizes N If “do” = R,
the turtle
Y turns right
If “do” isn’t F, the function runs do == R? right(val)
through other letters it recognizes

EXPERT TIPS
“do” isn’t “R”. N
Is it “U”?
Letter commands Y
do == U? penup()
The Turtle controller will use
Because “do”
these letters to stand for is “U”, the
different turtle commands: N If “do” isn’t a letter command
the function “penup()”
N = New drawing (reset) recognizes, it stops the
report unknown command
reports an error turtle from
U/D = Pen up/down
drawing
F = Forward
B = Backward
R = Right turn Once the After any command is
command is finished executed successfully,
L = Left turn return from function you return to the the program goes to
main program the end of the function
142 P L AY I N G W I T H P Y T H O N

DRAWING MACHINE
The Turtle controller
The first part of the program is a function that moves the turtle,
one command at a time. It is planned out in the flowchart on the
previous page. This code enables the turtle to convert the “do”
and “val” values into movement commands.
Loads all the commands
that control the turtle

This code creates the Defines “do” and “val” as


from turtle import *
2 Turtle controller function. inputs for the function
It turns “do” inputs into def turtle_controller(do, val):
directions for the turtle, do = do.upper()
and “val” inputs into This command converts all
angles and distances. if do == "F": the letters in “do” to upper
forward(val) case (capital letters)

elif do == "B": This tells the function


backward(val) to turn a “do” value of
F into the turtle
elif do == "R": command “forward”
right(val) As in the flowchart, the
function checks the “do”
elif do == "L":
letter against all the
left(val) letters it understands
This command tells elif do == "U":
the turtle to start This command instructs
drawing on the page penup() the turtle to stop drawing
on the page
elif do == "D":
pendown() This command resets
elif do == "N": the turtle’s position to
the center of the screen
reset()
else: This message appears if the
print("Unrecognized command") “do” value is a letter that the
function cannot recognize
The starting
position of
the turtle
These “do” and “val”
This calls the function inputs tell the turtle to
using its name move 100 steps forward

Here are some examples of how


>>> turtle_controller("F", 100)
3 to use the Turtle controller. Each
This makes the
time it is used, it takes a “do, val” >>> turtle_controller("R", 90)
turtle turn right
command and turns it into code >>> turtle_controller("F", 50) 90 degrees
the turtle can understand.
D R AW I N G M AC H I N E 143

Write some pseudocode EXPERT TIPS


Another way to plan a program is to write it in Clear coding
pseudocode. “Pseudo” means fake, so pseudocode
isn’t real code that you can run. It’s rough code where It’s not only computers that need
to be able to read your code, it
you can write your ideas in the style of the real thing.
should be clear to people too. So
it’s important to make your code
It’s time to plan the String artist. This function takes a as easy to understand as possible.
4 string of several “do” and “val” inputs and breaks it into
pairs made up of a letter and a number. It then passes Use functions to break your code into
the pairs to the Turtle controller one at a time. smaller chunks. Each function should
String of do a single task in the program.
drawing Give your variables and functions
Broken-down F100-R90-F50-R45 commands
names that say what they do: “age_in_
string years” makes more sense than “aiy.”
Use plenty of comments (using
the “#” symbol) to explain what’s
happening. This makes it easier to
‘F’ 100 ‘R’ 90 ‘F’ 50 ‘R’ 45 read back over the code.
Don’t use symbols that can be
confused with others: an upper-case
“O” looks like zero, and a lower-case “L”
This is the String artist written in pseudocode.
can look like an upper-case “i” or a “1.”
5 It lets you organize the ideas and structure of the
code without having to think about the details yet.
The function will take in a string
function string_artist(input—the program as a string): of commands input by the user
(for example, “F100-R90”)

split program string into list of commands Splits string into


a list of separate
for each command in list: commands

check it’s not blank A blank command


won’t work, so the
function skips it
—if it is go on to next item in list
Recognizes the
command type is the first letter first letter as a
“do” command
if followed by more characters Recognizes the
following characters
—turn them into a number as a “val” number

call turtle_controller(command type, number) Passes the simple command


to Turtle controller
144 P L AY I N G W I T H P Y T H O N

DRAWING MACHINE
Creating the String artist
The pseudocode on the previous page plans a function called the
String artist, which will turn a string of values into single commands
that are sent to the Turtle controller. The next stage is to turn the
pseudocode into real Python code, using a function called “split()”.

The “split()” function splits a string into a list of This string lists the
6 smaller strings. Each break point is marked by a commands to create
the sample house shape
special character ( “-” in this program).

>>> program = "N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100"


>>> cmd_list = program.split("-")
>>> cmd_list
["N", "L90", "F100", "R45", "F70", ‘R90’, "F70", "R45", "F100", "R90", "F100"]

The “split()” function breaks the string


down into a list of separate commands

Now write out the pseudocode for the String artist Tells the program to split the string
7 using real Python code. Use the “split()” function to wherever it sees a “-” character
slice up the input string into turtle commands.
This makes the program loop
through the list of strings—each
def string_artist(program): item is one command for the turtle
cmd_list = program.split("-")
Gets the If the length of the command is 0 (so
length of the for command in cmd_list: the command is blank), the function
command string cmd_len = len(command) skips it and moves to the next one

if cmd_len == 0:
Checks if the Takes the first character of the command
command continue (remember, strings start at 0) and sets it
is followed by as the command type (“F”, “U”, etc.)
cmd_type = command[0]
more characters
(the number) num = 0
This takes all the remaining
if cmd_len > 1: characters from the command
Converts the by cutting off the first one
characters from num_string = command[1:]
strings into num = int(num_string)
numbers Prints the command on the
print(command, ":", cmd_type, num) screen so you can see what
the code is doing
turtle_controller(cmd_type, num)

Passes the command


to the turtle
D R AW I N G M AC H I N E 145

When the string representing the instructions for


8 the house shape is passed into the String artist,
it shows this output in the shell window.

>>> string_artist("N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100")
N : N 0 The turtle commands
Resets the screen and puts
L90 : L 90 are all separated by a “-”
the turtle back at the center
F100 : F 100
R45 : R 45 For command “F100”, the command
type is “F” and “num” is “100”
F70 : F 70
R90 : R 90
This makes the turtle turn 45
F70 : F 70 degrees before drawing the roof
R45 : R 45
This command makes the
F100 : F 100 turtle draw the right-hand
side of the roof
R90 : R 90
F100 : F 100

The turtle turns 90 degrees


right, ready to draw the
bottom of the house

Each command in the R90 REMEMBER


9 string that is passed to the
“string_artist” function is Commands
extracted, identified, and
F70 F70 Here’s a reminder of the turtle
executed. A picture of a
house is drawn in the turtle commands in this program. Some
graphics window. of these are only one letter long,
while others include a number
R45 R45 telling the turtle how far to travel
or turn. Each time you activate
“string_artist”, it adds to the
drawing, until “N” clears the screen.
F100 F100
N = New drawing
U/D = Pen Up/Down
L90
F100 = Forward 100
B50 = Backward 50
F100 R90 = Right turn 90 deg
The program R90
makes the turtle L45 = Left turn 45 deg
draw a house
146 P L AY I N G W I T H P Y T H O N

DRAWING MACHINE
Finish off the code with a user interface
The drawing machine needs an interface to make it easier to
use. This will let the user enter a string from the keyboard
to tell the machine what to draw.

This code creates a pop-up window where the user The triple quote (‘‘‘) tells Python
10 can input instructions. A “while True” loop lets them that everything until the next
triple quote is part of the same
keep entering new strings.
string, including the line breaks

instructions = '''Enter a program for the turtle:


eg F100-R45-U-F100-L45-D-F100-R90-B50
N = New drawing
U/D = Pen Up/Down
Tells the user what letters
F100 = Forward 100 to use for different turtle
B50 = Backward 50 commands

R90 = Right turn 90 deg


End of the string
L45 = Left turn 45 deg''' This line tells the
program what
screen = getscreen() Gets the data needed to to show in the
create the pop-up window pop-up window
while True:
t_program = screen.textinput("Drawing Machine", instructions)
print(t_program)
if t_program == None or t_program.upper() == "END":
Stops the program
break if the user types
“END” or presses
string_artist(t_program) the “Cancel” button
Passes the string to the
String artist function

This window pops Drawing Machine


11 up over the turtle
Enter a program for the turtle:
window ready for eg F100-R45-U-F100-L45-D-F100-R90-B50
the user to type a N = New drawing
drawing machine U/D = Pen Up/Down
program string. F100 = Forward 100
B50 = Backward 50
R90 = Right turn 90 deg
△ Turtle control
L45 = Left turn 45 deg
Using this program, the turtle is
Type the program string easier to control, and you don’t
here and then click “OK” OK Cancel have to restart the program to
to run the program draw another picture.
D R AW I N G M AC H I N E 147

The drawing machine can be used to create more than


12 just outlines. By lifting up the turtle’s pen while moving to
a new position, it’s possible to fill in details inside a shape.
Run the program and try entering the string below.

N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100-B10-U-R90-F10-D-
F30-R90-F30-R90-F30-R90-F30

Lifts up the turtle’s Puts the pen down


pen so it moves to draw a window
without leaving a line The house now
has a window

Time for something different


Now you know how to add details, you can really have fun
with the drawing machine. Try drawing this owl face using
the string of instructions below.

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


three times to draw the
eyes and nose separately The arrow shows where the
turtle stopped. This means that
the owl’s nose was drawn last

REMEMBER
Achievements
You created the drawing machine program Created the function “turtle_controller” that figures
by achieving several smaller targets: out what turtle command to execute from the letter
and number it’s been given.
Used a flowchart to plan a function by working out Created the function “string_artist” that produced
the decision points and the resulting actions. a turtle drawing from a string of instructions.
Wrote pseudocode to plan out a function before Made an interface that allows the user to tell
writing out the real code. the program what to draw from the keyboard.
148 P L AY I N G W I T H P Y T H O N

Bugs and debugging SEE ALSO

‹ 94–95 Errors
Programmers aren’t perfect, and most programs ‹ 122–123 Loops
in Python
contain errors at first. These errors are known as
“bugs” and tracking them down is called “debugging.”
What next? 176–177 ›

Types of bugs
Three main types of bugs can turn up in programs—syntax,
runtime, and logic errors. Some are quite easy to spot, while
others are more difficult, but there are ways of finding and
fixing them all.
This will cause an error Age cannot be less than 5
The Python keyword as no number can be and greater than 8 at the
is ”for” not “fir” divided by 0 same time, so no free tickets

fir i in range(5): a = 0 if age < 5 and age > 8:


print(i) print(10 / a) print("Free ticket!")

△ Easy to spot △ Harder to spot △ Hardest to spot


A syntax error is a mistake in the Runtime errors appear only Logic errors are mistakes in a program’s
program’s words or symbols, such when the program is running. thinking. Using “<” instead of “>”, for
as misspelled keywords, missing Adding numbers to strings or example, or adding when you should be
brackets, or incorrect indents. dividing by 0 can cause them. subtracting result in these errors.

Find and fix a bug


Syntax errors are easy to spot because IDLE highlights them in red
when you run the program. Finding runtime and logic errors takes
a bit more work.
Problem
1 program
top_num = 5
The highest number in the series
This program aims to total = 0 of numbers being added
add all the numbers for n in range(top_num):
from 1 up to the value
total = total + n This command prints
stored in the variable
print("Sum of numbers 1 to", top_num, "is", total) a sentence to let the
“top_num”. It then user know the result
prints the total.

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 The answer should be


answer as “10”. You need to find out why. “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 for n in range(top_num):
step. Adding a “print“
total = total + n
command here will let
you see what’s happening. print("DEBUG: n=", n, "total=", total) This command
The “input()” command prints the current
input() value of the loop
waits for the “return” or
print("Sum of numbers 1 to", top_num, "is", total) variable and the
“Enter” key to be pressed total so far
before looping.

New output
4 The loop is adding only 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 DEBUG: n= 2 total= 3 This is actually the
from 0 (unless told otherwise), and always sum of the numbers
DEBUG: n= 3 total= 6
stops 1 before the end of the range. from 0 to 4, not 1 to 5
DEBUG: n= 4 total= 10
Sum of numbers 1 to 5 is 10

Fix the
5 faulty line
top_num = 5

The range should total = 0


The new range will
go from 1 up to for n in range(1, top_num + 1): count from 1 and
“top_num + 1”, so that stop at “top_num”
total = total + n (1 less than “top_
the loop adds up the
numbers from 1 to print("DEBUG: n=", n, "total=", total) num + 1”)
”top_num” (5). 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. DEBUG: n= 3 total= 6 total is (1 + 2 + 3)
The bug has now been fixed!
DEBUG: n= 4 total= 10
DEBUG: n= 5 total= 15 The correct answer
Sum of numbers 1 to 5 is 15 is now printed
150 P L AY I N G W I T H P Y T H O N

Algorithms SEE ALSO

‹ 16–17 Think like


a computer
An algorithm is a set of instructions for performing a task.
Some algorithms are more efficient than others and take
Libraries 152–153 ›
less time or effort. Different types of algorithms can be
used for simple tasks such as sorting a list of numbers.

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

5 is sorted into position 1 2 6 5 1 4 3


The value of 5 is between 2 and 6, so
moves to position 1. 6 shifts to position 2

1 is sorted into position 0 2 5 6 1 4 3


1 is less than 2, so moves to
position 0. 2, 5, and 6 shuffle down

4 is sorted into position 2 1 2 5 6 4 3


4 is between 2 and 5,
so moves to position 2.
5 and 6 shuffle down

3 is sorted into position 2 1 2 4 5 6 3

Sorted! 1 2 3 4 5 6
4, 5, and 6 shuffle along to
make room for 3 in position 2
ALGORITHMS 151
Selection sort
“Selection sort” works differently to “insertion sort.” It swaps
pairs of items instead of constantly shifting all of the items.
Each swap moves one number to its final (sorted) position.
Swap the smallest value
with the first value
△ Swapping positions
Switching one thing with another
is usually quick and doesn’t affect
Swaps 1 and 2 2 6 5 1 4 3 anything else in the list.

Swap the smallest value in the unsorted part (2)


with the first value in the unsorted part (6)

Swaps 2 and 6 1 6 5 2 4 3

3 is the smallest value in the


Swaps 3 and 5 1 2 5 6 4 3 unsorted part. Swap it with 5, the
first value in the unsorted part

Swaps 4 and 6 1 2 3 6 4 5 5 isn’t in the right position


yet, but 4 is smaller so it’s
swapped first

Swaps 5 and 6 1 2 3 4 6 5
The largest number is in last
position after the swap, so
no further swapping is required
Sorted! 1 2 3 4 5 6
EXPERT TIPS
Sorting in Python
There are lots of different sorting “a” is a list of
algorithms, each with different unsorted numbers
strengths and weaknesses. Python’s
“sort()” function uses an algorithm This calls
>>> a = [4, 9, 3, 8, 2, 6, 1, 5, 7] the “sort()”
called “Timsort,” named after its function
designer, Tim Peters. It’s based on >>> a.sort()
two sorting algorithms: “Insertion >>> a The numbers
sort” and “Merge sort.” Type in this [1, 2, 3, 4, 5, 6, 7, 8, 9] in list “a” are
code to see how it works. now sorted
152 P L AY I N G W I T H P Y T H O N

Libraries SEE ALSO


Making 154–155
windows

Writing new code takes time, so it’s useful to be able
to reuse bits of other programs. These snippets of
Color and 156–157
coordinates

code can be shared in packages called “libraries.”

◁ Batteries
Standard Library modules included
Python comes with a “Standard Library” that has Python’s motto
lots of useful bits of code ready to use. Stand-alone is “batteries are
included.” This
sections of a library called “modules” can be added means it comes
to Python to make it even more powerful. with lots of ready-
to-use code.
◁ Random
This module can pick
a random number,
or shuffle a list into ▽ Turtle
a random order. This module is used to
draw lines and shapes
on the screen.

△ Time
The Time module gives the current
time and date, and can calculate
dates—for instance, what day will
it be in three days’ time?

▽ Tkinter
Tkinter is used to make buttons,
windows, and other graphics that
help users interact with programs. ▷ Math
Use the Math
module to work
with complex
mathematical
calculations.
△ Socket
The code in this module helps
computers connect to each other
over networks and the internet.
LIBRARIES 153
Importing modules EXPERT TIPS
Before using a module, you have to tell the computer Pygame
to import it so it can be used by your program. This
allows the bits of code it contains to be available to you. Pygame is a
Python library
Importing modules is done using the “import” command.
designed for
Python can import modules in a few different ways. writing video
games. Pygame
◁ “import random” gives you access to sound modules
import random This way of importing and special graphics that can be
requires you to type the used in games. You’ll be able to
module name at the start of use Pygame once you have a good
random.randint(1, 6) the code. It makes it easier understanding of the basics of
random.choice(my_list) to read because you know Python covered in this book.
which module it came from.

The module name comes


before each function Imports all the functions
from the Random module

▷ “from random import *” from random import *


Importing a module like this works well for
small programs. But it can get confusing
with bigger programs because it isn’t clear
randint(1, 6)
which module the function belongs to.
choice(my_list)

This code doesn’t show which


Imports only the module the function came from
“randint” function

from random import randint


◁ “from random import randint”
You can import a single function from the
module. This can be more efficient than
importing the whole module if it’s the
randint(1, 6)
only function you want to use.
Only the “randint”
function is available

Help and documentation Help ◁ Help!


At the top of any IDLE
Not sure how to use a module or what functions About IDLE window, click “Help” and
are available? The Python Library Reference has choose “Python Docs”.
IDLE Help This brings up a window
all the details. Simply click on the library you
with lots of useful
want to learn more about. It’s a good idea to get Python Docs
information.
to know the libraries, modules, and functions
that are available, so you don’t waste time
writing code that already exists.
154 P L AY I N G W I T H P Y T H O N

Making windows SEE ALSO


Color and 156–157
coordinates

Many programs have windows and buttons that can
be used to control them. These make up the “graphical
Making 158–159
shapes

user interface,” or “GUI” (pronounced “gooey”). Changing 160–161 ›
things

Make a simple window


The first step in creating a GUI is to make the window that
will hold everything else inside it. Tkinter (from Python’s
Standard Library) can be used to create a simple one.

Enter the code A Tkinter window appears


1 This code imports Tkinter from the 2 Run the code and a window appears.
library and creates a new window. Tkinter It looks a bit dull for now, but this is only the
must be imported before it can be used. first part of your GUI.
This imports Tkinter
from tkinter import * from the library
Tk
window = Tk()

This creates a
Tkinter window

Add buttons to the window


Make the GUI more interactive by adding buttons. Create two buttons
A different message will be displayed when the 1 Write this code to create a
user clicks each button. simple window with two buttons.
This message appears
when button A is pressed

from tkinter import *


def bAaction(): This message appears
print("Thank you!") when button B is pressed.

def bBaction(): This tells the program


This label will appear
print("Ouch! That hurt!") on button A which function to run
when the button is clicked
window = Tk()
buttonA = Button(window, text="Press me!", command=bAaction)
buttonB = Button(window, text="Don't press!", command=bBaction)
buttonA.pack() This label will
This code tells the computer to
buttonB.pack() put the buttons in the window appear on
button B
MAKING WINDOWS 155
Click the buttons Click the button to Output appears in
2 to print messages
Tk show a message the shell window
When the program is run, a window
with two buttons appears. Click the Press me! Thank you!
buttons and different messages will
appear in the shell. You’ve now made
an interactive GUI that responds to Ouch! That hurt!
Don’t press!
the user’s commands.

Roll the die


Tkinter can be used to build a GUI for a simple
application. The code below creates a program
that simulates rolling a six-sided die.

1 Create a die simulator


This program creates a button that, This imports the
when pressed, tells the function “roll()” to function “randint” from
display a random number between 1 and 6. the random library

from tkinter import *


from random import randint This code clears the text
def roll(): inside the text box and
replaces it with a random
text.delete(0.0, END) number between 1 and 6
text.insert(END, str(randint(1,6)))
This tells the
window = Tk() Creates a text box to display
program which
the random number
text = Text(window, width=1, height=1) function to run when
the button is clicked
buttonA = Button(window, text="Press to roll!", command=roll)
text.pack()
This puts the text box and
buttonA.pack() This label appears
the button in the window
on the button

EXPERT TIPS
2 Press the button to
roll the die
Tk
Clear and simple
Run the program, then click the
button to roll the die and see the When you’re designing a GUI, try
result. This program can be simply 6 not to confuse the user by filling
changed so that it simulates a the screen with too many buttons.
12-sided die, or a coin being tossed. Label each button with a sensible
Press to roll!
name to make the application
A new number appears here easy to understand.
each time the button is clicked
156 P L AY I N G W I T H P Y T H O N

Color and coordinates SEE ALSO

‹154–155 Making
windows
Pictures and graphics on a computer screen are
made up of tiny colored dots called pixels. To
Making 158–159
shapes

create graphics in a program, the computer needs Changing 160–161 ›
to be told exactly what color each pixel should be. things

Selecting colors EXPERT TIPS


It’s important to describe colors in a way that Mixing colors
computers can understand. Tkinter includes a
useful tool to help you do this. Each pixel can give out red, green,
and blue light. By mixing these
colors together, you can make
Launch the color selection tool any color imaginable.
1 Type the following code into the shell This imports all
window to launch the Tkinter tool of the Tkinter Red and Red and blue
for selecting colors. functions green make make purple

>>> from tkinter import *


yellow R
>>> t = Tk()
>>> colorchooser.askcolor()
G B
Use the American
spelling of color Mixing all three
makes white
Select the color you
want by clicking on it

Choose a color
2 The “color chooser” window will
appear. Pick the color you want and
then click the “OK” button.

This window makes it


easy to pick the exact
color you want

Color values
3 When a color is selected, a list
((60.234, 190.742, 52.203), "#3cbe34")

of numbers will appear in the shell


Red Green Blue
window. These numbers are the values Code for the color
value value value
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)
Create a graphics program (50,100)
1 Use this code to create a
This imports the
+y
window and put a canvas inside “randint” and “choice” (250,200)
it. It will then draw random circles functions from the
on the canvas. Random module

from random import *


This imports all of
from tkinter import * the Tkinter functions
size = 500
The variable “size” sets the
window = Tk() dimensions of the canvas
canvas = Canvas(window, width=size, height=size) This creates a canvas
inside a window
canvas.pack() A forever loop makes the
program draw circles endlessly
while True:
col = choice(["pink", "orange", "purple", "yellow"]) This chooses a random
color from the list
x0 = randint(0, size)
This creates a circle of a random size
y0 = randint(0, size) in a random place on the canvas
d = randint(0, size/5)
canvas.create_oval(x0, y0, x0 + d, y0 + d, fill=col)
window.update() This part fills it with the color
that has been chosen ( “col”)
This part of the line draws the circle

Colored canvas
2 Run the code and the
Tk

program will start drawing


circles on the canvas.

The size of each


circle is random

Circles are drawn in


random places
158 P L AY I N G W I T H P Y T H O N

Making shapes SEE ALSO


Changing 160–161
things

As well as adding windows, buttons, and colors to
a graphical user interface (GUI), Tkinter can also be
Reacting 162–163
to events

used to draw shapes.

Creating basic shapes


Rectangles and ovals are useful shapes for drawing all
sorts of things. Once a canvas has been created, the
following functions can be used to draw shapes on it.

>>> from tkinter import * Sets the size


Creates a canvas of the canvas
>>> window = Tk() to draw on.
>>> drawing = Canvas(window, height=500, width=500) Sets the position and
size of the rectangle
>>> drawing.pack() Draws a rectangle. using coordinates
>>> rect1 = drawing.create_rectangle(100, 100, 300, 200) (see below)

>>> square1 = drawing.create_rectangle(30, 30, 80, 80)


>>> oval1 = drawing.create_oval(100, 100, 300, 200)
A square can be made by
>>> circle1 = drawing.create_oval(30, 30, 80, 80) drawing a rectangle with
all sides the same length
Draws a circle Sets the position
and size of the circle

Drawing with coordinates ▽ Coordinates grid


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 (350, 250).
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

This is the name Coordinates for the


of the canvas top left of the rectangle
200

>>> drawing.create_rectangle(50, 50, 250, 350)


300

△ Setting the coordinates Coordinates for (x2=350, y2=250)


The first two numbers give the the bottom right
400

coordinates for the top-left corner of the of the rectangle


rectangle. The second two numbers
500

locate the bottom-right corner.


MAKING SHAPES 159
Adding color to shapes
It’s also possible to create colored shapes.
Creates a solid
Code can be used to set different colors for blue circle with
the outline and the inside (“fill”) of each shape. a red outline

>>> drawing.create_oval(30, 30, 80, 80, outline="red", fill="blue")

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.

Create the alien


1 For each part of the alien, you must define the type of
shape, size, position on the canvas, and color. Each shape
has a unique ID number that can be stored in a variable. Creates the canvas

from tkinter import * Sets “Alien” as the


window = Tk() title of the window

window.title("Alien")
c = Canvas(window, height=300, width=400) Draws a green oval
c.pack() for the body

body = c.create_oval(100, 150, 300, 250, fill="green")


eye = c.create_oval(170, 70, 230, 130, fill="white") Draws a black dot
inside the eye
eyeball = c.create_oval(190, 90, 210, 110, fill="black")
mouth = c.create_oval(150, 220, 250, 240, fill="red")
neck = c.create_line(200, 150, 200, 130) Draws a red oval
hat = c.create_polygon(180, 75, 220, 75, 200, 20, fill="blue") for the mouth

Draws a blue
triangle for
the alien’s hat

Meet the alien


2 Run the code to draw
the alien. It has a green body, The finished alien
a red mouth, and one eye
on a stalk. It’s also wearing
a lovely blue hat.
160 P L AY I N G W I T H P Y T H O N

Changing things SEE ALSO

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

Moving shapes REMEMBER


To make a shape move on the canvas, you need to Meaningful names
tell the computer what to move (the name or ID
you gave the shape) and where to move it. It’s a good idea to use sensible
names to identify the shapes
The eyeball on the canvas. These pages
turns left, then use names like “eyeball” and
back again
“mouth” so the code is easy
to read and understand.
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
Write the code
1 Type this code to create two The function “itemconfig()” 2 Open and close
closed

functions that will make the mouth Type this code into the shell
changes the properties of
seem to open and close. shapes you’ve already drawn window to make the mouth open
and close.
def mouth_open():
>>> mouth_open()
c.itemconfig(mouth, fill="black")
>>> mouth_close()
def mouth_close(): The opened
mouth will Enter these commands
c.itemconfig(mouth, fill="red") be black to make the alien open
The closed mouth and close its mouth
The shape’s ID will be red
CHANGING THINGS 161
Hide and show ◁ Blinking alien
Shapes can be hidden using the “itemconfig()” To make the alien blink,
function. If you hide the eyeball, and then you need to hide the
pupil and make the
show it again a moment later, the alien looks white of the eye green.
as though it is blinking.

Create blinking functions Blink and unblink


1 This code creates two functions 2 Type this code into the shell
so you can make the alien blink. The shape’s ID window to make the alien blink.
Turns the
def blink(): white of the >>> blink()
eye green
c.itemconfig(eye, fill="green") >>> unblink()
c.itemconfig(eyeball, state=HIDDEN) Hides the
pupil The “unblink()”
def unblink(): command makes the
Makes the eye eye appear open again
c.itemconfig(eye, fill="white") white again
c.itemconfig(eyeball, state=NORMAL) Reveals
the pupil

Saying things
Text can also be displayed on the screen to make I am an alien!
the alien talk. You can even make it say different
things in response to user commands.

Adding text
1 This code adds text to the Positions the text
graphic of the alien and creates a on the canvas
function to steal its hat.

words = c.create_text(200, 280, text="I am an alien!") Put what you want


the alien to say in
def steal_hat(): This hides quote marks
the hat.
c.itemconfig(hat, state=HIDDEN)
As soon as the hat
c.itemconfig(words, text="Give my hat back!")
disappears the alien
will ask for it back
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

Reacting to events SEE ALSO

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

Mouse events Keyboard events


<Button-1> <Right> <Up>
Left mouse Right arrow Up arrow Down arrow
button clicked key pressed key pressed key pressed

<Button-3> <Left> <Down>


Right mouse Left arrow
key pressed “A” key Different letters
button clicked pressed can go here

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
Creates a function
called “burp”
window.attributes("-topmost", 1)
def burp(event):
△ Burping alien
mouth_open()
Links the left
Click the left mouse button and
c.itemconfig(words, text="Burp!") mouse click to the alien lets out a burp. This
c.bind_all("<Button-1>", burp) the “burp” is because the “burp” function
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.

Makes the eye


def blink2(event): green (closed)

c.itemconfig(eye, fill="green")
c.itemconfig(eyeball, state=HIDDEN)
def unblink2(event):
Hides the
c.itemconfig(eye, fill="white") eyeball
c.itemconfig(eyeball, state=NORMAL)
c.bind_all("<KeyPress-a>", blink2)
c.bind_all("<KeyPress-z>", unblink2)
Shows the
eyeball a z
△ Make the alien blink
When this code is run, the “A” key
This code links This binds the function will make the eye close, and the
functions to events “unblink2” to the “Z” key “Z” key will make it open again.

Moving with keys


Key presses can also be used to trigger movement.
This code binds the arrow keys to functions that make
the alien’s eyeball move.

This line finds out the


name of the pressed key

def eye_control(event):
The eyeball moves
key = event.keysym up if the up arrow
key is pressed
if key == "Up":
c.move(eyeball, 0, -1)
The eyeball
elif key == "Down": moves left if the
c.move(eyeball, 0, 1) left arrow key
is pressed
elif key == "Left":
c.move(eyeball, -1, 0)
elif key == "Right": Activates the
function
c.move(eyeball, 1, 0) “eye_control” △ Eyeball control
when any key The eyeball moves in the direction
c.bind_all("<Key>", eye_control)
is pressed of the pressed arrow key.
164 P L AY I N G W I T H P Y T H O N

PROJECT 7
Bubble blaster SEE ALSO

‹154–155 Making
windows
This project uses all the skills taught in this chapter
to make a game. It’s a big project, so tackle it in stages
‹ 156–157 Color and
coordinates
and remember to save the program regularly. Try to ‹ 158–159 Making
understand how each part fits together before moving shapes

on to the next stage. By the end you’ll have a game


that you can play and share with friends.

Aim of the game


Before writing any code, think about the overall plan for the
game and how it should work. Here are the main rules that
set out how the game will be played:

The player controls a submarine


The arrow keys move the submarine
Popping bubbles scores points
A timer is set to 30 seconds at the start
Scoring 1,000 points earns extra time
The game ends when the time runs out
BUBBLE BLASTER 165

Create the game window Bubble Blaster

and the submarine IDLE File Edit Shell Debug Window Help

Start by setting the scene. Open a new code


window in IDLE. Type in the code below to
create the window for the game, and the
submarine that the player controls.

Use the Tkinter library to build the graphical


1 user interface (GUI). This code will create the
main window for the game.

from tkinter import * Imports all of the


Tkinter functions
HEIGHT = 500
Sets the size Sets dark blue as
WIDTH = 800
of the window the color of the
Give the game
window = Tk() background (the sea)
a snappy title
window.title("Bubble Blaster")
c = Canvas(window, width=WIDTH, height=HEIGHT, bg="darkblue")
c.pack()

Creates a canvas that


can be drawn on The submarine will
be represented by a
triangle inside a circle

A simple graphic will represent the submarine in this


2 game. This can be made using some of the drawing Draws a red triangle
functions from Tkinter. Type out this code, then run it. for the submarine

Draws a red
ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill="red")
circle outline
ship_id2 = c.create_oval(0, 0, 30, 30, outline="red")
SHIP_R = 15 The radius (size) of the submarine.

MID_X = WIDTH / 2 The variables “MID_X” and


“MID_Y” give the coordinates
MID_Y = HEIGHT / 2 of the middle of the screen
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)

Moves both parts of the submarine Don’t forget to


to the center of the screen save your work
166 P L AY I N G W I T H P Y T H O N

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.

Type this code to create a function called “move_ship”. This


3 function will move the submarine in the correct direction when
a cursor key is pressed. Try running it to see how it works.

The sub will move SHIP_SPD = 10


this far when a
key is pressed def move_ship(event):
if event.keysym == "Up":
Moves the two parts of
c.move(ship_id, 0, -SHIP_SPD)
the sub up when the up
c.move(ship_id2, 0, -SHIP_SPD) arrow key is pressed
These lines are
elif event.keysym == "Down":
activated when the
down arrow key is c.move(ship_id, 0, SHIP_SPD)
pressed, and the
sub moves down c.move(ship_id2, 0, SHIP_SPD)
elif event.keysym == "Left":
c.move(ship_id, -SHIP_SPD, 0) The sub moves left when
the left arrow key is pressed
c.move(ship_id2, -SHIP_SPD, 0)
elif event.keysym == "Right":
Moves the sub right
when the right c.move(ship_id, SHIP_SPD, 0)
arrow key is pressed c.move(ship_id2, SHIP_SPD, 0)
c.bind_all("<Key>", move_ship) y coordinate gets
smaller moving up
Tells Python to run “move_ship”
whenever any key is pressed

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

Get ready for bubbles


Now the submarine can move, start creating the
bubbles for the player to pop. Each bubble will be
a different size and move at a different speed.
Every bubble needs an ID number (so the
4 program can identify each specific bubble),
a size, and a speed.

from random import randint


This creates three
empty lists used to bub_id = list()
store the ID, radius bub_r = list()
(size), and speed of
each bubble bub_speed = list()

Sets the minimum MIN_BUB_R = 10


radius of the bubble MAX_BUB_R = 30
to 10, and the
maximum to 30 MAX_BUB_SPD = 10
GAP = 100
Sets the position
def create_bubble(): of the bubble
x = WIDTH + GAP on the canvas This line of
code creates the
y = randint(0, HEIGHT) bubble shape
r = randint(MIN_BUB_R, MAX_BUB_R)
Picks a random size for
the bubble, between the id1 = c.create_oval(x - r, y - r, x + r, y + r, outline="white")
maximum and minimum
bub_id.append(id1)
values possible
bub_r.append(r)
bub_speed.append(randint(1, MAX_BUB_SPD))

Adds the ID, radius, and


speed of the bubble to
the three lists
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. Goes through each
bubble in the list
This function will go
def move_bubbles():
5 through the list of
bubbles and move for i in range(len(bub_id)):
each one in turn. c.move(bub_id[i], -bub_speed[i], 0)

Moves the bubble


across the screen
according to its speed Imports the functions
you need from the
Time library

This will be the main


from time import sleep, time
6 loop for the game. It
BUB_CHANCE = 10
will be repeated over
Generates a random
and over while the #MAIN GAME LOOP number from 1 to 10
game is running. Try
running it! while True:
if randint(1, BUB_CHANCE) == 1:
If the random number
create_bubble() is 1, the program
move_bubbles() creates a new bubble
Runs the (on average 1 in 10
window.update() “move_bubbles” times—so there aren’t
function. too many bubbles!)
sleep(0.01)
Don’t forget to
save your work Slows the game Updates the window
down so it’s not to redraw bubbles
too fast to play that have moved
(x0, y0)
Now you’re going to create a useful function to find out where a
7 particular bubble is, based on the ID. This code should be added
to the program directly after the code you created in step 5.
(x, y)
def get_coords(id_num):
pos = c.coords(id_num) Figures out the (x1, y1)
x coordinate of the
x = (pos[0] + pos[2])/2 △ Locating bubbles
middle of the bubble
y = (pos[1] + pos[3])/2 The function finds the middle of
Figures out the the bubble by taking the point
return x, y
y coordinate of the halfway between the corners of
middle of the bubble the box around it.
BUBBLE BLASTER 169

How to make bubbles pop


The player will score points when the bubbles are popped, so
the program has to make bubbles disappear from the screen.
These next functions will allow it to do that.

This function deletes


the bubble with ID “i”

This function will be used to remove


def del_bubble(i): Deletes the bubble from
8 a bubble from the game. It does this
del bub_r[i]
the radius and speed lists
by deleting it from all the lists, and
from the canvas. This code should del bub_speed[i]
be added directly after the code
you typed out in step 7. c.delete(bub_id[i])
Deletes the bubble
del bub_id[i] from the canvas

Deletes the bubble


from the ID list

This goes through the


Type this code to bubble list backward
def clean_up_bubs():
9 create a function
for i in range(len(bub_id)-1, -1, -1):
to avoid the “for” loop
that cleans up causing an error when
bubbles that have bubbles are deleted
x, y = get_coords(bub_id[i])
floated off the screen.
if x < -GAP:
This code should go
directly after the del_bubble(i) Finds out where
the bubble is
code from step 8.
If the bubble is off the screen
then it is deleted; otherwise, it
would slow the game down

Now update the main


#MAIN GAME LOOP
10 game loop (from step
while True:
Makes a
new bubble
6) to include the
helpful functions you if randint(1, BUB_CHANCE) == 1:
have just created.
create_bubble()
Run it to make sure
Updates the
you haven’t included move_bubbles() positions of all
any errors. clean_up_bubs() the bubbles

window.update()
Removes bubbles that
are off the screen sleep(0.01)

Redraws the window Don’t forget to


to show the changes save your work
170 P L AY I N G W I T H P Y T H O N

BUBBLE BLASTER
Figuring out the distance between points
In this game, and lots of others, it is useful to know the distance
between two objects. Here’s how to use a well-known mathematical
formula to have the computer work it out.
Loads the “sqrt” function
from the Math library
This function calculates Gets the position
from math import sqrt
11 the distance between two of the first object
objects. Add this bit of def distance(id1, id2): Gets the position of
code directly after the x1, y1 = get_coords(id1) the second object
code you wrote in step 9.
x2, y2 = get_coords(id2)
return sqrt((x2 - x1)**2 + (y2 - y1)**2)

Gives back the distance


between them

Pop the bubbles


The player scores points by popping bubbles. Big bubbles
and fast bubbles are worth more points. The next section of
code figures out when each bubble is popped by using its
radius (the distance from the center to the edge). ▷ Collision sensing
If the distance between
When the submarine and a bubble crash into each other, the the center of the sub and
12 program needs to pop the bubble and update the score. This the center of a bubble is less than their
bit of code should come directly after the code in step 11. radiuses added together, they have collided.

This variable keeps This loop goes through the entire list of bubbles (it
track of points scored goes backward to avoid errors when deleting bubbles)

def collision():
points = 0
Checks for collisions
for bub in range(len(bub_id)-1, -1, -1): between the sub
and any bubbles
if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):
points += (bub_r[bub] + bub_speed[bub])
del_bubble(bub)
return points

Gives back Deletes the bubble Calculates the number of


the number points this bubble is worth
of points and adds it to “points”
BUBBLE BLASTER 171

Now update the main game loop to use the


13 functions you have just created. Remember that
the order is important, so make sure you put
everything in the right place. Then run the code.
Bubbles should burst when they hit the sub.
Check the shell window to see the score.

Sets the score to zero


when the game starts

score = 0
#MAIN GAME LOOP
while True:
if randint(1, BUB_CHANCE) == 1: Creates new bubbles
create_bubble()
move_bubbles()
clean_up_bubs() Adds the bubble
score to the total
score += collision()
print(score)
Shows the score in the shell
window.update() window—it will be displayed
sleep(0.01) properly later

This pauses the action for


a very short time—try
removing this and see
what happens

EXPERT TIPS
Python shortcut Don’t forget to
save your work

The code “score += collision()”


is a shortcut for writing
“score = score + collision()”. It adds
the collision score to the total
score, then updates the total score.
Code like this is common, so a
shortcut is useful. You can also do
the same thing using the “–”
symbol. For example, “score –= 10”
is the same as “score = score – 10”.
172 P L AY I N G W I T H P Y T H O N

BUBBLE BLASTER
Adding a few final touches
The main stages of the game are now working. All that remains
is to add the final parts: displaying the player’s score, and setting
a time limit that counts down until the game ends.

Type in this code after the code you entered in step Creates “TIME” and “SCORE”
14 12. It tells the computer to display the player’s score labels to explain to the player
what the numbers mean
and the time left in the game.

c.create_text(50, 30, text="TIME", fill="white" )


c.create_text(150, 30, text="SCORE", fill="white" )
Sets the scores and
time_text = c.create_text(50, 50, fill="white" ) time remaining
score_text = c.create_text(150, 50, fill="white" )
def show_score(score):
c.itemconfig(score_text, text=str(score))
def show_time(time_left): Displays the score

c.itemconfig(time_text, text=str(time_left))

Displays the
time remaining

Next, set up the time limit and the score required to gain
15 bonus time, and calculate the end time of the game. This
bit of code should come just before the main game loop.

Imports functions
from the Time library
from time import sleep, time
BUB_CHANCE = 10
Starts the game with a
TIME_LIMIT = 30 30-second time limit
BONUS_SCORE = 1000
SCORE
score = 0
Sets when bonus time is
bonus = 0 given (when a player has
scored 1,000 points)
end = time() + TIME_LIMIT
△ Scoreboard
Stores the finish time in Scoreboards are a great visual way to
a variable called “end” show players at a glance how well they
are doing in a game.
BUBBLE BLASTER 173

Update the main Repeats the main


#MAIN GAME LOOP
16 game loop to include game loop until
the new score and while time() < end: the game ends
time functions. if randint(1, BUB_CHANCE) == 1:
create_bubble()
move_bubbles()
Calculates when to
clean_up_bubs() give bonus time
score += collision()
if (int(score / BONUS_SCORE)) > bonus:
bonus += 1 “print(score)” has
been replaced by
end += TIME_LIMIT “show_score(score)”
so that the score
show_score(score)
now appears in the
show_time(int(end - time())) game window
window.update()
sleep(0.01)

Don’t forget to
Displays the
save your work
time remaining

Finally, add a “GAME OVER” graphic. This will be


17 shown when the time runs out. Add this to the Puts graphic in the
middle of the screen
very bottom of your program.

c.create_text(MID_X, MID_Y, \ Sets the font—


text="GAME OVER", fill="white", font=("Helvetica",30)) “Helvetica” is a good
font for big letters
c.create_text(MID_X, MID_Y + 30, \
text="Score: "+ str(score), fill="white")
c.create_text(MID_X, MID_Y + 45, \
Tells you what
text="Bonus time: "+ str(bonus*TIME_LIMIT), fill="white") your score was

Shows how much bonus Sets the text


time was earned color to 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 The player
blaster and it’s now ready to play. Run the scores points for
popping bubbles
program and try it out. If something isn’t with the sub
working, remember the debugging tips—
look back carefully over the code on the
previous pages to make sure everything Bubble Blaster
is typed out correctly. IDLE File Edit Shell Debug Window Help
The timer counts TIME SCORE
Up arrow key down to the end
Left
of the game 13 241
arrow key Down arrow key

Right
arrow key

△ Controls
The submarine is steered using the arrow
keys. The program can be adjusted so it
works with other controls.

EXPERT TIPS
Improving your game
All computer games start as a basic idea. They
are then played, tested, adjusted, and improved.
Think of this as version one of your game. Here
are some suggestions of how you could change
and improve it with new code:

Make the game harder by adjusting the time limit


and the score required for bonus time.
Choose a different color for your submarine.
Create a more detailed submarine graphic.
Have a special type of bubble that increases the
speed of the submarine.
Add a smart bomb that deletes all of the bubbles
when you press the spacebar.
Build a leaderboard to keep track of the
best scores.
BUBBLE BLASTER 175

The bubbles float New bubbles drift


from right to left and in from the right at
disappear off the screen random intervals

The player uses this


submarine to pop as
many bubbles as they
can before time runs out

The bubbles are all


different sizes and move
at different speeds

◁ 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

What next? SEE ALSO

‹ 152–153 Libraries
Now that you’ve tackled the Python projects in this book, Computer 204–205
games

you’re on your way to becoming a great programmer.
Here are some ideas for what to do next in Python,
and how to take your programming skills farther.

Experiment REMEMBER
Play around with the code samples Read lots of code
in this book. Find new ways to remix
them or add new features—and Find interesting programs or
don’t be afraid to break them too! libraries written by other people
and read through the code and
This is your chance to experiment their comments. Try to understand
with Python. Remember that it how the code works, and why it is
is a professional programming built that way. This increases your
language with a lot of power—you knowledge of coding practices.
can do all sorts of things with it. You will also learn useful bits of
information about libraries that
you can use in future programs.
Build your own libraries
Programmers love to reuse code and share their
work. Create your own library of useful functions and
share it. It’s a great feeling to see your code being
used by another programmer. You might build
something as useful as Tkinter or Turtle!
W H AT N E X T ? 177
Make games EXPERT TIPS
with Python Different versions of Python
You could create your own game When you find code elsewhere (in other books or online), it
using Python. The PyGame may be written for a different version of Python. The versions
library, which is available to are similar, but you might need to make small changes.
download from the web, comes Python 2
with lots of functions and tools print "Hello World"
that make it easier to build
games. Start by making simple Python 3
print("Hello World")
games, then progress to more
complex ones.

Score 56
22

Debug your code


Debugging is an important part of programming. Don’t just
give up if something isn’t working. Remember that computers
will only do what you tell them, so look through the code and
figure out why it’s not working. Sometimes looking over it
with another programmer helps you find bugs quicker.
Inside
computers
180 INSIDE COMPUTERS

Inside a computer SEE ALSO


Storing data 192–193
in files

The earliest computers were simple calculators. At a
basic level, computers haven’t changed much since
The internet 194–195 ›
then. They take in data (input), perform calculations,
Mini 214–215
computers

and give out answers (output).

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

▷ Von Neumann architecture


A scientist called John von Neumann first
came up with the standard layout for a
computer in 1945. His plan is still followed The control unit Processor
today, with some improvements. loads and carries
out instructions
from programs
Input Control unit
Language and information
can be input through
the keyboard

Keyboard

Icons and menus can be


Mouse selected using the mouse
INSIDE A COMPUTER 181
Computer hardware Screen The network adapter,
is used for contacting
Hardware is the physical parts of other computers
The motherboard
a computer. Computers contain connects pieces of
Graphics processor
many different bits of hardware hardware together
The battery
working together. As computer supplies power
makers pack more and more Processor
features into smaller machines,
the hardware components have Data storage The chipset controls
to be smaller, generate less heat, communication
and use less power. Inside a laptop between components

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.

The processor is made up of


two parts, one to carry out
instructions and the other
to perform calculations

The arithmetic logic unit


(ALU) performs any calculations
the program needs

Arithmetic logic unit Output


Printers output
data onto paper Speakers turn
2+3=5 data into sounds

5>3=?

Printer

Screens provide
Screen Speaker
visual output
182 INSIDE COMPUTERS

Binary and bases SEE ALSO


Symbols 184–185
and codes

How can computers solve complex calculations when all
they understand is electrical signals? Binary numbers
Logic gates 186–187 ›
are used to translate these signals into numbers.

What is a base number? Each extra digit is worth


10 times the one before
A “base” is the number of values
that can be shown using only one x10 x10 x10
digit. Each extra digit increases
the number of values that can be
shown by a multiple of the base. 1000 100 10 1 The number
3274 is made
▷ Decimal system up of four digits
The decimal system is the most
familiar counting system, and has
a base of 10. It can show 10 values
3 2 7 4
with one digit, 100 values with two
digits, and 1,000 with three digits.
3x1,000 + 2x100 + 7x10 + 4x1 = 3,274
Binary code A wire with

1
a current
At the most basic level, computers understand only
two values: electrical signals that are “on” and “off.”
▷ 1 and 0
Because there are only two values, computers deal with A wire with ON
numbers using a base of two, or “binary.” Each digit is electrical signal
either a 1 or a 0, and each extra digit in the number “on” is a 1. A wire
is worth two times the previous digit.
Each extra digit is
with electrical
signal “off” is a 0. 0
worth twice as much
OFF
x2 x2 x2 x2 x2 x2 x2

128 64 32 16 8 4 2 1
◁ Binary
The range of
values that
can be written
doubles with

1 1 1 1 0 0 0 1
each digit added.

1x128 + 1x64 + 1x32 + 1x16 + 0x8 + 0x4 + 0x2 + 1x1 = 241


BINARY AND BASES 183
Hexadecimal ▽ Understanding nibbles
A “nibble” is made up of four binary
When using numbers in computer programs, a base of 16 digits, which can be represented by
is often used because it’s easy to translate from binary. one hexadecimal digit.
Because there are only 10 symbols for numbers (0–9), the
The number 241
values for 10–16 are represented by the letters A–F. in binary code

1 1 1 1 0 0 0 1
Binary numbers can be

1111 broken down into nibbles


made up of four digits 0001 The number in
hexadecimal

F 1 241=F1
1111 in binary is
15, which is F in
0001 in binary is 1, which
hexadecimal
is 1 in hexadecimal
The number
in decimal
▽ Comparing base systems
REMEMBER
Using this table, you can see that expressing
numbers in hexadecimal gives the most Bits, nibbles, and bytes
information with the fewest digits.
A binary digit is known as a “bit,” and is the
DIFFERENT BASES smallest unit of memory in computing. Bits
Decimal Binary Hexadecimal are combined to make “nibbles” and “bytes.” A
kilobit is 1,024 bits. A megabit is 1,024 kilobits.
0 0 0 0 0 0
1 0 0 0 1 1
2 0 0 1 0 2 Bits: Each bit is a single
binary digit—a 1 or 0.
3 0 0 1 1 3
4 0 1 0 0 4 1
5 0 1 0 1 5
6 0 1 1 0 6 Nibbles: Four bits make up
a nibble—enough for one
7 0 1 1 1 7 hexadecimal digit.
8 1 0 0 0 8
1001
9 1 0 0 1 9
10 1 0 1 0 A
Bytes: Eight bits, or two
11 1 0 1 1 B hexadecimal digits, make up a
12 1 1 0 0 C byte. This gives us a range of
13 1 1 0 1 D values from 0 to 255 (00 to FF).
14 1 1 1 0 E
10110010
15 1 1 1 1 F
184 INSIDE COMPUTERS

Symbols and codes SEE ALSO

‹ 180–181 Inside
a computer
Computers use binary code to translate numbers into
electrical signals. But how would a computer use binary
‹182–183 Binary
and bases
code to store the words and characters on this page?
ASCII
The first computers each stored characters in their own ASCII
unique way. This worked fine until data needed to be 32 SPACE 64 @ 96 `
moved between computers. At this point, a common 33 ! 65 A 97 a
system was chosen, called the American Standard Code 34 “ 66 B 98 b
for Information Interchange (ASCII, pronounced “askey”). 35 # 67 C 99 c
36 $ 68 D 100 d
▷ ASCII table 37 % 69 E 101 e
In ASCII, a decimal number value is 38 & 70 F 102 f
given to each character in the upper- 39 ‘ 71 G 103 g
and lower case alphabets. Numbers are 40 ( 72 H 104 h
also assigned to punctuation and other
41 ) 73 I 105 i
characters, such as a space.
42 * 74 J 106 j
43 + 75 K 107 k
44 , 76 L 108 l
▷ ASCII in binary
Because each character has a R = 82 = 1010010 45 - 77 M 109 m
number, that number then needs 46 . 78 N 110 n
to be converted to binary to be
stored in a computer. r = 114 = 1110010 47
48
/
0
79
80
O
P
111
112
o
p
49 1 81 Q 113 q
50 2 82 R 114 r
▽ ASCII in Python This command prints 51 3 83 S 115 s
You can convert between the character, the ASCII 52 4 84 T 116 t
ASCII and binary code in most value, and the binary
value for each letter in 53 5 85 U 117 u
languages, including Python.
the name “Sam” 54 6 86 V 118 v
55 7 87 W 119 w
>>> name = "Sam" 56 8 88 X 120 x
>>> for c in name: 57 9 89 Y 121 y
print(c, ord(c), bin(ord(c))) 58 : 90 Z 122 z
Here are the 59 ; 91 [ 123 {
results. The 60 < 92 \ 124 |
S 83 0b1010011 beginning of
each binary 61 = 93 ] 125 }
a 97 0b1100001
number is 62 > 94 ^ 126 ~
m 109 0b1101101 marked “0b” 63 ? 95 _ 127 DELETE
SYMBOLS AND CODES 185
Unicode
As computers across the world began to share data, the
limits of ASCII began to show. Thousands of characters
used in hundreds of languages had to be represented,
so a universal standard called Unicode was agreed on.

Unicode has over ▷ International code


110,000 characters!
Unicode represents all the
languages of the world. For
example, the Arabic characters are
represented in the range 0600–06FF.

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

0974 004D 2702 A147

REMEMBER
▽ Unicode in Python
Hexadecimals Unicode can be used to display special characters
in Python. Simply type a string containing a Unicode
Hexadecimal numbers have a base of 16.
character code.
Ordinary decimal numbers are used for 0 to 9,
and the values 10–15 are represented by the Putting “\u” before the
hexadecimal code tells the
letters A to F. Each hexadecimal number has an computer this is Unicode
equivalent binary value.
The Unicode value The same value >>> "Zo\u00EB"
of ë as hexadecimal as binary
"Zoë"

ë = 00EB = 11100111 The code is translated


into the character “ë”
186 INSIDE COMPUTERS

Logic gates SEE ALSO

‹ 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

△ Inputs 1 and 1 = output 1 △ Inputs 1 and 0 = output 0 △ Inputs 0 and 0 = output 0


Both input signals are “on,” If one input is “on” but the An AND gate produces
so the AND gate produces other is “off,” the output an “off” output signal if both
an “on” output signal. signal is “off.” input signals are “off.”

REAL WORLD
NOT gate
These gates “flip” any input
George Boole (1815–64)
to its opposite. “On” input George Boole was an English
becomes “off” output, and mathematician whose work made
“off” input turns to “on” logic gates possible. He worked
output. NOT gates are also out a system to solve logic
known as “inverters.” 1 0 problems. This kind of math,
which deals in values that can
only be true or false (positive or
△ Input 1 = output 0
negative), is known as “Boolean
logic” in his honor.
The NOT gate flips an “on” input to
an “off” output, and vice versa.
L O G I C G AT E S 187
OR gate
An OR gate produces an “on” output when either
one of the inputs is “on,” or when both are “on.”

1 1 0
1 1 0
1 0 0

△ Inputs 1 and 1 = output 1 △ Inputs 1 and 0 = output 1 △ Inputs 0 and 0 = output 0


Two “on” inputs produce One “on” and one “off” input still Only two “off” inputs produce an
an “on” output. produce an “on” output. “off” output from an OR gate.

EXCLUSIVE OR gate
This type of gate only gives 1 1
an “on” output when one
input is “on” and the other is
“off.” Two “on” or two “off”
0 1
inputs will produce an “off”
output. Gates like this are 1 0
also known as “XOR” gates.
△ Inputs 1 and 1 = output 0 △ Inputs 1 and 0 = output 1
Two “on” inputs produce The output is “on” only when
an “off” output. the inputs are different.

EXPERT TIPS
Building computer circuits
By combining these four basic with two NOT gates in a loop,
logic gates, you can create circuits you can create a circuit that
to perform a whole range of will store a bit of data (a single
advanced functions. For example, 1 or 0). Even the most powerful
by linking an AND gate to an computers are based on
XOR gate, you create a circuit that billions of tiny logic circuits.
can add two binary digits (bits)
Computer chips contain
together. By linking two OR gates many logic circuits
188 INSIDE COMPUTERS

Processors and memory SEE ALSO

‹ 180–181 Inside
a computer
Inside a computer are many types of electronic chips.
Most importantly, the processor chip runs programs
‹186–187 Logic
gates
and memory chips store data for instant access.

The processor
Processors are a collection of very small and complex circuits, printed on
a glasslike material called silicon. Small switches called transistors are
combined to form simple logic gates, which are further combined to form
complex circuits. These circuits run all the programs on your computer.

◁ Circuits in
a processor
The circuits are kept
synchronized by a
clock pulse, just like
an orchestra is kept in
time by a conductor.

Machine code
Save to
Processors understand only a set of memory
program instructions called “machine
code.” These simple instructions for
operations like adding, subtracting,
and storing data are combined to
create complex programs. Call another
piece of code

▷ Understanding machine code Compare


two values
Machine code is just numbers, so coders
use programming languages like Python
that get converted into machine code.
PROCESSORS AND MEMORY 189
Memory LINGO
Like processors, memory chips are printed on silicon. A few RAM
logic gates are combined to create a “latch circuit.” Each
latch stores one bit (the smallest unit of data with a binary Memory is often referred to as
RAM (“Random Access Memory”),
value of either 1 or 0), and many latches are combined to
meaning any part of it can be
create megabytes and gigabytes of storage. accessed directly. Early types
of storage could only access data
in order from start to end, which
Memory is made up was much slower.
of repeated identical
blocks of circuit

Every item of data has a


number (called an “address”)
so it can be found quickly

◁ Programs and data


Each block of memory can Programs constantly read,
store millions or billions of write, and update the data
bits of data stored in the memory.

REMEMBER
Processing information
The processor and memory, when
combined with input and output MEMORY
devices, give you everything you Contains the
need for a computer. In a game position of the A game program
character running
program, for example, the user
inputs position data by clicking The character
the mouse, the processor does the Mouse click jumps on screen
calculations, reads and writes
memory, and then produces output
in the form of making the character
INPUT PROCESSOR OUTPUT
jump on the screen.
190 INSIDE COMPUTERS

Essential programs SEE ALSO

‹ 180–181 Inside
a computer
There are a few programs that every computer
needs in order to work. Some of the most important
‹182–183 Binary
and bases
programs are operating systems, compilers, ‹188–189 Processors
and interpreters. and memory

Operating system
The operating system (OS) is the
This program has run
manager of the computer’s and is now waiting Each program has its
resources. It controls which for its next slice of own space in the
programs are allowed to run, how processor time computer’s memory

long they run for, and which parts


of the computer they use while
running. The OS also provides
interfaces, such as file browsers,
to let a user interact with the
computer. Common operating
systems include Microsoft
Windows and macOS. Program
Memory
1

off
Programs run in turn

The operating system is


like an octopus, with
tentacles connecting to
all parts of the computer
Program Memory
2
The operating system
manages the
processor’s time
on

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

Python, are known as “high- △ Compiler


level languages.” Computer Compilers produce translated output data
processors don’t understand machine code that can be saved
these languages, so compilers and run later. input data
and interpreters are used to Interpreter
translate them into a low- ▷ Interpreter input
level language (known as Interpreters translate the Interpreter
Program
“machine code”) that a code and execute the runs program
computer does understand. program at the same time.

output data

Links to monitor

Links to keyboard

Links to speaker

Links to mouse

Links to printer

Links to network

The OS acts as a bridge


Links to storage between the programs
you want to run and the
computer’s hardware
192 INSIDE COMPUTERS

Storing data in files SEE ALSO

‹182–183 Binary
and bases
A computer’s memory doesn’t just store numbers and
characters. Many more types of data can be stored,
‹188–189 Processors
and memory
including music, pictures, and videos. But how is this ‹190–191 Essential
data stored? And how can it be found again? programs

How is data stored? The computer’s file


system is similar to a
When data is saved to be used later, it is put into a paper filing system
file. This file can be given a name that will make it easy
to find again. Files can be stored on a hard-drive,
memory stick, or even online—so data is safe even
when a computer is switched off.

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

What type of file


Kilobytes (KB) it is, typically in
three characters file type
1 KB = 1,024 B extension
mp3
The program
Megabytes (MB) that can handle
the file’s data
1 MB = 1,024 KB = 1,048,576 B opens with Music Player

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.

The “root” of the


directory tree, where
you start looking for files

This “path”
This “path”
contains Sara’s
contains Jack’s
user data
user data

Jack’s Sara’s
folder folder

Mpegs are a type


of video file

Music Photos

story.txt film.mpg

PNGs and JPEGs


Text file are two types
of image file
Music files can
have different
file extensions

groove.mp3 funk.wav sunnyday.png island.jpg


194 INSIDE COMPUTERS

The internet SEE ALSO

‹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

Packets hop from


router to router
around the globe

File is broken down EXPERT TIPS


into small chunks of
data called packets Internet protocol
A protocol is a list of rules.
to ... “Internet Protocols” are rules for
10.150.93 ◁ Address information how big packets can be and how
.2 2 Every packet of data they are structured. All internet
from ... is labeled with the devices must follow these rules
62.769.20 destination and sender’s IP if they want to be able to
.5 7 addresses. Domain names communicate with each other.
like “dk.com” are translated
into IP addresses.
THE INTERNET 195
Moving data
Before packets can be sent
between devices, they have to
be translated into binary signals
(ones and zeroes) that can travel
over great distances. Every device
△ Electrical signals △ Light △ Radio waves
on the internet has a “network
Copper wires carry Special glass fibres, Different types
adapter” to perform this task. ones and zeroes as called fibre optic of radio waves can
Different devices send data in electrical signals of cables, transmit data carry ones and zeroes
different forms. different strengths. as pulses of light. without using wires.

Ports ▽ Port numbers


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
programs have ports specially within a
reserved for them. For example, 1 2 3 4 device is like
web browsers always receive an 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

The combination of an IP address


12

and a port is known as a “socket.”


Sockets let programs send data
directly to each other across the 13 14 15 16
internet, which is
useful for things
such as playing
online games. 17 18 19 20
Programming in
the real world
198 PROGRAMMING IN THE REAL WORLD

Computer languages SEE ALSO


Computer 204–205
games

Thousands of different programming languages have
been created. Which one you should use depends on a
Making 206–207
apps

number of factors, such as the type of program being
written and which kind of computer it will run on.
#include <stdio.h>
main()
Popular programming languages {
printf(“Hello World!”);
Some languages have emerged as the most popular for }
creating certain types of program on certain types of
computer. Here is how to run a simple “Hello World!”
program in a few popular programming languages.
△C
One of the most popular
languages of all time, C is often
#include <iostream> used for programming hardware.
int main()
{
std::cout << “Hello World!” << std::endl; #import <stdio.h>
} int main(void)
{
printf(“Hello World!”);
}

△ C++
alert(‘Hello World!’);
Based on C, but with extra
features. Used in programs
that need to be fast, such
as console games.
△ Objective-C
Based on C, with some extra △ JavaScript
features. It has become popular Used to create
because of its use on Apple’s programs that run on
class HelloWorldApp { Mac and iOS devices. web browsers, such
public static void main(String[] args) {
as simple games and
System.out.println(“Hello World!”);
} email websites.
} <?php
echo “Hello World!”;
?>

△ Java ◁ PHP
A very versatile language that Mostly used for creating
can run on most computers. interactive websites, PHP
It’s often used for coding on runs on the web servers
the Android operating system. that host websites.
COMPUTER LANGUAGES 199
Languages from the past REAL WORLD
Many languages that were famous twenty or thirty years Millennium bug
ago have fallen in popularity, despite still being used in
some very important systems. These languages are often Many programs in older languages
like COBOL used two digits to
seen as difficult to code by modern standards.
represent a year (such as 99 for
1999). The “millennium bug” was
BASIC
Designed in 1964 at Dartmouth College, in the predicted to cause problems in
US, BASIC was very popular when home
2000 when these dates rolled over
computers first became available.
into the new millennium as 00.

Computers all over

Fortran
Designed in 1954 at IBM, a technology firm, Fortran the world had to be
is mainly used for calculations on large computers. updated to prevent
It is still being used in weather forecasting. the millennium bug

COBOL
Designed in 1959 by a committee of experts,
COBOL is still being used in many business and
banking programs.

Weird languages (‘&%:9]!~}|z2Vxwv-,POqponl$Hjig%eB@@>a=<M:9[p6tsl1TS/


Among the thousands of languages are QlOj)L(I&%$””Z~AA@UZ=RvttT`R5P3m0LEDh,T*?(b&`$#87[}{W
a few that have been created for very
△ Malbolge
specific and strange purposes.
The Malbolge language was designed to be impossible to
program. The first working code did not emerge until two
years after its release, and was written by another program.

△ 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

Coding stars SEE ALSO

‹ 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

Dates: 1815–52 Famous for:


Mathemati
Alan Turin cian
g is known
Lovelace is as the
Famous for: Ada father of c
omputer sc
to be the first He’s also fa ience.
considered mo
computer pr og ra m mer. ground-bre us for his
ak
In 1843, she pu
blished the cracking se ing work
cret
r Charles
first program fo German co
des during
ytical World War
Babbage’s Anal II for
ed early
Engine (a propos the British
.
e al so
computer). Sh
et ho ds for
suggested m
g ch ar acters
representin
as numbe rs .
Bil l Ga tes an d Pa ul All en
Gra ce Hop per Nationality: American

Nationalit y: American 3–present


Dates: Gates 1955–present, Allen 195

Dates: 1906–92 Famous for: Bill


Gates and Paul
Famous for: Grace Hopper created Allen founded
the first programming language Microsoft together
compiler (which transforms human in the 1970s. They
readable programs into machine invented some of
code). As well as being a the most popular
computer scientist programs ever, such as
she was a Rear Microsoft Windows
Admiral in the and Office.
US Navy!
CO D I N G S TA R S 201

Gu np ei Yo ko i an d Sh ig er u M iy am Ti m B e rn e rs -L e e
ot o
Nationalit y: Japanese Nationalit y: British

nt
Dates: Yokoi 1941–97, Miy
amoto 1952–present Dates: 1955–prese

working at
Famous for: Yokoi and Famous for: While
s sc ientific
Miyamoto worked for CERN (a famou
er in Switzerland),
Nintendo, the gaming research cent
vented
company. Yokoi Tim Berners-Lee in
invented the Game wi de we b,
the world
Boy, while Miyamoto ad e it fre e fo r
and m
made successful games ever yo ne . He wa s
n
such as Super Mario. knighted by Quee
04 .
Elizabeth II in 20

S e r g e i B r in Ma rk Zu ck erb erg
L ar r y Page and
Nationality: American
merican
Nationalit y: A
Dates: 1984–present
73–present
Dates: Both 19

1996, Famous for: Zuckerberg


Famous for: In launched Facebook from his
B ri n began
Page and college room in 2004.
w h at would
work on Facebook has since become
Google
become the a billion-dollar company, and
e.
search engin made Zuckerberg one of the
r ef fe ct iv e
Thei wealthiest people alive.
ch m et h o d
sear
revolutioniz ed
the internet.

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

Busy programs SEE ALSO

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

Compressing files REAL WORLD


Almost every type of file that is sent over the internet Music files
is compressed (squeezed) in some way. When a file is
compressed, data that isn’t needed is identified and Without music compression
programs, you could only fit a
thrown away, leaving only the useful information.
few songs on your music player.
By compressing audio files, the
average smartphone can now
hold thousands of songs.
◁ Squeezing data
Compressing a file
is like squeezing a
jack-in-the-box to
make it fit into a
smaller space.

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.

Supercomputers REAL WORLD


Supercomputers—used by high-tech organizations such Weather forecast
as NASA—combine the power of thousands of computer
processors that share data and communicate quickly. The Weather patterns are very
result is a computer that can perform millions of unpredictable. Supercomputers
crunch the huge amounts of data
calculations per second. needed to accurately predict what
3 Each processor works on will happen. Each processor in the
one of the smaller problems supercomputer calculates the
2 Computer
breaks problem 4 Each sub-problem is weather for a small part of the map.
into smaller, solved separately All the results are then combined
sub-problems to produce the whole forecast.
5 Computer
puts results
back together

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

Computer games SEE ALSO

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

Who makes computer games?


Even simple games on your mobile phone might be made by large
teams of people. For a game to be popular and successful, attention
to detail needs to be given to every area during its development,
which involves many people with lots of different skills.

△ Graphic designer
All of the levels and
◁ Level designer characters need to
The architects of the game’s look good. The graphic
virtual world, level designers designers define the
△ Coder create settings and levels structure and appearance
Programmers write the that are fun to play. of everything in the game.
code that will make the
game work, but they can
do this only with input
from the rest of the team. LINGO

▷ Tester Consoles
Playing games all
day may seem like a A console is a special type of
great job, but testers computer that is well suited to
often play the same running games. Consoles, such as
level over and over the PS4 and Xbox One, often have
again to check for bugs. advanced graphics and sound
processors capable of running
many things at once, making
△ Scriptwriter more realistic games possible.
Modern games have
interesting plots just like
great books and films. ◁ Sound designer
Scriptwriters develop Just like a good movie,
all the characters and a great game needs
stories for the game. to have quality music
and sound effects to
set the mood.
COMPUTER GAMES 205
Game ingredients
The most common ingredients in games are often combined
into a “game engine.” Engines provide an easy-to-use base so
that new games can be developed quickly.

▷ Story and game logic


All games must have a good
story and some sort of goal
to aim for, such as saving the
princess. Well-designed game
logic keeps players interested.

◁ 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

Making apps SEE ALSO

‹190–191 Essential
programs
Mobile phones have opened up a world of possibilities
for coders. With a computer in everyone’s pocket, mobile
‹ 198–199 Computer
languages
apps can use new inputs, such as location-finding and ‹204–205 Computer
motion-sensing, to give users a better experience. games

What is an app?
“App” (short for “application”) is a word that describes
◁ Social network
programs that run on mobile devices, including
Social apps can allow
smartphones, tablets, and even wearable technology people to connect with
such as watches. There are many different categories friends, whether they are
of apps that do different things. nearby or far away, to
share thoughts, pictures,
◁ Games music, and videos.
All sorts of games are available on mobile
devices, from simple puzzle games to
fast-paced action adventures.

△ Travel
Travel apps use your location
combined with other users’ reviews
to provide recommendations for
restaurants, hotels, and activities.

△ Weather
Mobile apps use your location to
provide accurate weather forecasts,
and also allow you to check the
weather around the world.

◁ Sport △ Education
People use apps to track their fitness Educational apps are great for
when running or cycling, and can also learning. Young children can learn
keep up to date on the latest sports to count and spell, and older
scores while on the go. people can learn a new language.
MAKING APPS 207
How to build an app
There are many questions to answer before
building an app. What will it do? What devices will
it run on? How will the user interact with it? Once
these questions are answered, building an app
is a step-by-step process.

Mac Have an idea


1 Any idea for a new app must be well suited to
mobile devices. It might be a completely new idea,
Android or it could just be an improvement on an already
existing idea to make a better version.
Windows
Which operating system?
2 Will the app target a certain type of
Learn to make apps
mobile device? Coders can often use tools that
let them write their application once and then
3 Whichever platform the app will run on,
adapt it for different operating systems. a coder needs to learn the language and other
skills needed to build a good app. Online
tutorials and local coding clubs can help.

Create the program


4 Good apps take time to make. A basic Test it
version might be working in weeks, but for an 5 Users will quickly get rid of an app if it contains
app to be really successful, it will need to be bugs. Putting in tests as part of the code, and getting
developed for a few months before its release. friends and family to try out the app can help clean
up any errors before the app is released.
208 PROGRAMMING IN THE REAL WORLD

Programming SEE ALSO

‹ 198–199 Computer

for the internet


languages
Using 210–211
JavaScript

Websites are built using coding languages that work
just like Python. One of the most important of these
is JavaScript, which makes websites interactive.

How a web page works


Most web pages are built using several ◁ CSS
different languages. An email website, for The language CSS
(Cascading Style
instance, is made with CSS, HTML, and
JavaScript. The JavaScript code makes the
CSS Sheets) controls the
colors, fonts, and
site respond instantly to mouse clicks layout of the page.
without having to reload the page.

INBOX CONTACTS CALENDAR

Compose ▼ Delete + Move

Inbox ▢ Sam Funny cat video


Drafts ▢ Lizzie Presents for Ben
Sent ▢ Fiona Lunch?
Spam ▢ Shaila No thanks
Trash ▢ Paula Come to my party?
▢ Dan Re: Barnyard dance
▢ Ben Re: Amazing picture
JavaScript
▢ Sarah Hockey match
▢ Vicky Re: New York
▢ Ella Book review
▢ Phil Ben’s presents

HTM L ◁ HTML
HTML (HyperText Markup
▷ JavaScript
JavaScript controls how the
Language) builds the basic page changes when you use
structure of the page, with it. Click on an email, for
different sections that instance, and JavaScript
contain text or images. makes a message open up.
PROGRAMMING FOR THE INTERNET 209
HTML <html> Blocks of text are surrounded by “tags,”
a very common feature in HTML code.
When you open a website, your <head> This tag gives the window a title
internet browser downloads an <title>The Hello World Window</title>
HTML file and runs the code to turn </head>
it into a web page. To see how it <body>
works, type the code here into an
<h1>Hello World in HTML</h1>
IDLE code window (see pp.92–93)
<p>Hello World!</p>
and save it as a file with the ending The “<p>” and “</p>”
“.html”. Double click the file and it </body> tags surround
ordinary paragraphs
will launch a browser window </html>
saying “Hello World!” This tag shows where
the HTML code ends

Trying JavaScript EXPERT TIPS


It’s easy to experiment with JavaScript Games in JavaScript
because all modern web browsers can
understand it. JavaScript code is usually placed JavaScript is so good at
creating interactive features
within HTML code, so the example below uses
that it can be used to make
two coding languages at once. The JavaScript games—from simple
section is surrounded by “<script>” tags. puzzles to fast-paced racing
games. These will work in
Write some JavaScript any modern web browser,
1 Open a new IDLE code window and type out so there’s no need to install
the code below. Check the code very carefully. If the game first. JavaScript
there are any errors, you’ll just see a blank page. is also used to create web
apps such as webmail or
<script> The “<script>” tag interactive calendars.
introduces JavaScript code
alert("Hello World!");
</script>

The “alert” command will


make an alert box pop up

Save your file Pop-up appears


2 Save the file and enter a filename such as “test.html” 3 The browser will open and an interactive alert box
so the code is saved as an HTML file and not a Python file. will pop up with the greeting “Hello World!” Click “OK” to
Then double click the file to test it. dismiss the box.
JavaScript
creates

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

Using JavaScript SEE ALSO

‹ 162–163 Reacting
to events
JavaScript is great for creating mini programs that run
inside HTML, bringing websites to life and allowing users
‹ 122–123 Loops
in Python
to interact with them. Although it works like Python, ‹ 208–209 Programming
JavaScript code is more concise and trickier to learn. for the internet

Getting input
As with Python, you can use JavaScript to ask the user
for information. JavaScript can do this with a pop-up This line creates
a pop-up box and
box. The following program prompts the user to stores the text the
enter their name and responds with a greeting. user types into it
The text in quotes
appears in the box
Use a prompt
1 This short script
<script>

stores the user’s name in a var name = prompt("Please enter your name");
variable. Type the code into var greeting = "Hello " + name + "!";
the IDLE code window and
document.write(greeting);
remember to save it with a JavaScript lines
“.html” filename. </script>
always end with
a semicolon
The “</script>” tag shows This line displays
where the JavaScript ends the greeting
EXPERT TIPS

Question appears Type carefully


2 Double-click the HTML file to launch When working with JavaScript, be
a browser window. Enter your name in the
careful to check that you’ve typed
box and click “OK” to see the greeting.
out the code correctly. If there’s an
error, the browser will simply
JavaScript A prompt box ignore the whole block of
always has “OK” JavaScript and
Please enter your name and “Cancel”
buttons will create a
Charlie blank window,
without any error
The greeting message saying
OK Cancel appears in what went wrong.
the browser
window If that happens,
check the code
< > again carefully.
Hello Charlie!
U S I N G J AVA S C R I P T 211
Events 1 Type the code
In this example, an event (clicking a button) triggers a
An event is any action simple function (a tongue-twister appears). Type the code in
that a program can an IDLE code window and save the file with a “.html” ending.
detect, such as a mouse
click or a keystroke. The <button onclick="tonguetwist()">Say this!</button>
HTML code
section of code that <script> Name of the function links the
reacts to an event is function tonguetwist() function to
called an “event handler.” a button
{
Event handlers are used a
document.write("She sells seashells");
lot in JavaScript and can
}
trigger many different JavaScript
</script> code defines
functions, making web the function
pages fun and interactive.
Curly brackets surround a block of code—they
work in a similar way to indents in Python
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
1 Like Python, JavaScript uses “for” to set up a loop. The repeated
it. The loop keeps repeating as long as “x”
is less than 6 (“x<6” in the code). To
lines of code are enclosed in curly brackets. This loop creates a simple increase the number of repeats, use a
counter that increases by one each time it repeats. higher number after the “<” symbol.

The “<script>” tag introduces


the JavaScript code < >
<script> This line creates a counter Loop count: 0 The loop
called “x” with a starting value repeats
for (var x=0; x<6; x++) Loop count: 1
of 0, rising by 1 in each repeat six times
{ Loop count: 2
document.write("Loop count: "+x+"<br>"); Loop count: 3
} This line tells the computer Loop count: 4
to write the text “Loop count:”
</script> followed by counter number
Loop count: 5
212 PROGRAMMING IN THE REAL WORLD

Bad programs SEE ALSO

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

Good software to the rescue LINGO


Thankfully, people aren’t defenseless in the fight against Hackers
malware. Anti-malware software has become big
business, with many providers competing to provide Coders that study and write
the best protection. Two well-known examples are malware are known as “hackers.”
Those who write malware to
firewalls and antivirus programs. commit crimes are known as
“black-hat” hackers, and those
who write programs to try to
protect against malware are
known as “white-hat” hackers.

△ Antivirus programs △ Firewalls


Antivirus software tries to Firewalls aim to prevent malware
detect malware. It identifies bad and dangerous network traffic
programs by scanning files and from reaching your computer.
comparing their contents with They scan all incoming data White-hat hacker Black-hat hacker
a database of suspicious code. from the internet.
214 PROGRAMMING IN THE REAL WORLD

Mini computers SEE ALSO

‹ 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

Input and output pins


for sensing and control
(good for robots)

Network connection
Removable memory to access the internet
card stores operating
systems, programs,
and data HDMI video output—to
connect to modern TVs
Power connector

Arduino Many input and output


pins make the Arduino Microcontroller—a
The Arduino is cheaper than very adaptable single-chip computer
the Pi, but less powerful. It
is often used as a low-cost Reset button
and simple way to build
custom electronic or
robotic machines. Sockets for
connecting the
Arduino to other
USB connector used to electronics
load programs on to the
Arduino from a PC Power connector
MINI COMPUTERS 215
Using mini computers
There are endless useful things a mini computer can do because of
its many connection options. Here are just a few suggestions.

△ Computer △ Audio output △ Mobile phones △ Gadgets


Connect a keyboard, mouse, Connect a set of speakers Connect the computer Connect LED lights and
and monitor for a fully and then send music to to the internet using a other simple electronics to
working desktop computer. them over the network. mobile phone. make robots or gadgets.

△ Television △ Camera △ USB △ SD card


Connect a TV and use it as a Connect a basic camera Connect a USB hard drive Change the programs on
media center to show all of to your mini computer to and share your files over your mini computer just
your movies and pictures. create your own webcam. your network. by swapping SD cards.

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:

Weather balloons that record


weather conditions in the atmosphere.
Mini vehicles that can sense
obstacles using sonar like a bat.
Robotic arms that pick up and
move different objects.
216 PROGRAMMING IN THE REAL WORLD

Become a master SEE ALSO

‹ 176–177 What next?


programmer ‹ 214–215 Mini
computers

The secret to becoming a master programmer is to


have fun. As long as you’re enjoying yourself, there’s
no limit to how skilled you can become at coding,
whether as a hobby or a lifelong career.

Ways to become a better programmer


Like skiing, learning the piano, or playing tennis, coding is a
skill that you’ll get better and better at over time. It can take △ Code a lot
years to become a true expert, but if you’re having fun on People say practice makes
perfect—and it’s true. The
the way, it will feel like an effortless journey. Here are a few more code you write, the
tips to help you become a master programmer. better you’ll get. Keep going
and you’ll soon be an expert.

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

▷ Train your brain


Your brain is like a muscle—
▷ Show a friend if you exercise it, it will get
Teach someone else to stronger. Do things that
code and you’ll learn a lot help you think like a
yourself. Explaining how programmer. Solve logic
coding works is a great puzzles and brainteasers,
way of making sure you take up Sudoku, and work
understand it thoroughly. on your math.
BECOME A MASTER PROGRAMMER 217
▷ Test your code
Test your code by entering crazy
values to see what happens. See
how well it stands up to errors.
Scala Pascal SQL
Try rewriting it to improve it or
try rewriting someone else’s— Ruby on rails C++
you’ll learn all their secret tricks.

◁ Build a robot army


You can connect your computer
to all sorts of programmable
devices, from flashing LED △ Learn new languages
lights to robots. It’s fun and
Become multilingual. Every new programming
you’ll learn lots as you figure
language you learn will teach you more about the
out how to conquer the world.
ones you already know (or thought you knew). You
can download free versions of most languages.

▷ Pull a computer to bits


Take an old computer apart ▷ Win a prize
to see how it works (ask When your skills develop,
permission first!). There why not enter an online
aren’t many components, coding contest? There are lots
so it won’t take long to to choose from at all different
figure out what all the bits levels. The toughest are
are. Best of all, build your worldwide competitions like
own computer and then Google’s Code Jam, but there
run your code on it. are easier challenges too.

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

integer memory programming language statement


Any number that does not A computer chip inside a A language that is used The smallest complete
contain a decimal point computer that stores data. to give instructions to instruction a programming
and is not written as a a computer. language can be broken
fraction (a whole number). module down into.
A section of code that random
interface performs a single part A function in a string
The means by which of an overall program. computer program that A series of characters.
the user interacts with allows unpredictable Strings can contain
software or hardware. operator outcomes. Useful when numbers, letters, or
A symbol that performs creating games. symbols, such as a colon.
IP address a specific function: for
A series of numbers that example, “+” (addition) run syntax
makes up a computer’s or “-” (subtraction). The command to make The rules that determine
individual address when a program start. how a program must be
it is connected to OS structured in order for it
the internet. A computer’s operating server to work properly.
system (OS) provides the A computer that stores files
library basis for other programs accessible via a network. trojan
A collection of functions to run, and connects A piece of malware that
that can be reused in them to hardware. single-step pretends to be another
other projects. A way of making a piece of software to
output computer program run trick the user.
loop Data that is produced by one step at a time, to
Part of a program that a computer program and check that each step is tuple
repeats itself (to prevent viewed by the user. working properly. A list of items separated by
the need for the same commas and surrounded
piece of code to be typed port socket by brackets.
out multiple times). A series of numbers The combination of an
used by a computer as IP address and a port, Unicode
machine code the “address” for a which lets programs send A universal code used by
The basic language specific program. data directly to each other computers to represent
understood by computers. over the internet. thousands of symbols
Programming languages processor and text characters.
must be translated into A type of electronic chip software
machine code before the inside a computer that The programs that run on variable
processor can read them. runs programs. a computer and control A named place where you
how it works. can store information
malware program that can be changed.
Software that is designed A set of instructions that a sprite
to harm or disrupt a computer follows in order A movable object. virus
computer. Malware is short to complete a task. A type of malware that
for “malicious software”. works by multiplying
itself to spread between
computers.
220 REFERENCE

Index
Page numbers in bold refer bits 183, 189, 218 in strings 114 comments, adding 143
to main entries. black-hat hackers 213 Unicode 185 comparison blocks/operators
blank lines 117 Chef 199 62–3, 118–19
blocks circles, drawing 157, 158 compass 39

A
Ada 18
colored 31
connecting 18
creating 72–3
circuits, computer 187, 188, 189
clicking, and events 44, 66, 162
clock pulse 188
compilers 191
components, computer 181, 217
compression 202, 218
addition 52, 102, 112 defining 72, 73 coordinates computer circuits 187, 188, 189
AI see Artificial Intelligence functions of 31 drawing with 158 computer games see games
algorithms 16, 17, 150–1, 218 help with 83 and location 168 computer languages see
Allen, Paul 200 with inputs 73 and movement 166 programming languages
ALU see arithmetic logic unit programming 22 in Python 157 computer programmers see
American Standard Code for types of 31 in Scratch 56–7 coders
Information Interchange see blocks palette 27, 31, 32, 35, 38, COBOL 199 computer programs 14–15
ASCII 50 code 22, 23 algorithms 16, 17
“and” block/operator 63, 103, bomb disposal 203 building 27 bad programs 212–13
118, 119 Boole, George 186 and colored blocks 30–1 essential 190–1
AND gate 186 Boolean expressions 62, 63, 64, flow of 30 experimenting with 19
Android operating system 198, 65, 111, 118–19, 120, 218 pausing 69 how they work 15
207 botnets, zombie 213 in Python 101 uses of 14
anti-malware software 213 brackets repeating 68 computers
antivirus programs 213 errors 94 running 30 deconstructing 217
apostrophes 115 in lists 128, 129 in Scratch 30–1, 101 invention of 201
Apple Mac in tuples 134 and sprites 28 main parts of 180–1
file management 193 using 112, 119 stopping 30, 68 mini 214–15
operating system 190, 207 brain, training 216 testing 30 supercomputers 203
programming languages branches/branching 65, 99, 100, code area 27 console games 198
198 120–1, 218 Code tab 27 consoles 14, 204
Python 3 on 88, 90 breaks, inserting in loops 126–7 code windows 92, 93, 106–7 containers 134, 218
Scratch on 25 Brin, Sergei 201 errors in 94 “continue” keyword 127
apps, making 206–7 broadcast blocks 70–1, 77 coders 14, 15 “Control” blocks 31, 65, 68
Arduino 214, 215 browser windows 210, 211 becoming a coder 18–19 control unit 180
arithmetic logic unit (ALU) 181 Bubble blaster project 164–75 becoming a master controls, game 174, 205
arrow keys 163, 166 bugs 148–9, 177, 207, 218 programmer 216–17 costumes 40–1
Artificial Intelligence (AI) 203, buttons famous 200–1 and movement 23, 40, 41
205 creating 152, 154–5 and games 204 random 61
ASCII 184, 218 labelling 155 think like a computer 16–17 Roll the die project 60–1
audio output 181, 215 linking to events 162 coding and speech bubbles 41
bytes (B) 183, 192, 218 clear 143 switching 34, 40, 41
computer programs 14–15 cryptography 202

B
Babbage, Charles 200 C
reading 176, 216
what is coding? 14–19
coding clubs 82, 207
CSS (Cascading Style Sheets) 208
cursor tools 26

backgrounds/backdrop 23, 26 C 18, 198 coding contests 217


changes to 45
selecting from library 33, 74
switching 41
C++ 198
calculations 180, 181, 189
in Python 112
colors
adding to shapes 159
changing 60, 160
D
data 218
backpack, Scratch 82 in Scratch 52–3 mixing 156 and functions 131
banking 199, 202 supercomputers 203 in Python 156–7 input 180
bases 182–3 calling functions 104, 139, 218 selecting 156 output 181
BASIC 199 cameras 215 commands secret 202
battery, computer 181 canvas 157, 158 Python and Scratch sending via internet 194,
beats 59 cars 14 compared 102–5 195
Berners-Lee, Tim 201 characters commas theft 213
binary code/signals 15, 182–3, between outputs 117 in lists 128 data storage
184, 185, 195, 218 numbering in strings 115 in tuples 134 in files 192–3
INDEX 221

memory 180, 181, 188, 189


in variables 50
data types
F
Facebook 201
graphic designers 204
graphical user interface
see GUI
installation
Python 3 88–91
Scratch 24–5
converting 111 false see true or false graphics 218 instruments, musical 59
mixed 111 fiberoptic cables 195 changing 160–1 integers 110, 219
spotting 111 file browsers 190 color and coordinates 156–7 Integrated DeveLopment
tuples and dictionaries 134–5 files 218 effects 43, 152, 153 Environment see IDLE
debugging 148–9, 174, 177, compressing 202 games 205 interface
207, 218 corruption 213 making shapes 158–9 GUI 154–5
decimal system 182 managing 193 graphics processing unit see GPU Scratch 26–7, 49
decisions properties 192 grid, x and y 56, 158 user 140, 146–7, 219
and branches 64–5 sizes 192 GUI 154–9, 218 internet 194–5
flowcharts 141 storing data in 192–3 connecting to other
logic gates 186–7 firewalls 213 computers via 152
die simulator 155
dictionaries 135
direction 39
floats 110, 218
flowcharts 141, 146
folders 193
H
hackers 213, 218
connection to 19
programming for 208–9
internet browsers 209
directories 193, 218 “for” loops 122, 124 hardware 15, 181, 191, 218 Internet Protocol 194
directory trees 193 “forever” block 23, 31, 32, 33, 38, programming 198 interpreters 191
division 52, 102, 112 39, 46, 47, 125 hexadecimal 156, 183, 185, 218 inverters 186
domain names 194 forever loop 46, 47, 69, 103, 125, high-level languages 191 iOS devices 198
drawing 133 Hopper, Grace 200 IP addresses 194, 195, 219
on a canvas 157, 165 Fortran 199 HTML (HyperText Markup
with coordinates 158 full stops 117 Language) 208, 209, 210
pens and turtles 48–9, 122,
152
functions 72, 130–1, 132–3, 218
calling 104, 130, 139 J
Drawing machine project 140–7
drums 59
getting data back from 131
making 130
passing data to 131
I
IDLE
Java 18, 198
JavaScript 18, 198, 208, 209
using 210–11
using and naming 143 code and shell windows 106–7 JPEGs 193

E and variables 138–9 color codes 107


and errors 148
educational apps 206
electrical signals 195
“elif” command 121 G
how it works 93
and installation of Python
89, 90, 91
K
keyboard
“else-if” command see “elif” gadgets 215 what is IDLE? 88 events 44, 66, 162, 163, 211
command Game Boy 201 working in 92–3, 209 input function 116, 162, 163,
emails game engines 205 “if” block/command 64, 120 180
spam 213 game logic 205 “if-elif-else” command 121 keys, dictionaries 135
websites 198, 208 games 14, 204–5 “if-else” command 120 kilobytes (KB) 183, 192
encryption 202, 218 customizing 81 “if-then” block/command 64, 66,
“end” label 117 improving 174 67, 103
errors 94–5
finding and fixing 148–9
Escape the dragon! project
in JavaScript 209
making with Python 177
for mobile devices 206
“if-then-else” block/command
64, 65, 76, 103
“in” operator 119
L
laptops 181
32–7 online 195 indents 98 latch circuits 189
event handlers 166, 211 random numbers in 53 index numbers 115, 128, 218 letter commands 141
events 211, 218 see also projects infinite loops 125 level designers 204
reacting to 162–3 Gates, Bill 200 input libraries 219
“Events” blocks 31, 32, gates, logic 186–7, 218 blocks with 73 building your own 176
44–5 Ghost game project 96–9 devices 162, 180, 189 help and documentation
EXCLUSIVE OR gate 187 gigabytes (GB) 189, 192 logic gates 186–7 153
experimenting global variables 138, 139 program 31, 100, 101, 106, importing 153
with coding 19 GNU/Linux operating system 201 116, 180, 218 light, data transmission as
with Python 176–7 Google 86, 201, 217 “input()” function 101, 130 pulses of 195
with Scratch 82–3 GPU 218 insertion sort 150 Linux 88, 201
222 REFERENCE

lists megabytes (MB) 183, 189, 192 nested loops 47, 69, 123 position
adding/deleting items 55, 105, memory 180–1, 188–9, 190, network adaptors 181, 195 coordinates 56–7
128, 129, 169 192, 219 networks, computer 152, random 43, 57
combining 129 messages 194, 218 “print()” function 87, 101, 102,
commands 105 reacting to 70 nibbles 183 108, 109, 116, 117, 130
copying 137 sending and receiving 70 NOT gate 186 printers 181
creating 55, 105 microphones, and events 44, 45 notes, musical 59 processors 100, 101, 180–1,
in loops 129 Microsoft 200 numbers 188–9, 190, 203, 219
playing with 55 Microsoft Windows binary and bases 182–3 program flow 100–1
putting tuples in 134 file management 193 comparing 62, 118 programming languages 15, 18,
in Python 128–9, 132–3 operating system 190, 207 data types in Python 110 19, 22, 49, 83, 198–9, 219
in Scratch 54–5 Python 3 on 88, 89 random 53, 104, 113, 152, 155 conversion into machine code
using 55, 129, 167 Scratch on 25 188
in variables 136–7 millennium bug 199 first 200
local variables 138, 139
logic circuits 187, 188, 189
logic errors 148
mini computers 214–15
Miyamoto, Shigeru 201
mobile phones 14, 204, 215
O
Objective-C 198
from the past 199
and interpreters 191
learning new 217
logic gates 186–7, 188, 189 apps 206–7 Ook 199 popular 198
logical operators 118–19 modules 219 open source movement 201 Python and Scratch commands
LOGO 49 importing 153 operating systems (OS) 25, compared 102–5
“Looks” blocks 31, 40, 42–3 Standard Library 152 88–91, 92, 190–1, 207, 219 text-based 86
loop blocks 46 Monkey mayhem project 74–81 operators 219 weird 199
loops 100, 103, 219 motherboard 181 blocks 31, 52, 53 programs see computer
complex 68–9 “Motion” blocks 31, 32, 33, 34, 36, logical 118–19 programs
with conditions 104 38–9, 57, 75 “or” block/operator 63, 103, 118 projects 11, 23
escaping 126–7 motion detector, webcam 45 OR gate 187 Bubble blaster 164–75
“for” 122, 124 mouse OS see operating systems Drawing machine 140–7
forever 46, 47, 69, 103, 125 control 25 output Escape the dragon! 32–7
in JavaScript 211 events 162, 211 and branching 120–1 Ghost game 96–9
lists in 129 input function 180, 189 devices 180, 181, 189 Monkey mayhem 74–81
main 99, 168, 169, 171 mouse-pointer logic gates 186–7 remixing existing 82
nested 69, 123 coordinates 56 program 31, 92, 100, 101, Roll the die 60–1
in Python 122–7, 133 following 69 106, 108, 116–17, 180–1 Silly sentences 132–3
in Scratch 46–7, 68–9 pointing toward 32, 33, 36 PS4 204
simple 46–7 movement pseudocode 143, 144, 147
skipping 124, 127
stopping 125
variable 123
coordinates 57
and costumes 23, 40, 41
with keys 66, 163, 166
P
packets 194, 195
Pygame 153, 177
Python 19, 83, 84–177
algorithms 150–1
while 124–5 and “Sensing” blocks 66, 67 Page, Larry 201 ASCII in 184
Lovelace, Ada 200 sprites 22, 23, 38–9, 57 painting area 60, 61 Booleans 111
low-level languages 191 Mpegs 193 passwords, theft of 213 branching 120–1
multiplication 52, 102, 112 paths 193 Bubble blaster project 164–75
music “Pen” blocks 31, 48–9, 87, 107 bugs and debugging 148–9

M
Mac see Apple Mac
adding 37, 79
files 192, 193, 202
making your own 59
Peters, Tim 151
photograph files 193
Pi 214
code structure 98–9
color and coordinates 156–7
color codes 107
macOS 190 playing 59 pictures, files 192, 193 different versions of 177
machine code 188, 191, 219 tempo 59 Piet 199 Drawing machine project
Malbolge 199 mutable/immutable objects 129 pilots 205 140–7
malware 212–13, 219 Pixar 86 errors 94–5
Math module 152 pixels 156 escaping loops 126–7
math
in Python 102, 112–13
in Scratch 52–3, 102
N
name errors 95
player’s name 50
PNGs 193
pop-up boxes/windows 146,
functions 130–1, 132–3
Ghost game project 96–9
harder commands 104–5
MATLAB 18 NASA 86 209, 210 input and output 116–17
medicine 203 negative numbers 56, 57 ports 195, 219 installing 88–91
INDEX 223

introducing IDLE 92–3 Random module 152, 153, 157 make some noise 58–9 sound library 79
libraries 152–3 random numbers 53, 104, 113, making things move 38–9 sounds 22, 23
lists 128–9, 132–3 152, 155 math in 52–3 adding to program 58–9, 79
lists in variables 136–7 random positions 43, 57 menu and tools 26 detectors 45
loops in 122–7, 133 Raspberry Pi 25, 214 and microphones 45 in games 205
making decisions 118–19 reacting to events 162–3 Monkey mayhem project playing 58
making games with 177 readable code 133 74–81 selecting from library 37, 58
making shapes 158–9 remainders 53 pens and turtles 48–9, 87 volume control 58
making windows 154–5 repeat loops 46, 122, 211 and Python 87, 102–5, 124, 125 spam 213
math in 112–13 “repeat until” block 68, 76, 77, and Python’s Ghost game 101 speakers 181
numbers in 110 78, 124 Roll the die project 60–1 speech bubbles 22, 28, 87, 101
print in 87 rewriting code 217 sending messages 70–1 adding 41, 161
program flow 100–1 robots 16, 203, 217 sensing and detecting 66–7 conversations 71
reacting to events 162–3 home-built 215 simple commands 102–3 speed, setting 51, 77
saving work 88 Roll the die project 60–1 simple loops 46–7 “split()” function 144
and Scratch 87, 101, 102–5, rotation software 24 sprites 22, 23, 28–9, 39, 219
124, 125 styles 38 special effects 42–3 adding graphic effects 43
code blocks 101 tools 61 sprites 28–9 adding more 76–7, 80
shell and code windows 92, routers 194, 195 strings and lists 54–5 adding sounds 58–9
93, 106–7 Ruby 18 true or false 62–3 changing size 43
shortcuts 171 running typical programs 23 changing time or speed 35, 51
Silly sentences project 132–3 programs 23, 102, 106 understanding 22 coordinates 56–7
simple commands 102–3 code blocks 30 variables 50–1, 108 collisions 67
sorting in 151 runtime errors 148 versions of 25 communication between
strings in 110, 114–15, 117 and webcams 45 70–1
tuples and dictionaries 134–5 website 24, 82 controlling 31, 66
turtle graphics 87
types of data 110–11
Unicode in 185
S
saving your work 11
what is Scratch? 18, 22–3
screens 181
scriptwriters 204
copying or deleting 29
creating and editing 29, 34, 36
designing your own 39
variables 99, 101, 108–9, 116 in Python 88, 93, 106, 107 SD cards 215 direction 39
variables and functions 138–9 in Scratch 24, 25, 33 secret data 202 and events 44–5
website 89 saying things (in Python) 161 selection sort 151 hiding and showing 42
what is Python? 19, 86–7 score 50, 79, 99, 172–3 “Sensing” blocks 31, 34, 36, 51, in the interface 28
what next? 176–7 scoreboards 172 65, 66–7, 75 movement 22, 23, 38–9, 57,
while loops 124–5 Scratch 20–83 separators 117 66–7
account 24 servers 219 naming 29
adding sounds 58–9, 79 shapes pen tools 48–9

Q
questions
backpack 82
blocks 30–1, 72–3
colored blocks and code
adding color 159
drawing 140
making 158–9
renaming 29
rotation styles 38
and code blocks 28
asking 54 30–1, 101 moving 160 selecting from library 34, 36,
combining 63 complex loops 68–9 naming 160 39, 75, 76
true or false 62–3 coordinates 56–7 shell windows 92, 93, 106–7, 116 and “Sensing” blocks 66–7
quote marks costumes 40–1 errors in 95 sprite list 27
errors 94 creating blocks 72–3 silicon chips 188, 189 turtle graphics 49
in lists 128 decisions and branches 64–5 Silly sentences project 132–3 and variables 35, 50–1
in strings 110, 114, 116 Escape the dragon! project skipping, in loops 127 what they can do 28
32–7 slicing 115 square roots 53
events 44–5 smartphones 206 stage 23, 25, 27

R
radio waves 195
experimenting with 82–3
harder commands 104–5
help menu 83
social apps 206
Socket module 152
sockets 195, 219
Standard Library modules 152
stop button 30
stopping programs 102
RAM 189 hide and seek 42–3 software 14, 15, 219 strategy games 205
“randint()” function 98, 99, 101, installing and launching 24–5 sorting algorithms 150–1 strings 219
104, 113, 130, 153, 155 interface 26–7, 49 “Sound” blocks 31, 58–9 adding 114
Random Access Memory see RAM lists 55 sound designers 204 assigning 108
224 REFERENCE

comparing 63, 118, 119


creating 114
joining 105
commands 105, 145
Drawing machine project
140–7
results in 52
in Scratch 50–1, 108
splitting tuples into 134
X
x and y coordinates 56, 57, 157,
length of 114 and loops 122 strings in 114 158, 166, 168
operators 119 Turtle module 152, 176 using 51, 109 Xbox One 204
in Python 110, 114–15, 117 “Variables” blocks 31, 50
in Scratch 54–5 video files 192, 193
separating 117
subprograms see functions
subtraction 52, 102, 112
U
Ubuntu
video games 204–5
writing 153
viruses 212–13, 219
Y
Yokoi, Gunpei 201
supercomputers 203 file management 193 visual output 181
surgeons 205 Python 3 on 88, 91 volume control 58
symbols, choice of 143
syntax 219
errors 94, 148
Scratch on 25
Unicode 185, 219
upper/lower case 94
von Neumann, John 180
Z
zombie botnets 213
USBs 215
user interface 140, 146–7, 219 W Zuckerberg, Mark 201

T washing machines 14
watches 206
tablets 25, 206
tabs 26, 27
teleporting 43
V
values
wearable technology 206
weather forecasting 199, 203,
206, 215
television 215 assigning to variables 108, web browsers 86, 195, 198
tempo 59 109, 113, 118, 136 web servers 198
terabytes (TB) 192 changing 136 webcams, and events 44, 45
testers, game 204 in dictionaries 135 websites
text editors 88 and functions 131 construction 208–9
text files 193 variables 35, 219 email 198, 208
text messages 14 assigning a value to 108, 109, interactive 198, 208, 210, 211
text-based programming 113, 118, 136 Python 89
languages 86 changing contents of 109 Scratch 24, 82
time limit 172–3 comparing 62, 63, 118 while loops 124–5
Time module 152 creating 50, 54, 77, 102, 108 white-hat hackers 213
Tkinter module 152, 154–5, 156, deleting 51 Wikipedia 201
157, 158, 159, 162, 165, 176 and functions 138–9 Windows
transistors 188 global 138, 139 see Microsoft Windows
travel apps 206 lists in 136–7 windows
Trojans 212, 213, 219 local 138, 139 code and shell 92, 93, 106–7
true or false 62–3, 64, 111, loop variables 123 making 152, 154–5, 165
118–21, 125 naming 50, 109, 143 word processing 86
tuples 134, 219 in Python 99, 101, 108–9, 116, words, comparing 63
Turing, Alan 200 138–9 world wide web 201
turtle graphics 49, 87, 105, 107 read-only 51 worms 212, 213

Acknowledgments
DORLING KINDERSLEY would like to thank: Max Albert for technical Scratch is developed by the Lifelong Kindergarten Group at MIT
assistance on the US edition; Vicky Short, Mandy Earey, Sandra Perry, Media Lab. See http://scratch.mit.edu
and Tannishtha Chakraborty for their design assistance; Olivia
Stanford for her editorial assistance; Caroline Hunt and Steph Lewis Python is copyright © 2001–2013 Python Software Foundation; All
for proofreading; Helen Peters for the index; and Adam Brackenbury Rights Reserved.
for creative technical support.

DORLING KINDERSLEY INDIA would like to thank: Kanika Mittal for


design assistance; Pawan Kumar for pre-production assistance; and
Abhijit Dutta and Mark Silas for code testing.

You might also like