Module 1: What a Computer Is and How to Talk to It
What is really inside the machines around you, why they do exactly what they are told, and why the order of your instructions decides everything.
What a Computer Actually Is
- Name the four jobs every computer does: input, storing, processing and output.
- Find five computers in your house that do not look like computers.
- Explain why a computer does what it is told rather than what you meant.
A computer the size of a room
In 1945, at a university in Philadelphia, engineers switched on a machine called ENIAC. It weighed about thirty tonnes. It filled a room bigger than most classrooms. Inside were more than seventeen thousand glass tubes that glowed like light bulbs, and when one burned out somebody had to find it and change it.
To give it a new job, six women who worked as its programmers had to walk round the machine unplugging thick cables and setting rows of switches by hand. Changing the program could take days.
The phone in a grown-up's pocket is millions of times faster than ENIAC, and it fits in a hand. But it is doing the same thing that room sized machine did, and it is doing it in the same way, which is what this course is about.
Key idea: Computers have got smaller and faster. What they actually do has not changed.
The four jobs
Every computer that has ever existed does four things.
- Input. It takes something in.
- Storing. It keeps things to use later.
- Processing. It follows instructions and works things out.
- Output. It puts something out.
Look at what happens when somebody types a message. The keyboard is input. The letters get stored. The processor works out what to draw on the screen. The screen is output. Four jobs, in a fraction of a second.
| Job | Parts that do it | Everyday example |
|---|---|---|
| Input | Keyboard, mouse, microphone, camera, buttons, touchscreen | Pressing 7 on a microwave |
| Storing | Memory and disk | Remembering your photos when it is switched off |
| Processing | The processor, sometimes called the CPU | Working out the countdown |
| Output | Screen, speaker, printer, lights, motors | The beep when the time runs out |
Most computers do not look like computers
Go and look at a microwave. It has buttons you press, which is input. It has a little screen, which is output. It counts down and turns the turntable, which is processing and more output. There is a computer in there.
Now count how many you can find. In an ordinary house there are usually more than twenty.
- The washing machine, which follows a different program for cottons and for wool.
- The television and whatever is plugged into it.
- A digital watch or a fitness band.
- The car outside, which has dozens.
- The traffic lights at the end of the road.
- The till in a shop, and the card machine next to it.
- A modern fridge, a thermostat, a doorbell with a camera.
The point: A computer is not a shape. It is anything that takes input, follows instructions, and produces output.
What a computer is not
This part matters more than any other part of the lesson, so read it slowly.
A computer does not understand anything. It does not know what a cat is, or what a birthday is, or what you meant. It has no idea what it is doing.
It cannot be bored, and it cannot get tired, and it will happily do the same wrong thing four million times without once wondering whether it should stop.
What it can do is follow instructions, extremely fast and exactly. That is the whole trick.
Remember: A computer does what you told it, not what you meant. When something goes wrong, that gap is nearly always where the problem is.
Fast, but only at tiny steps
People say computers are clever. They are not clever. They are fast.
The steps a processor can do are almost insultingly small.
- Add two numbers together.
- Compare two numbers and say which is bigger.
- Move a number from one place to another.
- Go and do a different instruction next.
That is close to the whole list. But a normal processor does billions of those every second, and out of billions of tiny steps you get a video call, a game, a weather forecast.
Here is the size of that number. If you did one step every second, without ever sleeping, one second of a computer's work would take you more than thirty years.
Programs and programmers
A program is a list of instructions for a computer. That is all it is. A washing machine program says fill, heat, turn, drain, spin.
A programmer is a person who writes those instructions. Programmers do not push electricity around. They write down, in a very careful language, what the machine should do in what order.
The first person to write instructions for a machine that could follow different programs was Ada Lovelace, in 1843, working on a mechanical computer designed by Charles Babbage. It was never finished, so her instructions were never run. She had worked out what such a machine could do before one existed.
The one skill this course teaches
All of computing rests on one skill: being able to say exactly what you want, in the right order, in steps small enough that something with no understanding at all can follow them.
You will practise it on paper for most of this course. Nothing here needs a computer, a website or an account. That is not a limitation. The thinking is the difficult part, and the thinking works with a pencil.
When you do want to try it on a screen, two free things are worth knowing about: Scratch, made by MIT, where you drag blocks together, and Code.org, which has short puzzles. Neither is needed for this course.
Why this matters: The hard part of coding is thinking clearly, and you can practise that at a kitchen table.
Try it: is there a computer in it?
Say yes or no for each, and give a reason using input and output.
- A pencil.
- A microwave.
- A wooden chair.
- A washing machine.
- A calculator.
- A book.
Answers. One: no, it takes no input and follows no instructions. Two: yes, buttons in, heat and beep out. Three: no. Four: yes, you choose a program and it follows a stored list of steps. Five: yes, keys in, numbers out, and it processes in between. Six: no, though a book is a kind of storage, it never processes anything.
Common misconceptions
- Mistake: computers are clever. They are fast and obedient. Every clever looking thing a computer does was thought of by a person and written down as instructions.
- Mistake: the screen is the computer. The screen is only output. The processing happens in a chip you never see, which in a phone is smaller than a fingernail.
- Mistake: computers never make mistakes. Computers follow instructions perfectly, including wrong ones. Almost every computer mistake is a person's mistake being carried out very accurately.
- Mistake: a computer knows what you meant. It has no idea what you meant. This is the single most useful thing to remember in the whole course.
What you now know
- ENIAC in 1945 filled a room and was reprogrammed by moving cables by hand.
- Every computer does four jobs: input, storing, processing and output.
- Most computers do not look like computers, and there are more than twenty in an ordinary house.
- A processor only does tiny steps, but it does billions of them every second.
- A program is a list of instructions and a programmer is the person who writes it.
- A computer does what it is told, not what you meant.
Sources
- Wikipedia contributors. (n.d.). ENIAC. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Computer. Wikipedia. en.wikipedia.org
- Computer History Museum. (n.d.). Timeline of computer history. Computer History Museum. computerhistory.org
- Wikipedia contributors. (n.d.). Ada Lovelace. Wikipedia. en.wikipedia.org
- BBC. (n.d.). KS2 Computing. BBC Bitesize. bbc.co.uk
- Key terms
- Computer
- A machine that takes input, follows stored instructions, and produces output.
- Input
- Anything that goes into a computer, like a key press, a tap or a sound.
- Output
- Anything a computer puts out, like a picture on a screen, a sound or a motor turning.
- Processor
- The part that follows the instructions and does the working out. Also called the CPU.
- Program
- A list of instructions for a computer to follow.
- Programmer
- A person who writes those instructions.
- Storage
- Where a computer keeps things so it still has them later.
Exact Instructions
- Explain why an instruction that seems obvious to a person can be useless to a computer.
- Spot the three faults in a bad instruction: vague, missing a step, or assuming knowledge.
- Rewrite a sloppy instruction as a numbered list a literal follower could obey.
Eleven minutes too late to help
On 18 February 2021, a NASA rover called Perseverance landed on Mars. The landing took about seven minutes: hitting the atmosphere, a parachute, a rocket powered crane, and finally wheels on the ground.
Here is the problem the engineers had. A radio signal from Mars to Earth took roughly eleven minutes that day. So by the time anyone on Earth heard that the landing had started, the rover had already landed, or already crashed, eleven minutes earlier.
Nobody could steer it. Nobody could shout stop. Every single instruction had to be written down beforehand, exactly right, and the rover had to carry them out with no help.
Key idea: Instructions have to be right before they are run, because a computer will not ask you what you meant.
The sandwich test
Here is the classic way of proving this, and it needs one child, one grown-up, bread and a jar of something spreadable.
The child writes instructions for making a sandwich. The grown-up plays a robot and does exactly what is written, in the most literal way possible.
Watch what happens to ordinary sentences.
- Put the peanut butter on the bread. The robot puts the closed jar on top of the loaf. It is on the bread.
- Open the jar. With what? The robot has not been told to pick it up.
- Spread it. Spread what, with what, on what, how much?
- Cut the sandwich in half. The robot cuts through the plate.
This is funny for about four minutes and then it becomes genuinely useful, because you can feel the gap between what you said and what you meant.
The three faults
Bad instructions fail in three ways, and naming them makes them easier to hunt.
- Vague. It could mean more than one thing. Put it over there. Which it? Which there?
- Missing a step. The order jumps. You cannot spread butter before you have opened the tub.
- Assuming knowledge. It uses a word the follower does not know. Make a cup of tea hides about thirty separate steps.
Test any instruction against those three and most problems appear at once.
The point: Vague, missing, or assumed. Nearly every broken instruction is one of those three.
Rewriting a bad one
Take this instruction: put the ball in the box.
A literal follower can fail in six ways. Which ball? Which box? What if the box has a lid? Do they need to walk anywhere? What if the ball is already in a different box? What counts as in?
Here is the same instruction rewritten so a robot could do it.
- Walk forward until you are standing beside the red ball on the floor.
- Bend down and close your hand around the ball.
- Stand up, holding the ball.
- Turn to face the blue box in the corner.
- Walk forward until the box is directly in front of your feet.
- Hold your hand over the open top of the box.
- Open your hand.
Seven steps for something a person does without thinking. That is normal. Coding is mostly the job of saying obvious things carefully.
Agree the words first
Real programming languages have a fixed set of words. So should your instructions.
Before you write anything, agree on the list of moves the follower is allowed to do. For a person walking on a floor grid, this works well.
FORWARD 1means take one step forward.LEFTmeans turn a quarter turn to the left, without moving.RIGHTmeans turn a quarter turn to the right, without moving.PICK UPmeans pick up whatever is on the square you are standing on.
Now a whole route can be written as a short list: FORWARD 2, RIGHT, FORWARD 3, PICK UP.
Notice how much argument that prevents. Turn left no longer means anything vague, because everybody agreed what it means before the game started.
Remember: Decide what your words mean before you use them. Every programming language does this.
Being precise about numbers
Walk forward is vague. Walk forward four steps is a command.
Numbers do a lot of work in instructions, and leaving them out is the fastest way to make a mess.
| Vague | Exact |
|---|---|
| Turn a bit | Turn right a quarter turn |
| Wait a while | Wait 10 seconds |
| Add some water | Add 200 millilitres of water |
| Make it bigger | Make it twice as tall |
| Go over there | Walk forward 6 steps |
Try it: find the fault
For each instruction, say which of the three faults it has: vague, missing a step, or assuming knowledge.
- Draw a house.
- Pour the milk into the bowl, then get the milk out of the fridge.
- Put it next to the other one.
- Log in and check it.
Answers. One: assuming knowledge, because house means a different picture to every person, and it is also vague about size and position. Two: missing a step in the wrong order, since you cannot pour milk you have not fetched. Three: vague, with two words that point at nothing, it and the other one. Four: assuming knowledge, since log in hides several steps and check it does not say what to look for.
Why this is the whole job
People sometimes imagine programmers spend their time typing furiously. Mostly they sit and think about what exactly should happen, in what order, in cases nobody mentioned.
What if the box is full? What if the ball is not there? What if somebody presses two buttons at once? A person handles those without noticing. A computer needs to be told.
Why this matters: Writing exact instructions is not a small skill you do before the real work. It is the real work.
Common misconceptions
- Mistake: the computer will work out what I meant. It has nothing to work it out with. It has no idea what a sandwich is, or that plates should not be cut in half.
- Mistake: more words make it clearer. A long, chatty instruction can be vaguer than a short one. Exact beats long every time.
- Mistake: if I understand it, it is clear. You already know what you meant, so you are the worst possible judge. That is why you test instructions on somebody else.
- Mistake: real programmers do not need to be this careful. The Mars landing worked because thousands of instructions were exact eleven minutes before anybody on Earth could react.
The short version
- Instructions must be complete before they run, because the machine cannot ask what you meant.
- Bad instructions are vague, missing a step, or assuming knowledge.
- Rewriting one properly usually turns one sentence into six or seven steps.
- Agree what your words mean before you start using them.
- Put numbers in: four steps, ten seconds, a quarter turn.
- Test your instructions on somebody who does not already know what you meant.
Sources
- NASA. (n.d.). Mars 2020: Perseverance Rover. NASA Science. science.nasa.gov
- CS Unplugged. (n.d.). Kidbots. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Wikipedia contributors. (n.d.). Algorithm. Wikipedia. en.wikipedia.org
- Key terms
- Instruction
- One step telling a computer or a person to do one thing.
- Vague
- Able to mean more than one thing, so the follower has to guess.
- Literal
- Doing exactly what the words say, and nothing else.
- Command
- An instruction whose meaning has been agreed in advance, like FORWARD 1.
- Precise
- Exact, with numbers and named objects instead of it and over there.
- Assumption
- Something you expected the follower to know without being told.
Sequence: The Order Matters
- Explain what a sequence is and why a program runs one step at a time from the top.
- Decide which pairs of steps can safely swap places and which cannot.
- Trace a short program with your finger and predict where it ends up.
Shoes first
Do this before reading on. Take one sock and one shoe. Put the shoe on your foot. Now put the sock on, over the shoe.
It works, in the sense that both items are on your foot. Both steps happened. Nothing was missed out. And the result is ridiculous.
You did not do anything wrong except the order, and the order was enough to ruin it.
Key idea: Having all the right steps is not enough. They have to be in the right order.
What a sequence is
A sequence is a set of steps in a fixed order, done one after another.
That is how a program runs. The computer starts at the top, does the first instruction, then the next, then the next, and does not skip about. If instruction three says draw a circle, the circle is drawn after instruction two and before instruction four. Always.
This is the first of the big ideas in this course, and it is the one everything else sits on. Loops, conditions and events all change which instruction comes next, but there is still an order at every moment.
Which pairs can swap?
Not every pair of steps matters. Here is the test: does the second step need something the first step made?
| Pair of steps | Can they swap? | Why |
|---|---|---|
| Put on sock, put on shoe | No | The shoe covers the foot the sock needs |
| Put on hat, put on scarf | Yes | Neither one blocks the other |
| Open the jar, take out the jam | No | You cannot reach into a closed jar |
| Feed the cat, water the plants | Yes | They have nothing to do with each other |
| Turn on the tap, wash your hands | No | No water yet |
The point: Two steps must stay in order when the second one needs something the first one produced.
A program you can walk
Draw a grid on paper, five squares by five squares. Put a small toy on the bottom left square, facing up the page. Put a counter, or a coin, on a square three up and two right.
Here is a program, using the commands from the last lesson.
FORWARD 3RIGHTFORWARD 2PICK UP
Move the toy one instruction at a time, and keep your finger on the line you are doing. It ends on the coin and picks it up.
Now swap lines 2 and 3, so it says FORWARD 3, FORWARD 2, RIGHT, PICK UP.
Run it again with your finger. The toy goes five squares up, falls off the top of the grid, turns right, and picks up nothing. Same four instructions. Completely different outcome.
Tracing: being the computer
What you just did has a name. Tracing means pretending to be the computer and following the program by hand, one line at a time, writing down what changes.
It is the single most useful habit in this whole course, and here is how to do it properly.
- Keep one finger on the instruction you are doing.
- Keep a written note of anything that changes: where you are, what you are holding, what number you have.
- Do exactly what the line says, not what you think it should say.
- Move your finger down one line and repeat.
Point three is the hard one. When you trace your own program, you keep quietly correcting it in your head, which is precisely how bugs survive.
Remember: When tracing, do what the line actually says. Your head will try to be helpful and it must not be allowed to.
A trace table
For anything with numbers, write the changes in a small table. Take this program.
SET score TO 0ADD 5 TO scoreADD 3 TO scoreTAKE 2 FROM score
| Line | What it does | score is now |
|---|---|---|
| 1 | Starts the score at zero | 0 |
| 2 | Adds five | 5 |
| 3 | Adds three | 8 |
| 4 | Takes away two | 6 |
The answer is 6. Now imagine line 1 had been left out. The score would start at whatever it happened to be already, which might be anything, and the answer would be wrong in a way that changes every time you run it. Setting a starting value is a step, and forgetting it is a real bug that catches everybody.
When the order does not matter
Sometimes steps are genuinely independent, and knowing that is useful too.
If a program has to send three emails, feed three animals or draw three separate shapes in different corners, the order between them makes no difference. Big computers take advantage of this by doing independent jobs at the same time on different parts of the chip.
So the question is never simply what order. It is: which steps depend on which other steps?
Try it: unscramble these
Put each set in the right order, then check.
Set A, brushing teeth: rinse your mouth; put toothpaste on the brush; brush for two minutes; wet the toothbrush; put the cap back on the toothpaste.
Set B, a jam sandwich: spread the jam; put the second slice on top; open the jar; take two slices of bread.
Answers. Set A: wet the toothbrush, put toothpaste on the brush, put the cap back on the toothpaste, brush for two minutes, rinse your mouth. The cap step can also go later, since nothing else needs it, which makes it a genuinely free step. Set B: take two slices of bread, open the jar, spread the jam, put the second slice on top. Every one of those depends on the one before, so there is only one correct answer.
Common misconceptions
- Mistake: if all the steps are there, the program is right. Sock and shoe are both on your foot in the wrong order too.
- Mistake: the computer will notice the order is silly. It will not. It has no idea what a sock is or what a foot is for.
- Mistake: every step depends on the one before. Some are completely independent, and spotting those is how big programs get made faster.
- Mistake: sequence is only for beginners. Every program ever written, in every language, is still doing one thing after another underneath.
Putting it together
- A sequence is steps in a fixed order, carried out one at a time from the top.
- Two steps must stay in order when the second needs something the first produced.
- Swapping two lines can change the whole result even when nothing is missing.
- Tracing means following a program by hand, doing exactly what each line says.
- A trace table records what changes after every line, which is how you find where it went wrong.
- Forgetting to set a starting value is a real bug that produces different wrong answers each time.
Sources
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- CS Unplugged. (n.d.). Kidbots. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Wikipedia contributors. (n.d.). Control flow. Wikipedia. en.wikipedia.org
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Key terms
- Sequence
- A set of steps in a fixed order, done one after another.
- Step
- One single instruction in a program.
- Trace
- To follow a program by hand, one line at a time, doing exactly what it says.
- Trace table
- A small table recording what has changed after each line runs.
- Dependent steps
- Steps that must stay in order because the second needs what the first produced.
- Starting value
- The value something is set to before the program begins changing it.
Module 2: The Four Big Ideas in Code
Repeating without rewriting, making choices, waiting for a person to do something, and the ordinary daily business of finding your own mistakes.
Loops: Saying It Once Instead of Fifty Times
- Rewrite a repeated set of instructions as a loop with a count.
- Tell the difference between a counted loop, a loop with a condition, and a forever loop.
- Work out what a loop inside another loop will do.
A square, and then a fifty sided shape
Here is a program that draws a square. The turtle draws a line, turns a quarter turn, and does it four times.
FORWARD 10RIGHTFORWARD 10RIGHTFORWARD 10RIGHTFORWARD 10RIGHT
Eight lines for four sides. Now imagine a shape with fifty sides. That is a hundred lines, and every one of them has to be typed correctly, and if you later want a different length you have to change fifty of them without missing one.
Nobody does that. There is a better way, and it is one word long.
Key idea: When you find yourself writing the same thing again, that is the signal for a loop.
The counted loop
A loop is an instruction that tells the computer to do something again.
The square becomes this.
REPEAT 4FORWARD 10RIGHTEND REPEAT
Four lines instead of eight, and it does exactly the same thing. The two instructions between REPEAT and END REPEAT are called the body of the loop, and they run four times.
Now watch what happens when you want a triangle instead. You change one number. Change 4 to 3 and turn a third of a turn instead of a quarter. Change 4 to 50 and you have a fifty sided shape that looks almost exactly like a circle.
The point: A loop is not just shorter. It is easier to change, because the thing you want to change is written down once.
Loops are everywhere already
You use loops all day without a computer in sight.
- Brushing teeth: repeat for every tooth.
- Dealing cards: repeat until everybody has seven.
- Setting the table: repeat for every person sitting down.
- A song: verse, chorus, verse, chorus.
- Stirring: keep stirring until there are no lumps.
Notice that those last two are different from the first ones. Sometimes you know the number in advance. Sometimes you do not, and you stop when something becomes true.
Three kinds of loop
| Kind | Looks like | Stops when | Everyday example |
|---|---|---|---|
| Counted | REPEAT 8 | It has run that many times | Do eight star jumps |
| Conditional | REPEAT UNTIL smooth | Something becomes true | Stir until there are no lumps |
| Forever | REPEAT FOREVER | Never, until switched off | Traffic lights changing all day |
The forever loop sounds like a mistake and it is not. A game runs a forever loop: check the buttons, move everything, draw the screen, and do it all again, sixty times a second, until you quit. A central heating thermostat runs one for years.
The loop that will not stop
Now the famous bug. Here is a conditional loop.
REPEAT UNTIL you reach the wallFORWARD 1END REPEAT
That works, as long as you are facing the wall. Turn round first and it never ends, because you walk away from the wall for the rest of your life.
A loop whose stopping condition never becomes true is called an infinite loop, and it is one of the most common bugs there is. When a program freezes and stops responding, an infinite loop is often what has happened: the computer is not stuck, it is busy, going round and round forever, exactly as instructed.
Remember: Every conditional loop needs something inside it that can eventually make the stopping condition true.
A loop inside a loop
You can put a loop inside another one. This is called nesting, and it is how rows and columns get made.
REPEAT 3REPEAT 5DRAW STAREND REPEATNEW LINEEND REPEAT
How many stars? The inside loop draws five, and the outside loop makes the whole inside part happen three times. So three rows of five, which is fifteen stars.
The rule is that the inner loop finishes completely every time the outer loop goes round once. Trace it slowly with your finger the first time.
A clock is a good example. The seconds hand goes round sixty times for every one time the minutes hand moves round once, and the minutes hand goes round sixty times for one turn of the hour hand. That is a loop inside a loop inside a loop.
Tracing a loop
Take this program and work out the total.
SET total TO 0REPEAT 4ADD 3 TO totalEND REPEAT
| Time round the loop | Adds | total is now |
|---|---|---|
| Before starting | 0 | |
| 1st | 3 | 3 |
| 2nd | 3 | 6 |
| 3rd | 3 | 9 |
| 4th | 3 | 12 |
The answer is 12, which is four threes. A loop that adds the same number over and over is multiplication, done the slow way, and that is genuinely how some machines do it.
Try it: spot the loop
Rewrite each of these using a loop, then check.
- Clap, clap, clap, clap, clap, clap.
- Jump, spin, jump, spin, jump, spin.
- Keep pouring water into the glass. Stop when it is full.
- Draw 4 rows with 6 dots in each row.
Answers. One: REPEAT 6, clap. Two: REPEAT 3, with both jump and spin inside the loop, because the pattern that repeats is the pair. Three: REPEAT UNTIL the glass is full, pour a little. Four: a nested loop, REPEAT 4 containing REPEAT 6 draw a dot, followed by a new line, which gives 24 dots.
Common misconceptions
- Mistake: a loop makes the program run faster. The computer does exactly the same amount of work. What gets shorter is what you had to write, and the number of places a mistake can hide.
- Mistake: loops go on forever. Only a forever loop does. A counted loop stops after its number, and a conditional loop stops when its condition becomes true.
- Mistake: a frozen program has stopped. Usually it is going round an infinite loop as fast as it can, doing precisely what it was told.
- Mistake: in a nested loop the two loops take turns. The inner loop finishes completely each time the outer one goes round once, which is why three and five give fifteen and not eight.
What to carry forward
- Writing the same thing twice is the signal that a loop is needed.
- A counted loop repeats a fixed number of times.
- A conditional loop repeats until something becomes true, and needs a way for that to happen.
- A forever loop is normal in games, thermostats and traffic lights.
- A nested loop runs the inner one completely for each turn of the outer one.
- Loops make programs shorter and much easier to change, not faster.
Sources
- Wikipedia contributors. (n.d.). Loop (statement). Wikipedia. en.wikipedia.org
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- Scratch Team, MIT Media Lab. (n.d.). Scratch: imagine, program, share. Massachusetts Institute of Technology. scratch.mit.edu
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Key terms
- Loop
- An instruction that tells the computer to do something again.
- Counted loop
- A loop that repeats a fixed number of times, like REPEAT 8.
- Conditional loop
- A loop that keeps going until something becomes true.
- Forever loop
- A loop with no stopping point, used in games and thermostats.
- Loop body
- The instructions inside the loop, which are the ones that repeat.
- Nested loop
- A loop inside another loop, which is how rows and columns are made.
- Infinite loop
- A loop whose stopping condition never comes true, so it never ends.
If This, Then That
- Write a condition as a question that can only be answered yes or no.
- Use IF, ELSE and a chain of tests, and explain why the order of the tests matters.
- Combine two conditions with AND and OR and predict the result.
The doors that know you are there
Walk up to a supermarket and the doors open. Stand still ten steps away and they stay shut.
There is no person watching. Above the door is a sensor, and the program behind it is about as simple as a program gets. It asks one question, several times a second, forever.
Is somebody standing in front of the door? If yes, open. If no, close.
That is a condition, and it is the third big idea in this course. Sequence says what order. Loops say do it again. Conditions let a program make a choice.
Key idea: A condition is a question a computer can answer yes or no, and it decides which instructions run next.
Questions with only two answers
A condition has to be answerable with yes or no. Programmers usually say true or false, which means the same thing.
Look at the difference.
| Not a condition | A condition |
|---|---|
| What colour is the door? | Is the door red? |
| How old are you? | Are you older than 7? |
| What is the score? | Is the score more than 10? |
| Where is the cat? | Is the cat in the kitchen? |
Anything you want to ask can be turned into a yes or no question. It sometimes takes several of them, and that is fine.
IF and THEN
The basic shape is this.
IF it is rainingTHEN take a coat
If the answer is yes, the THEN part happens. If the answer is no, it is skipped completely and the program carries on below.
Notice what a condition is not. It is not a loop. The question is asked once, at that moment, and then the program moves on.
ELSE: the other road
Often you want something to happen either way.
IF it is rainingTHEN take a coatELSE take sunglassesLeave the house
Exactly one of those two middle lines happens. Never both, and never neither. Then everybody, rained on or not, leaves the house.
Drawing it as a fork in a road helps: the road splits, you take one branch, and the two branches join up again afterwards.
The point: With IF and ELSE, one branch runs and the other does not. Then the program comes back together.
A chain of tests, and the bug hiding in it
Say you are giving out medals for a game score.
IF score is 10 or more, THEN goldELSE IF score is 5 or more, THEN silverELSE bronze
Trace it with a score of 12. Line 1 is true, so gold, and the rest is skipped. Score of 7: line 1 is false, line 2 is true, so silver. Score of 2: both false, so bronze. It works.
Now swap the first two lines round, so it tests 5 or more first.
Score of 12. Is 12 five or more? Yes. So it gives silver, and stops. Nobody in the game can ever win gold, and the program has no idea anything is wrong.
Remember: In a chain of tests, put the fussiest test first. The loosest test grabs everybody if you let it go first.
Two conditions at once: AND and OR
Sometimes one question is not enough.
- AND needs both to be true. Take an umbrella if it is raining AND you are going outside. If you are staying in, no umbrella, even in a storm.
- OR needs at least one to be true. Wear a coat if it is cold OR it is raining. Either one is enough, and both is fine too.
- NOT flips the answer. IF NOT hungry, do not make lunch.
Here is a table for two conditions, which is worth working through slowly because everyday English is much sloppier than this.
| Raining? | Cold? | Raining AND cold | Raining OR cold |
|---|---|---|---|
| Yes | Yes | Yes | Yes |
| Yes | No | No | Yes |
| No | Yes | No | Yes |
| No | No | No | No |
The row that catches people is the last column, second row. In a computer, OR is happy with just one. In everyday speech, would you like tea or coffee usually means pick exactly one, which is not what OR means here.
Conditions inside conditions
You can put an IF inside another IF, which is called nesting, just as with loops.
IF it is a school dayIF you are awake before 8THEN walk to schoolELSE run to schoolELSE stay in bed
The inner question is only asked at all when the outer one was true. On a Saturday, the program never even wonders what time you woke up.
Nesting more than two or three deep gets very hard to follow, and at that point most programmers rewrite it using AND instead.
Conditions in real things
- A microwave: IF the door is open, THEN do not heat. This condition is checked constantly, and it is the reason microwaves are safe.
- A game: IF the player touches the spikes, THEN lose a life.
- A washing machine: IF the water is not hot enough, THEN keep heating.
- A phone: IF the battery is under 20 percent, THEN show the warning.
- A traffic light: IF a car is waiting AND the other road has had its turn, THEN change.
Try it: what happens?
Use this program. IF score is more than 20, THEN say win, ELSE say try again.
- Score is 25. What does it say?
- Score is 20. What does it say?
- Score is 0. What does it say?
- How many of the two messages can ever appear at once?
Answers. One: win. Two: try again, because 20 is not more than 20, and this off by one trap is one of the commonest bugs in all of programming. Three: try again. Four: exactly one, never both and never neither.
Common misconceptions
- Mistake: the ELSE part runs as well. Exactly one branch runs. If the condition was true, the ELSE is skipped entirely.
- Mistake: IF keeps checking. An IF asks once, at that moment. A loop is what keeps checking, which is why the supermarket door has both.
- Mistake: more than 20 includes 20. It does not. If you mean 20 as well, you have to write 20 or more, and mixing these up is a genuine bug in real software.
- Mistake: OR means one or the other but not both. In programming, OR is true when either is true and also when both are.
Pulling it together
- A condition is a question with only two possible answers: true or false.
- IF runs the THEN part when the answer is yes, and skips it when the answer is no.
- With ELSE, exactly one of the two branches runs, and then the program rejoins.
- In a chain of tests, the fussiest test must come first or the loosest one takes everything.
- AND needs both true; OR needs at least one; NOT flips the answer.
- More than 20 does not include 20, and this catches everybody at least once.
Sources
- Wikipedia contributors. (n.d.). Conditional (computer programming). Wikipedia. en.wikipedia.org
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- CS Unplugged. (n.d.). Topics. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Key terms
- Condition
- A question a computer can answer only yes or no.
- True and false
- The two answers a condition can have.
- IF
- An instruction that runs the next part only when the condition is true.
- ELSE
- The branch that runs when the condition is false.
- AND
- True only when both conditions are true.
- OR
- True when at least one condition is true, including when both are.
- NOT
- Flips an answer from true to false, or false to true.
- Branch
- One of the roads a program can take at a choice point.
Events: Making Things Happen
- Explain what an event is and write a rule in the form when this happens, do that.
- Say how an event is different from a condition.
- List the events a game or a doorbell has to wait for, including ones with no person involved.
A button by the front door
Somebody presses a doorbell. A moment later a chime sounds in the kitchen.
Nobody in the kitchen was watching the button. The bell was not counting anything or checking anything. It was doing nothing at all, and then the press happened and the chime ran.
That is an event: something that happens, from outside the program, that a piece of code has been waiting for.
Key idea: An event turns a program from a list you run into a machine that reacts.
When this, do that
Event rules are written in a fixed shape.
WHEN the doorbell is pressed, THEN play the chimeWHEN the space key is pressed, THEN make the cat jumpWHEN the green flag is clicked, THEN start the gameWHEN two sprites touch, THEN lose a lifeWHEN 30 seconds have passed, THEN show the time is up message
The piece of code attached to an event has a name: an event handler. It sits there doing nothing, possibly for hours, and then runs the instant its event happens.
How an event differs from a condition
These two get muddled constantly, and the difference is worth pinning down.
| Condition (IF) | Event (WHEN) | |
|---|---|---|
| Asked | Once, at the moment the program reaches it | Never asked; it arrives on its own |
| Comes from | Something the program already knows | Outside: a person, a sensor, a clock, a message |
| Example | IF the score is over 20, say win | WHEN the mouse is clicked, fire |
| Program is | Running through its steps | Waiting |
Underneath, a computer often does check for events over and over, thousands of times a second, in a loop you never see. But from the point of view of the person writing the code, the program waits and the event arrives.
The point: An IF asks a question. A WHEN waits for news.
Not all events involve a person
People are the obvious source of events, but plenty of events have nothing to do with anybody.
- Time. When a timer reaches zero. An alarm clock is this and nothing else.
- Sensors. When the temperature drops below 18 degrees, turn the heating on.
- Messages. When a message arrives from another computer, show a notification.
- The program itself. When the download finishes, open the file.
- Other parts of the same program. A sprite in a game can broadcast a message that other sprites are all waiting for.
That last one is how anything complicated gets organised. One part shouts level complete, and six other parts, which know nothing about each other, all react.
The thing that surprises everybody
Up to now, programs in this course have run from the top to the bottom in order.
A program built out of events does not work like that. Ten different handlers sit waiting at once, and which one runs next depends on what the person outside does. Press a key and one runs. Click the mouse and a different one runs. Do nothing at all and none of them run, possibly forever.
So the order the handlers are written on the page tells you nothing about the order they will run in. This feels wrong the first few times and then becomes obvious, because it is exactly how a shop counter works: the shopkeeper has rules for what to do when somebody buys something, when the phone rings, and when a delivery arrives, and the day decides which happens first.
Remember: With events, the order things are written in is not the order they happen in.
Designing a game on paper
You can design a whole game without a computer by listing its events. Here is a simple catching game.
| When this happens | Do this |
|---|---|
| The game starts | Set score to 0, put the basket in the middle |
| The left arrow is pressed | Move the basket 10 steps left |
| The right arrow is pressed | Move the basket 10 steps right |
| An apple touches the basket | Add 1 to the score, move the apple back to the top |
| An apple touches the ground | Take 1 from lives |
| Lives reaches 0 | Say game over and stop |
That table is the game. Everything else is decoration. If you ever build it in Scratch, which is free and made by MIT, you will find the blocks have almost exactly these names, because Scratch is built around events on purpose.
Two events at nearly the same time
What if somebody presses two keys at once?
The computer puts events in a queue, like people lining up at a till, and deals with them one at a time in the order they arrived. They are handled so quickly that it looks simultaneous.
This matters in games. If your character can jump and duck, and both handlers change the same thing, the second one wins, which is a real source of odd behaviour.
Try it: name the event
For each, write the rule as WHEN something, THEN something.
- A microwave beeps when the time runs out.
- A phone screen lights up when a message arrives.
- A car dings when a seatbelt is not fastened.
- A shop door opens as you walk up.
Answers. One: WHEN the timer reaches zero, THEN beep. Two: WHEN a message arrives, THEN light the screen. Three: WHEN the engine starts AND the belt is unfastened, THEN ding, which is an event and a condition working together. Four: WHEN the sensor detects a person, THEN open the doors.
Common misconceptions
- Mistake: events happen in the order they were written. They happen in the order they occur in the world. The page order tells you nothing.
- Mistake: an event is the same as an IF. An IF is a question the program asks itself. An event is news arriving from outside.
- Mistake: events need a person. Timers, sensors, finished downloads and messages from other parts of the program are all events.
- Mistake: a waiting program is doing nothing wrong. A program that never responds may simply have no handler for what you did, which is why a button that does nothing when clicked is such a common bug.
Where this leaves us
- An event is something that happens which a piece of code has been waiting for.
- Event rules take the shape WHEN this happens, THEN do that.
- The waiting code is called an event handler.
- An IF asks a question at a moment; a WHEN waits for news from outside.
- Time, sensors, messages and other parts of the program all create events.
- The order handlers are written in has nothing to do with the order they run in.
Sources
- Wikipedia contributors. (n.d.). Event (computing). Wikipedia. en.wikipedia.org
- Scratch Team, MIT Media Lab. (n.d.). Scratch: imagine, program, share. Massachusetts Institute of Technology. scratch.mit.edu
- Wikipedia contributors. (n.d.). Scratch (programming language). Wikipedia. en.wikipedia.org
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- Key terms
- Event
- Something that happens which a piece of code has been waiting for.
- Event handler
- The instructions that run when a particular event happens.
- Trigger
- The thing that sets an event off, such as a key press or a timer.
- Broadcast
- A message one part of a program sends so other parts can react.
- Queue
- A line of events waiting to be dealt with, one at a time in order of arrival.
- Sensor
- A part that detects something in the world, like heat, light or movement.
Debugging: Finding the Mistake
- Explain why debugging is a normal part of programming rather than a sign of failure.
- Name five kinds of bug and give an example of each.
- Use a five step method to find a bug, changing only one thing at a time.
The moth in the machine
On 9 September 1947, at Harvard University, a team was working on a huge computer called the Mark II when it started giving wrong answers.
They opened it up and searched. Inside one of the relays, which are little electrical switches, they found a moth. It had flown in and been squashed, and it was stopping the switch from working.
They taped the moth into the logbook and wrote beside it that this was the first actual case of a bug being found. That page, moth still attached, is now in a museum.
The word bug was already engineers' slang for a fault before that day, which is exactly why the note is a joke. But the name stuck to computers, and a mistake in a program has been called a bug ever since.
Key idea: A bug is a mistake in the instructions. Almost never is anything actually broken.
Everyone's first version is wrong
Here is something that is not usually said out loud. Professional programmers, with twenty years of experience, write programs that do not work on the first try. All the time. Every day.
They then spend a large part of their working life finding out why, and they are paid well to do it. Debugging is not what happens when you fail at programming. It is most of programming.
So when your program does the wrong thing, nothing has gone wrong with you. You have reached the part where the actual work starts.
Remember: A bug is information. It is the program telling you exactly where your thinking and your writing came apart.
Five kinds of bug
| Kind | What it looks like | Example |
|---|---|---|
| Wrong word | The computer stops, complaining | Writing FORWERD instead of FORWARD |
| Wrong order | It runs but does things back to front | Spreading jam before opening the jar |
| Missing step | Something never happens | Never setting the score to zero at the start |
| Wrong number | Nearly right, but out by a bit | FORWARD 3 when you needed FORWARD 4 |
| Wrong idea | It runs perfectly and gives a wrong answer | Testing 5 or more before testing 10 or more |
The first kind is the easiest, because the machine tells you. The last kind is the hardest, because nothing complains at all. The program is happily doing exactly what you wrote, and what you wrote is not what you wanted.
The five step method
Guessing wildly is the slowest way to fix anything. Here is the method that actually works.
- Say what it does and what it should do. Out loud, in one sentence each. It draws a triangle. It should draw a square.
- Find the smallest example that still goes wrong. If it fails on a list of twenty names, try three. Small bugs are easier to see than big ones.
- Trace it by hand. Go line by line, doing exactly what each line says, and find the first line where what happens differs from what you expected. The bug is at or just before that line.
- Change one thing. One. Then run it again.
- Test everything again, including the parts that already worked, because fixes break things.
Step four is the one people ignore. If you change four things and it works, you do not know which one fixed it, and you may have added two new bugs that are hiding behind each other.
Explaining it to a duck
There is a technique with a silly name that professionals genuinely use. It is called rubber duck debugging.
You take a rubber duck, or a teddy, or a photograph of your cat, and you explain your program to it out loud, one line at a time, saying what each line does and why it is there.
Some way through, you stop mid sentence and say oh. Then you fix it.
It works because explaining forces you to slow down and say what each line really does, instead of what you assumed it did when you wrote it. Your head skims. Your mouth cannot.
The point: Saying your program out loud, slowly, to something that cannot help you, finds an astonishing number of bugs.
A worked example
Here is a program for making toast. It has three bugs in it. Find them before reading on.
Put the bread in the toasterWait 2 minutesSpread the butterTake the toast out of the toasterEat it
Bug one is a missing step: nothing ever switches the toaster on, so it waits two minutes beside cold bread. Bug two is wrong order: line 3 spreads butter on toast that is still inside the toaster. Bug three is a missing step again, since nobody ever got the butter or a knife.
Here is the fixed version.
Put the bread in the toasterPush the lever down to switch it onGet a plate, a knife and the butterWait until the toast pops upTake the toast out and put it on the plateSpread the butter with the knifeEat it
Notice that line 4 changed from a counted wait to a conditional one. Two minutes might be wrong for a different toaster. Waiting until it pops is right for all of them.
Bugs that only happen sometimes
The nastiest bugs are the ones that appear now and then.
A program that works with three names but fails with one. A game that is fine unless you press two keys at once. A quiz that breaks only when the answer is zero.
For these, the trick is to find the pattern. Write down every case that works and every case that fails, side by side, and stare at the two lists. What is different about the failures? Very often the answer is an edge: the first item, the last item, an empty list, or a number that is exactly on the boundary.
Try it: find the bug
This program should make the toy walk round a square and end up where it started. Trace it and find the mistake.
REPEAT 4FORWARD 3END REPEAT
Answer. There is no turn inside the loop, so the toy walks twelve squares in a straight line and never comes back. It is a missing step, and the fix is to add RIGHT after FORWARD 3, inside the loop. If you put the turn after END REPEAT instead, you get a straight line followed by one useless turn, which is a wrong order bug on top of the first one.
Common misconceptions
- Mistake: a bug means you are bad at this. Every professional writes buggy first versions. Finding bugs is the job, not the punishment for doing the job badly.
- Mistake: the computer made a mistake. Almost never. The computer did exactly what the instructions said, which is the whole reason bugs are findable.
- Mistake: change lots of things and one will fix it. Then you will not know which, and you may have added new bugs. One change, one test.
- Mistake: it worked once, so it works. Try it with nothing, with one item, with a hundred, and with something silly. Bugs live at the edges.
Summing up
- A bug is a mistake in instructions, and the word comes from a moth taped into a logbook in 1947.
- Debugging is most of programming, for everybody, at every level.
- The five kinds are wrong word, wrong order, missing step, wrong number, and wrong idea.
- Say what it does and what it should do, shrink the example, trace by hand, change one thing, test everything.
- Explaining your program out loud to a duck finds bugs that reading silently does not.
- Bugs that only happen sometimes usually live at an edge: the first, the last, the empty, or the exact boundary.
Sources
- Wikipedia contributors. (n.d.). Software bug. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Grace Hopper. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Debugging. Wikipedia. en.wikipedia.org
- Computer History Museum. (n.d.). Timeline of computer history. Computer History Museum. computerhistory.org
- Key terms
- Bug
- A mistake in a program that makes it do the wrong thing.
- Debugging
- Finding and fixing bugs, which is most of what programmers do.
- Trace
- Following a program by hand, line by line, to see where it goes wrong.
- Edge case
- An unusual input such as nothing at all, one item, or a number right on the boundary.
- Rubber duck debugging
- Explaining your program out loud to something that cannot help, which makes you notice the mistake.
- Test
- Running a program on purpose to see whether it does what it should.
Module 3: Thinking Like a Programmer
Cutting a big job into small ones, spotting when you have solved something before, and following a method that gets the answer every time.
Breaking a Big Job into Small Ones
- Split a large task into parts that can each be finished and checked on their own.
- Test a split by asking whether somebody else could do one piece without you.
- Split one of the pieces again when it turns out to be too big.
Forty seven things on the bedroom floor
Somebody says tidy your room.
You stand in the doorway. There are books on the floor, a jumper on the chair, three socks that do not match, a plate, some Lego, a wet towel and a school bag with everything falling out of it.
Nothing happens. It is not that you are refusing. It is that tidy your room is not an instruction you can start, because there is no first step in it.
Key idea: A job you cannot start is usually not too hard. It is too big.
Decomposition
Programmers have a long word for cutting a big job into small ones: decomposition. It means exactly what tidy your room needs.
Watch what happens when you split it.
- Put all the books on the shelf.
- Put all the dirty clothes in the basket.
- Put all the toys in the box.
- Take the plate and the cup to the kitchen.
- Put the rubbish in the bin.
- Make the bed.
Every single one of those can be started immediately and finished in a few minutes, and when it is finished you can see that it is finished. That is the difference.
Four reasons programmers do this constantly
- You can start. A small piece has an obvious first move.
- You can tell when it is done. The books are on the shelf or they are not.
- You can test it on its own. If the books end up in the wrong place, you know which piece to look at.
- Somebody else can do a piece. This is how teams of hundreds build one program without every person understanding all of it.
The point: Small pieces can be started, finished, checked and shared. Big ones cannot.
Splitting a game
Say you want to make a catching game. That is far too big a sentence to code.
| Piece | What it means | Done when |
|---|---|---|
| The background | Draw or choose the picture behind everything | Something appears behind the characters |
| The basket | Make it move left and right with the arrow keys | It moves and stops at the edges |
| The falling apple | Make it start at the top and fall | It reaches the bottom and starts again |
| Catching | Notice when apple and basket touch | Something happens on a touch |
| The score | Count catches and show the number | The number goes up when you catch one |
| Game over | Stop when lives run out | The game ends and says so |
Six pieces. Any one of them could be built and tested on its own, in any order. And if the score does not go up, you already know that the score piece is where to look, not the whole game.
Three ways to cut
There is more than one way to split something, and picking a good one matters.
- By part. A bicycle: wheels, frame, brakes, chain, seat. A game: characters, background, score.
- By step in time. Making a cake: weigh, mix, pour, bake, cool, ice. Each step finishes before the next starts.
- By kind of thing. Tidying: books, clothes, toys, rubbish. All the same job done to different objects.
For a jigsaw puzzle, most people split by kind: all the edge pieces first, then the sky, then the grass. That is decomposition being used by someone who has never heard the word.
The test for a good split
Ask two questions about each piece.
- Could I explain this piece to somebody else in one sentence? If it takes a paragraph, it is still too big.
- Would I know when it is finished? If not, it is too vague, which is the same problem as in the exact instructions lesson.
Compare make the game fun, which fails both tests, with make the basket move when the arrow keys are pressed, which passes both easily.
Remember: If you cannot say when a piece is finished, it is not a piece yet.
Splitting a piece again
Sometimes a piece is still too big, and you split it again.
Take make the bed from the tidying list. For a small child that is one job. For a very small child it is three.
- Pull the duvet up to the pillow.
- Straighten it so the edges hang evenly.
- Put the pillow at the top and the teddy on top of that.
You do not need to plan every level in advance. Split it once, start on a piece, and if that piece turns out to be a monster, split that one too. Programmers do this all day.
Why this matters beyond code
A school project, a long book, a tidy room, learning to ride a bike, a birthday party. Every one of them defeats people in exactly the same way and is fixed by exactly the same move.
A big car factory has teams for the engine, the doors, the wiring and the seats. Nobody in that building knows how to build an entire car alone, and the car gets built anyway.
Try it: split these
Write three to six pieces for each, then compare.
- Make a birthday card.
- Plan a picnic.
Sample answers. Card: fold the paper; draw the picture on the front; write the message inside; write the name on the envelope; decorate the edges. Picnic: decide who is coming; make a list of food; make the sandwiches; pack the bag with a blanket and drinks; choose the place; check the weather.
Your lists will not match these exactly and that is fine. Two people can split the same job differently and both be right. What matters is that every piece can be started and finished.
Common misconceptions
- Mistake: splitting is extra work before the real work. It is the fastest part of the work, and it is why the rest of the work becomes possible.
- Mistake: the pieces must all be the same size. They almost never are. Pack the bag might take four minutes and make the sandwiches twenty.
- Mistake: you have to plan every level before starting. Split once, start, and split again if a piece turns out to be a monster.
- Mistake: there is one correct way to split a job. By part, by step, or by kind of thing are all valid, and different splits suit different jobs.
What you now know
- Decomposition means breaking a big job into small ones.
- A job you cannot start is usually too big rather than too hard.
- Small pieces can be started, finished, tested and handed to somebody else.
- You can split by part, by step in time, or by kind of thing.
- A good piece can be described in one sentence and has a clear finish.
- If a piece is still too big, split that piece again.
Sources
- Wikipedia contributors. (n.d.). Decomposition (computer science). Wikipedia. en.wikipedia.org
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- CS Unplugged. (n.d.). Topics. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Key terms
- Decomposition
- Breaking a big job into smaller jobs that can each be finished.
- Piece
- One small part of a big job, with a clear finish.
- Sub problem
- A smaller problem hiding inside a larger one.
- Testable
- Able to be checked on its own, so you know whether it works.
- Team
- A group of people each building a different piece of the same program.
Patterns and Reusing What Works
- Spot a chunk of instructions that has been written more than once.
- Give a set of steps a name and use that name instead of the steps.
- Make one named recipe work in several sizes by giving it a number.
You already solved half of this
Two lessons ago you wrote a program that draws a square: REPEAT 4, FORWARD 10, RIGHT.
Now you want to draw a house, which is a square with a triangle on top. And after that a street of five houses.
The question is whether you write the square out again. Then again. Then five more times.
You do not, and the reason is the most powerful habit in programming: when you have solved something once, give the solution a name and use the name.
Key idea: Solve it once. Name it. Use the name from then on.
Naming a set of steps
You can teach a computer a new word. It looks like this.
TO DRAW SQUAREREPEAT 4FORWARD 10RIGHTEND REPEATEND
Nothing is drawn yet. That block is a recipe, not a meal. It sits there until somebody writes DRAW SQUARE, and at that moment all four sides get drawn.
A named set of steps like this has several names depending on the language: a procedure, a function, a subroutine, or in Scratch, a custom block. They all mean the same thing.
Now a street of five houses is short.
REPEAT 5DRAW HOUSEMOVE RIGHT 15END REPEAT
Three reasons this is worth doing
- Write it once. Five houses use one recipe.
- Fix it once. If the roof is wrong, you change the recipe and all five houses are fixed at the same moment. This is the big one.
- The name explains it. A program that says DRAW HOUSE, MOVE RIGHT, DRAW HOUSE can be understood at a glance. The same program written out in full is forty lines of FORWARD and RIGHT that nobody can read.
The point: The main gain is not typing less. It is having one place to fix and a name that says what is happening.
Copying is not reusing
There is a tempting shortcut: write the square once, then copy those four lines five times.
It works, at first. Then you notice the squares are too small and you have to find and change five separate copies. You will change four of them and miss one, and the fifth house will keep its wrong roof for weeks until somebody notices.
That is not a made up danger. It is one of the commonest sources of bugs in real software.
Remember: Copied code has to be fixed in every copy. Named code is fixed in one place.
One recipe, different sizes
What if you want a big square and a small square?
You do not need two recipes. You leave a gap in the recipe for a number to be handed in.
TO DRAW SQUARE sizeREPEAT 4FORWARD sizeRIGHTEND REPEATEND
Now DRAW SQUARE 10 gives a small one and DRAW SQUARE 40 gives a big one, from the same six lines. The number you hand in is called a parameter.
You already use this idea. A recipe for pancakes works for four people or eight; the recipe is the same and the number changes. Sing happy birthday to works for anybody, because the name is a gap you fill in.
Spotting the pattern in the first place
The hard part is not writing the recipe. It is noticing that two things are the same.
Look at this program and find what repeats.
FORWARD 5, RIGHT, FORWARD 5, RIGHT, FORWARD 5, RIGHT, FORWARD 5, RIGHTMOVE TO the next spotFORWARD 8, RIGHT, FORWARD 8, RIGHT, FORWARD 8, RIGHT, FORWARD 8, RIGHT
Two squares of different sizes. One recipe with a parameter handles both, and the whole thing becomes DRAW SQUARE 5, MOVE TO the next spot, DRAW SQUARE 8.
Three lines instead of eighteen, and now anybody reading it can see immediately what it does.
Problems that are secretly the same problem
Patterns also turn up between problems that look completely different.
- Sharing twelve sweets between four children.
- Cutting a cake into equal slices for four people.
- Putting twelve chairs into four equal rows.
Three different scenes and one piece of maths: twelve divided by four. If you can see that, you only have to learn the answer once.
Programmers hunt for this constantly. A shopping basket, a music playlist and a queue at a shop are all lists of things with things being added and removed, so the same solution works for all three.
Using work other people have already done
Nobody writes everything themselves. When a programmer needs to draw a circle, or sort a list, or work out what day of the week a date falls on, they use a set of ready made recipes that somebody else wrote and shared. Collections like this are called libraries.
This is not cheating and it is not lazy. It is the same reason you do not grind your own flour before making a sandwich. The interesting part of your program is the part nobody has written yet.
Try it: name the recipe
For each, decide what you would name and what would go inside the name.
- A program that draws four identical flowers in four corners.
- A program that says hello to Sam, then to Ali, then to Jo.
- A dance where you clap twice, spin, clap twice, spin, clap twice, spin.
Answers. One: a recipe called DRAW FLOWER, called four times, with the moving between corners left outside it. Two: a recipe called SAY HELLO with the name as a parameter, called three times with a different name each time. Three: a recipe called CLAP AND SPIN containing clap, clap, spin, then REPEAT 3 around it.
Common misconceptions
- Mistake: copying and pasting is the same as reusing. A copy has to be fixed in every place it was copied to. A name is fixed once.
- Mistake: a recipe has to be long to be worth naming. Two lines with a good name are often clearer than two lines without one, because the name says why they are there.
- Mistake: using other people's code is cheating. Every professional does it. The interesting part is the part nobody has written yet.
- Mistake: a recipe with a gap in it is complicated. A birthday song with a name in it is exactly this idea, and every four year old can handle it.
The takeaway
- When you have solved something, give the solution a name and use the name.
- A named set of steps is called a procedure, a function or a custom block.
- The biggest gain is that there is only one place to fix when it is wrong.
- A parameter is a gap in the recipe for a number or a word to be handed in.
- Problems that look different can be the same problem underneath.
- Using recipes other people wrote is normal, expected and sensible.
Sources
- Wikipedia contributors. (n.d.). Function (computer programming). Wikipedia. en.wikipedia.org
- Scratch Team, MIT Media Lab. (n.d.). Scratch: imagine, program, share. Massachusetts Institute of Technology. scratch.mit.edu
- BBC. (n.d.). Computer science, KS2 Computing. BBC Bitesize. bbc.co.uk
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Key terms
- Procedure
- A set of steps with a name, which you can use again by writing the name.
- Function
- Another word for a named set of steps.
- Custom block
- What Scratch calls a set of steps you have named yourself.
- Parameter
- A gap in a recipe for a number or word to be handed in when it is used.
- Reuse
- Using a solution you already have instead of writing it again.
- Library
- A collection of ready made recipes written by other people and shared.
Algorithms: Searching and Sorting
- Say what an algorithm is and give an example that has nothing to do with computers.
- Use a halving search to find a number from 1 to 100 in seven guesses.
- Sort a shuffled set of cards using a method you could write down for somebody else.
Seven guesses
Think of a number between 1 and 100. Do not say it.
Somebody who knows what they are doing will find your number in at most seven guesses, every single time, even though there are a hundred numbers to choose from. Not by luck. By method.
Here is the method. Guess 50. You say higher or lower. Guess halfway into whichever half is left. Say higher or lower again. Keep halving.
The list of possible numbers goes 100, then 50, then 25, then 13, then 7, then 4, then 2, then 1. That is seven halvings, and the number is cornered.
Key idea: A good method beats a fast guesser. This lesson is about methods that always work.
What an algorithm is
An algorithm is a set of steps that solves a problem, works every time, and finishes.
Those three parts all matter. Steps that sometimes work are not an algorithm. Steps that never end are not an algorithm either.
Most algorithms have nothing to do with computers.
- A recipe for pancakes.
- The written method for adding two three digit numbers in columns.
- The instructions for tying a shoelace.
- How to look a word up in a dictionary.
Long division is an algorithm somebody had to invent, and you can do it because you learned their steps.
Looking for one thing among many
Say you have a hundred cards face down with numbers on them, and you want the card that says 73.
The obvious method is to turn them over one at a time, from the beginning, until you find it. This is called linear search, and it works on anything, in any order.
The cost is that it can be very slow. If 73 is the last card, you turn over all hundred. On average you turn over about fifty.
The faster way, and what it costs
Now suppose the cards are in order, smallest to largest.
Turn over the middle one. It says 40. Since 73 is bigger, every card before the middle can be thrown out, all fifty of them, in one move. Turn over the middle of what is left, and again, and again.
This is binary search, the same halving as the guessing game. Here is what it buys you.
| How many things | Linear search, worst case | Binary search, worst case |
|---|---|---|
| 10 | 10 checks | 4 checks |
| 100 | 100 checks | 7 checks |
| 1,000 | 1,000 checks | 10 checks |
| 1,000,000 | 1,000,000 checks | 20 checks |
Look at the last row for a moment. A million things, and twenty questions is enough. Every time you double the number of things, binary search needs exactly one more check.
But there is a price, and it is not optional: the things have to be in order first. Halving an unsorted pile tells you nothing, because there is no reason for the smaller ones to be on the left.
Remember: Binary search is enormously faster, and it only works on a sorted list.
You already use this
Look a word up in a dictionary and watch yourself. You do not start at aardvark. You open it near the middle, see you are too far on, and jump back. Three or four jumps and you are on the right page.
Phone books, indexes, library shelves and the contents page of a book all exist so that people can do binary search instead of linear search. Putting things in order is work that is done once so that finding them is quick forever afterwards.
Putting things in order
So how do you sort a shuffled pile in the first place? Here is a method you can write down.
Selection sort.
- Look through the whole pile and find the smallest card.
- Put it at the start of a new row.
- Look through what is left and find the smallest of those.
- Put it next in the row.
- Repeat until the pile is empty.
It always works, it always finishes, and you could hand it to somebody who had never sorted anything. That makes it an algorithm rather than a knack.
It is also slow, because finding the smallest means looking at everything left in the pile, every single time. There are cleverer sorting methods, some of which split the pile in half and sort each half, and for a thousand cards the difference is enormous. For ten cards on a kitchen table nobody cares.
Why the method matters more than the machine
People assume a slow program just needs a faster computer. Sometimes that is true. Often it is not, and the numbers explain why.
Searching a million sorted names with binary search takes about twenty checks. Searching them one at a time takes up to a million. Buying a computer twice as fast still leaves you doing half a million checks, which is twenty five thousand times worse than just using a better method on the old machine.
Why this matters: Choosing a better algorithm often beats buying a faster computer, and it costs nothing.
Try it: count the questions
Work each one out before you check.
- You are guessing a number from 1 to 100 and you have been told higher than 50. What should you guess next?
- Why can you not use halving on a shuffled pile of cards?
- Roughly how many halvings does it take for a thousand things?
- You are looking for one particular sock in an unsorted drawer. Which method are you using?
Answers. One: 75, the middle of what is left, since guessing 51 would only rule out one number if you are wrong. Two: because there is no reason the smaller ones are on one side, so an answer of higher tells you nothing about where to look. Three: ten, since doubling adds one check each time and a thousand doubles from one about ten times. Four: linear search, and it is the right choice, because sorting the drawer first would take far longer than looking through it.
Common misconceptions
- Mistake: an algorithm is a computer thing. Long division, shoelaces and pancakes are all algorithms. Computers just follow them very fast.
- Mistake: binary search works on any list. Only on a sorted one. This is the single most common mistake people make with it.
- Mistake: a faster computer fixes a slow method. Doubling the speed halves a million checks to half a million. A better method turns it into twenty.
- Mistake: sorting is always worth it. If you are looking for one thing once, just look. Sorting pays off when you will search the same collection many times.
Looking back
- An algorithm is a set of steps that solves a problem, works every time, and finishes.
- Linear search checks everything in turn and works on any pile.
- Binary search halves the pile each time and needs the pile to be in order.
- A million sorted items can be searched in about twenty checks.
- Selection sort finds the smallest, puts it first, and repeats.
- A better method usually beats a faster machine, and costs nothing.
Sources
- Wikipedia contributors. (n.d.). Binary search. Wikipedia. en.wikipedia.org
- CS Unplugged. (n.d.). Searching algorithms. University of Canterbury Computer Science Education Research Group. csunplugged.org
- CS Unplugged. (n.d.). Sorting networks. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Wikipedia contributors. (n.d.). Algorithm. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Sorting algorithm. Wikipedia. en.wikipedia.org
- Key terms
- Algorithm
- A set of steps that solves a problem, works every time, and finishes.
- Linear search
- Checking things one at a time from the start until you find what you want.
- Binary search
- Halving a sorted list each time until only the answer is left.
- Sorted
- Arranged in order, which is what binary search needs.
- Selection sort
- Sorting by repeatedly finding the smallest thing left and putting it next.
- Worst case
- The most checks a method could ever need, rather than the luckiest.
Module 4: How Computers Talk to Each Other
The wires under the sea, the way a message is cut up and sent in pieces, what a web page is made of, and how to look after yourself and other people online.
What the Internet Actually Is
- Describe the internet as machines, cables and agreed rules rather than as a cloud.
- Explain what a packet is and why a message is cut into pieces.
- Say what an address does and why names have to be turned into numbers.
The first message was two letters long
On 29 October 1969, a student at the University of California in Los Angeles sat at a terminal and tried to send a word to a computer at Stanford Research Institute, about six hundred kilometres away. The word was LOGIN.
He typed L. The other end confirmed L. He typed O. Confirmed. He typed G, and the system crashed.
So the first message ever sent between two computers on the network that became the internet was LO. They fixed it and finished the word about an hour later.
Key idea: The internet is not magic and it was not always there. It was built by people, starting with two machines and a phone line.
What it is made of
The internet is three things and nothing else.
- Machines. Phones, laptops, servers, and the boxes in between.
- Connections. Mostly cables, plus some radio for the last few metres.
- Agreed rules. Everyone uses the same way of addressing and packaging messages.
The third one is the surprising one, and it is the reason any two machines in the world can talk. Not because they are the same, but because they follow the same rules about what a message looks like.
The cables under the sea
Here is a fact that surprises most people, including plenty of adults.
Almost everything that crosses an ocean on the internet goes through cables lying on the seabed. Not satellites. Cables, some of them thinner than a garden hose, carrying pulses of light through strands of glass.
There are hundreds of them, and ships have to be sent out to repair them when one is damaged by an anchor or an earthquake. A message from Britain to Australia is a flicker of light travelling along the bottom of the sea.
So when somebody says something is in the cloud, they mean it is on a computer in a big building somewhere, owned by a company, connected by cables. There is no cloud. There is a warehouse full of machines with very loud fans and a floor that has to be strong enough to hold them.
Remember: The cloud is somebody else's computer in a building, reached by wires.
Everything needs an address
Post cannot be delivered without an address, and neither can data.
Every machine on the internet has a number called an IP address. It looks something like 192.168.0.14. It says which machine, in the same way a house number and street say which door.
But nobody wants to remember numbers, so we use names instead, and there is a system whose whole job is turning a name into the right number. It is called the Domain Name System, or DNS, and it works like an enormous shared phone book.
Type a website name and the very first thing your machine does, before anything else, is ask what number goes with that name.
Why your message is cut into pieces
Now the clever part, and the part that makes the internet different from a phone call.
Your message is not sent as one lump. It is chopped into small pieces called packets. Each packet carries a bit of the message, the address it is going to, the address it came from, and a number saying which piece it is.
The packets are sent off separately. They can take different routes. They can arrive out of order. At the far end, the receiving machine puts them back in number order and rebuilds the message. If one never turns up, it asks for that one to be sent again.
Imagine posting a jigsaw to a friend in fifty envelopes, each with a number on it. Some go by van and some by train, they arrive over two days in a jumble, and your friend lays them out by number and has the whole picture.
Why bother chopping it up?
Three good reasons, and they are all about sharing.
- Nobody blocks the road. If one person sent a huge file in one piece, everybody else would wait. Packets take turns.
- Damage can be routed round. If a cable is cut, packets go a different way. The message still arrives. This was one of the original design goals.
- Only the lost bit is re-sent. Lose one packet out of five hundred and you re-send one packet, not the whole thing.
The point: Packets let millions of conversations share the same cables without anybody having to wait for anybody else to finish.
Routers, and the little that each one knows
Between you and the machine you are talking to there are usually somewhere between ten and thirty boxes called routers.
A router does one thing. It looks at the address on a packet and decides which cable to push it down next, to get it a bit closer. It does not know the whole route. It does not know what the message says. It knows the next hop.
It is like asking directions from a series of strangers, where each one only knows the way to the next junction, and it works.
Asking and answering
Most of what happens on the internet is one machine asking and another answering.
The asking machine is called the client, which is usually the phone or laptop in front of you. The answering machine is the server, which is a computer whose whole job is sitting in a building waiting for requests and sending back replies.
A server is not a special magic device. It is a computer with no screen, kept somewhere cool, that never gets switched off.
The internet and the web are not the same thing
People use these words as if they mean the same. They do not.
The internet is the roads: the machines, cables and rules that move data anywhere.
The web is one kind of traffic on those roads: pages you look at in a browser. Email is different traffic. A video call is different traffic again. All of them use the same roads.
The internet started in 1969. The web was invented twenty years later, which is the subject of the next lesson.
Try it: work these out
- You send a photo to a cousin overseas. Does it travel in one piece?
- A cable under the Atlantic is damaged. Does the message fail?
- Why do we need DNS at all?
- Is a message sent by satellite most of the time?
Answers. One: no, it is cut into many packets, which may take different routes and arrive out of order. Two: usually not, because the routers send packets a different way, though everything may get slower. Three: because machines need numbers and people remember names, so something has to translate. Four: no, almost all long distance traffic goes through cables on the seabed.
Common misconceptions
- Mistake: the internet is wireless. Wi-Fi is only the last few metres from your device to a box in the room. After that it is cable, most of it in the ground or under the sea.
- Mistake: the cloud is in the sky. It is a building full of computers with big fans, owned by a company, connected by cables.
- Mistake: the internet and the web are the same thing. The internet is the roads. The web is one kind of traffic on them, and it arrived twenty years later.
- Mistake: a message travels in one piece along one route. It is cut into numbered packets that may travel separately and are reassembled at the far end.
Putting it together
- The first message on the network that became the internet, in 1969, was LO, because the system crashed.
- The internet is machines, connections and agreed rules.
- Almost all long distance traffic runs through cables on the seabed.
- Every machine has an IP address, and DNS turns names into those numbers.
- Messages are cut into numbered packets that can take different routes and are rebuilt at the end.
- Routers only know the next hop, and clients ask while servers answer.
Sources
- Internet Society. (n.d.). A brief history of the internet. Internet Society. internetsociety.org
- Wikipedia contributors. (n.d.). ARPANET. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Packet switching. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Domain Name System. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Internet. Wikipedia. en.wikipedia.org
- Key terms
- Internet
- The machines, cables and agreed rules that move data around the world.
- Packet
- A small numbered piece of a message, carrying its own address.
- IP address
- The number that says which machine, like a house number for computers.
- DNS
- The system that turns a name people can remember into the number machines need.
- Router
- A box that reads a packet's address and sends it one hop closer to where it is going.
- Server
- A computer whose job is waiting for requests and sending back answers.
- Client
- The machine doing the asking, usually the one in front of you.
What a Website Is Made Of
- Name the three languages a web page is built from and say what each one is for.
- Read a few lines of HTML and say what would appear on the screen.
- Explain what a browser does when you type an address.
Vague but exciting
In March 1989 a scientist called Tim Berners-Lee, working at a physics laboratory in Switzerland, handed his manager a document proposing a way to link documents on different computers together.
His manager wrote two words at the top of it: vague but exciting. He did not say no, and that document became the World Wide Web. The first website went online in 1991.
Everything you have ever looked at in a browser comes from that idea: files, on different machines, with links pointing at each other.
Key idea: A web page is a file. It is not a picture of a page, it is a set of instructions for building one.
A page is text with labels
Open any web page and what actually arrived at your machine is a text file, with labels wrapped round the parts to say what they are.
The labels are called tags, and they go in angle brackets. Here is a whole tiny page.
<h4>My Dog</h4><p>My dog is called Biscuit. He is very fast.</p><ul><li>He is brown.</li><li>He hates the postman.</li></ul>
Read it out and you can see what appears: a heading saying My Dog, a paragraph underneath it, and a bulleted list of two things.
Notice the pattern. Most tags come in pairs. One opens, and the closing one has a slash in it. Whatever is between them is the thing being labelled.
This language is called HTML, and it does one job: it says what each piece of content is. A heading. A paragraph. A list. A link. A picture goes here.
Three languages, three jobs
| Language | Job | Like |
|---|---|---|
| HTML | What the content is and how it is organised | The bones and the words |
| CSS | What it looks like: colour, size, spacing, position | The clothes |
| JavaScript | What it does when you touch it | The muscles |
A page with only HTML still works. It looks plain, like an old fashioned typed document, and every word is there and every link works.
Add CSS and it becomes blue, or spaced out, or arranged in columns. Nothing new is said, it is just dressed.
Add JavaScript and it starts reacting: a menu opens when you click it, a number counts up, a form tells you that you missed a box. That is the events lesson, running inside a page.
The point: Content, appearance and behaviour are kept in three separate places on purpose, so each one can be changed without breaking the others.
What the browser does
Type an address and press enter, and a lot happens in under a second.
- The browser asks DNS what number goes with that name.
- It sends a request to that machine, saying which page it wants.
- The server sends back the HTML file, in packets.
- The browser reads the HTML and notices it needs other things too: a stylesheet, some pictures, maybe some JavaScript.
- It asks for each of those as well, often from several different machines.
- It works out where everything goes and draws the page.
The browser is doing the assembling. The server sent parts, not a picture. That is why the same page can look different on a phone and on a laptop: the parts are the same and the browser lays them out to fit.
Reading an address
An address has parts, and each one means something.
- https is the rule being used, and the s means the connection is encrypted, so somebody in the middle cannot read it.
- The domain name is which machine, like example.org.
- The path is which page on that machine, like the part after the slash.
The s in https matters. On a page where you type anything private, it should be there.
Links: the thing that made it a web
A link is one HTML tag with an address in it. Click it and the browser goes and asks for that page instead.
That single idea is why it is called a web rather than a library. Any page can point at any other page on any machine in the world, and nobody has to ask permission first. The whole thing is held together by pointing.
You do not need special software
Here is something worth knowing. A web page is just text. You can write one in the simplest text editor on any computer, save it with a name ending in .html, and open it in a browser. It will work. Nothing needs to be bought or installed.
That is unusual and it is deliberate. Berners-Lee and the group that followed him gave the whole thing away, with no charge and no permission needed, which is a large part of why it spread.
Try it: read the HTML
What appears on screen for each of these?
<p>Hello</p><h4>Shopping</h4>followed by<ul><li>Milk</li><li>Eggs</li></ul><p>Hellowith no closing tag
Answers. One: the word Hello as an ordinary paragraph. Two: the word Shopping as a heading, then a bulleted list showing Milk and Eggs. Three: browsers are very forgiving and will usually show Hello anyway, guessing at what you meant, which is unusual, because most languages refuse to guess. It is still a mistake, and in a longer page a missing closing tag can push the rest of the page into the wrong place.
Common misconceptions
- Mistake: a web page is a picture that gets sent to you. Text and instructions get sent, and your browser builds the page. That is why it can rearrange itself to fit a phone.
- Mistake: HTML is a programming language. It describes what things are. It cannot make a decision, count, or repeat anything. JavaScript is the programming language on a page.
- Mistake: you need to buy software to make a website. A plain text editor and a browser are enough, and both are already on the machine.
- Mistake: everything on a page comes from one place. A single page often pulls parts from several different machines, which is why some bits appear later than others.
What to remember
- The web was proposed in 1989 by Tim Berners-Lee, and the first site went up in 1991.
- A web page is a text file with tags that label what each piece of content is.
- HTML is the content, CSS is the appearance, JavaScript is the behaviour.
- The browser fetches the parts and assembles the page itself.
- An address names the rule, the machine and the page, and the s in https means encrypted.
- Links let any page point at any other page, which is what makes it a web.
Sources
- Wikipedia contributors. (n.d.). World Wide Web. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Tim Berners-Lee. Wikipedia. en.wikipedia.org
- Mozilla. (n.d.). Getting started modules. MDN Web Docs, Learn web development. developer.mozilla.org
- Wikipedia contributors. (n.d.). HTML. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Web page. Wikipedia. en.wikipedia.org
- Key terms
- HTML
- The language that says what each piece of content on a page is.
- Tag
- A label in angle brackets that marks a piece of content, usually in an opening and closing pair.
- CSS
- The language that decides how a page looks: colour, size, spacing and position.
- JavaScript
- The programming language that makes a page react when you do something.
- Browser
- The program that fetches the parts of a page and assembles them on your screen.
- Link
- A tag containing an address, which sends the browser to another page.
- Domain name
- The part of an address that says which machine to ask.
Staying Safe and Kind Online
- List what counts as personal information and say why it should not be given out.
- Build a strong password out of three random words and explain why length beats symbols.
- Say what to do about an unkind message, a stranger, or something that seems too good to be true.
A message that wants you to hurry
A message arrives. It says your account will be closed in twenty four hours unless you click a link and type your password.
Everything about that message is designed to do one thing: stop you thinking. It gives you a deadline. It threatens you with losing something. It puts the button right there, ready.
Real companies do not do this. The message is a trick, and the trick has a name: phishing, spelled with a ph, because you are the fish.
Key idea: Anything online that tries to make you hurry is trying to stop you thinking. Slow down, and go and tell somebody.
What counts as personal information
Some things about you should not be handed out to people you do not know.
- Your full name.
- Where you live, including your street.
- Which school you go to.
- Your phone number and your family's phone numbers.
- Your date of birth.
- Where you will be, and when.
- Passwords, obviously, and anybody else's too.
Pictures count as well, and this catches people out. A photo in school uniform says which school. A photo of the front of the house says the street and often the number. A photo of a birthday cake says the date.
The rule is simple: if it would help a stranger find you in real life, it is personal.
Passwords: long beats complicated
Most people think a good password looks like a mess of symbols. Length matters more.
A short password with a couple of odd characters can be worked out by a computer trying millions of guesses. A long one made of several unrelated words takes very much longer, because there are so many more possibilities to get through.
So the best kind is three or four random words that have nothing to do with each other, joined together. Something like purple hedgehog cactus lamp. It is long, it is easy to picture, and it does not appear in any book.
Three more rules go with it.
- Never share it. Not with a friend, not with somebody who says they work for the game, not with anybody who asks in a message. Nobody legitimate ever needs your password.
- Do not use the same one everywhere. If one place is broken into, everything else with the same password is open too.
- Do not use things about you. Your name, your pet, your birthday and your football team are the first things anybody guesses.
Remember: A long password of unrelated words beats a short one full of symbols, and it is far easier to remember.
People online are not always who they say
Here is the hardest thing on this page, and it needs saying plainly.
Online, a person can type anything about themselves. Somebody who says they are ten, and likes the same game as you, and has the same favourite colour, might be. They might not be.
Most people are fine. But you cannot tell from a message, and neither can any adult, which is exactly why the rules are what they are.
- Never agree to meet somebody you only know online.
- Never send photographs of yourself to somebody you only know online.
- If anybody asks you to keep something secret from your parents, tell your parents that day. This is the biggest warning sign there is.
- If somebody is being strange, uncomfortable or too friendly too fast, stop replying and tell a grown-up.
You will not be in trouble for telling. Telling is the correct move, always, and it is not tale telling, it is the same as saying that somebody is hurt.
Anyone can put anything on the internet
Nothing checks the internet for truth before it goes up. A page can be made by an expert, a company selling something, somebody having a joke, or a person who is simply wrong.
Three questions sort out most of it.
- Who made this, and why? A museum, a government health site or a university is a different thing from an advert or a video with no name on it.
- Does anywhere else say the same thing? One place saying something is a claim. Three unconnected places saying it is better evidence.
- Is it trying to make me feel something strongly? Amazing, shocking and terrifying things spread faster than true things, and people know that and use it.
Pictures need the same treatment. Photographs have been edited for a hundred years, and computers can now produce pictures of things that never happened. A picture is a claim too.
The point: On the internet, believing something needs a reason. Who made it, does anyone else agree, and what does it want from me.
Being the kind one
There is a real person at the other end of every message. They are not a character in a game.
Two rules cover almost everything.
- Do not type what you would not say to somebody's face, in front of your family.
- Assume everything you send is permanent and public. Deleted usually means hidden from you, not gone. Anybody can screenshot anything in a second.
Being unkind online feels smaller than being unkind in person, because you cannot see the face. That is exactly why it does more damage: it is easier to do, it lasts, and it can be seen by hundreds of people rather than one.
If it happens to you
If somebody sends you something unkind, threatening, or that makes you feel horrible, here is the order.
- Do not reply. A reply is what the sender wants and it always makes it worse.
- Keep the evidence. Take a screenshot or leave the message where it is. Do not delete it, even though you want to.
- Tell a grown-up you trust. A parent, a teacher, anyone. Today, not next week.
- Block and report. Every game, app and site has a way to do this, and adults can help you find it.
And one more, which matters just as much: if you see it happening to somebody else, say something kind to them privately, and tell an adult. Most people who are being bullied online say that nobody stepped in.
Try it: what would you do?
- Somebody in a game asks which school you go to.
- A message says you have won a prize and just need to type your address to claim it.
- A friend asks for your password so they can play on your account.
- Somebody sends a nasty message about a classmate and asks you to pass it on.
Answers. One: do not tell them, and mention it to a grown-up, because there is no good reason for that question. Two: it is a scam. Real prizes do not need your address typed into a link you did not go looking for. Three: no, even for a friend, because the rule has to be simple to be any use. Four: do not pass it on, do not reply to it, keep it, and tell an adult. Passing it on makes you part of it.
Common misconceptions
- Mistake: deleting a message makes it gone. It usually just hides it from you. Copies and screenshots survive.
- Mistake: if it is on a website, it is true. Nothing checks the internet before publication. Ask who made it and whether anyone else agrees.
- Mistake: a good password is short and complicated. Length wins. Three unrelated words beat a short jumble of symbols and are far easier to remember.
- Mistake: telling a grown-up will get me into trouble or get the tablet taken away. Adults would far rather be told early. Not telling is what lets a small problem become a big one.
Where this leaves us
- Anything that pushes you to hurry is trying to stop you thinking.
- Personal information is anything that would help a stranger find you, and photographs count.
- Long passwords made of unrelated words are strongest, and are never shared with anybody.
- People online can claim to be anyone, so never meet, never send photos, and never keep secrets from your parents.
- Believing something online needs a reason: who made it, who else says it, what does it want.
- Do not reply, keep the evidence, tell an adult, block and report.
Sources
- StopBullying.gov. (n.d.). What is cyberbullying. U.S. Department of Health and Human Services. stopbullying.gov
- StopBullying.gov. (n.d.). Prevent cyberbullying. U.S. Department of Health and Human Services. stopbullying.gov
- Federal Trade Commission. (n.d.). How to recognize and avoid phishing scams. FTC Consumer Advice. consumer.ftc.gov
- Federal Trade Commission. (n.d.). How websites and apps collect and use your information. FTC Consumer Advice. consumer.ftc.gov
- Common Sense Media. (n.d.). Age based media reviews for families. Common Sense Media. commonsensemedia.org
- Key terms
- Personal information
- Anything that would help a stranger find you in real life.
- Password
- The secret that proves an account is yours. Long is stronger than complicated.
- Phishing
- A fake message that tries to trick you into giving away a password or details.
- Scam
- A trick that offers something too good to be true in order to take something from you.
- Cyberbullying
- Using messages, posts or games to hurt somebody on purpose.
- Block
- To stop somebody from being able to message you.
- Report
- To tell the people who run a site or game that somebody is behaving badly.
Module 5: Inside the Machine, and Out Into the World
How everything a computer holds is really just switches that are on or off, and what people actually build once they can write instructions.
Ones and Zeros: How a Computer Stores Everything
- Explain what a bit is and how many things a set of bits can represent.
- Turn a number under 32 into binary, and read a binary number back.
- Say how letters, pictures and sounds all end up as numbers.
Billions of switches, and none of them can say maybe
Inside the chip in a phone there are billions of tiny switches. Each one is either on or off. There is no halfway, no nearly, and no maybe.
Which raises an obvious question. If all a computer has is switches that can only be on or off, how does it hold a photograph of your grandmother, a song, and the whole of a book?
The answer is the subject of this lesson, and it is one of the most satisfying things in computing, because you can do it on paper with five bits of card.
Key idea: Everything a computer stores is a number, and every number is a pattern of switches.
A bit is one switch
One switch is called a bit. We write on as 1 and off as 0.
One bit can hold two things. Yes or no. On or off. Left or right.
Two bits can hold four, because there are four patterns: 00, 01, 10, 11. Three bits give eight patterns. Each new bit doubles it.
| Bits | Different patterns |
|---|---|
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 8 | 256 |
Eight bits together are called a byte, and a byte can hold 256 different patterns. Remember that number, because it turns up constantly.
Counting with cards
Cut five squares of card. On the first draw 1 dot, then 2 dots, then 4, then 8, then 16. Lay them in a row with 16 on the left and 1 on the right.
Now the rule. A card is either face up, showing its dots, or turned over, showing nothing. To make a number, turn cards over until the dots you can see add up to it. Face up is 1, face down is 0.
Make 13. Start from the left. Is 16 too big? Yes, turn it down. Is 8 needed? Yes, leave it up, and 13 take away 8 leaves 5. Is 4 needed? Yes, and 5 take away 4 leaves 1. Is 2 needed? No. Is 1 needed? Yes.
So 13 is 8 plus 4 plus 1, and the cards read up, up, down, up if you write them from 8, or as a full five card row: 0 1 1 0 1.
Try 21. It is 16 plus 4 plus 1, so 1 0 1 0 1. Try 31. Every card is up: 1 1 1 1 1. Try 0. Every card is down.
The point: Binary is ordinary counting where each place is worth double the one to its right, instead of ten times.
Why the doubling
Look at our normal numbers. In 305, the places are worth 100, 10 and 1, each ten times the one on its right, and each place holds a digit from 0 to 9.
In binary the places are worth 16, 8, 4, 2 and 1, each double the one on its right, and each place holds a digit that can only be 0 or 1.
That is the whole difference. Binary is not a strange kind of maths. It is the same counting with two symbols instead of ten, and computers use it because a switch has two positions.
Letters, from numbers
So numbers are patterns of bits. But a computer holds words too.
The answer is that everybody agreed on a list. Each letter was given a number, and the list is called ASCII.
- Capital A is 65, B is 66, C is 67, and so on up to Z at 90.
- Small a is 97, b is 98, and so on.
- A space is 32.
So the word CAB is stored as three numbers: 67, 65, 66. And each of those is a pattern of bits, since 65 is 64 plus 1, which as eight bits is 0 1 0 0 0 0 0 1.
There is nothing letter shaped anywhere in the machine. There is a number, and an agreement about what that number means. Change the agreement and the same bits mean something else entirely, which is why a file opened with the wrong program comes out as nonsense.
Pictures, from numbers
Look very closely at a screen, or at a photo zoomed right in, and it breaks into little coloured squares. Each square is a pixel.
Every pixel holds three numbers: how much red, how much green, and how much blue, each from 0 to 255. That is one byte each.
- 255 red, 0 green, 0 blue is bright red.
- 255, 255, 255 is white, because all three are full.
- 0, 0, 0 is black.
- 255, 255, 0 is yellow, because red and green light together look yellow.
A photograph a million pixels wide and high needs three million numbers, and that is why photographs make big files.
Sounds, from numbers
Sound is air wobbling. A microphone measures how far the air has been pushed, and writes down a number.
Then it does it again, thousands of times per second. A recording is a very long list of measurements, and a speaker reads the list back and pushes the air the same way.
So a song is a list of numbers. A photo is a list of numbers. A book is a list of numbers. And every number is a row of switches.
Remember: Words, pictures and sounds are all turned into numbers first. That is the only thing a computer can actually keep.
Try it: convert these
Use the cards 16, 8, 4, 2 and 1, and always start from the biggest.
- Write 6 in binary.
- Write 19 in binary.
- What number is 1 1 0 0 0?
- What number is 0 0 1 1 1?
- How many different patterns can 8 bits make?
Answers. One: 6 is 4 plus 2, so 0 0 1 1 0. Two: 19 is 16 plus 2 plus 1, so 1 0 0 1 1. Three: 16 plus 8, which is 24. Four: 4 plus 2 plus 1, which is 7. Five: 256, because each bit doubles it and eight doublings from one gives 256.
Common misconceptions
- Mistake: binary is a different kind of maths. It is the same counting with two symbols. Each place is worth double the one to its right instead of ten times.
- Mistake: a computer stores letters as letters. It stores a number and everybody agrees what that number means. There is nothing letter shaped inside.
- Mistake: 0 means nothing is stored. A 0 is a real value, exactly as meaningful as a 1. The switch being off is part of the pattern.
- Mistake: one bit can hold a letter. One bit holds two possibilities. A letter needs a byte, which is eight bits and 256 possibilities.
The short version
- A bit is one switch, written as 1 for on and 0 for off.
- Each extra bit doubles the number of patterns, so eight bits, one byte, give 256.
- Binary place values are 1, 2, 4, 8, 16 and so on, and you build a number from the biggest downwards.
- Letters are numbers by agreement, with capital A at 65 in ASCII.
- A pixel is three numbers from 0 to 255, for red, green and blue.
- Sound is a long list of measurements taken thousands of times a second.
Sources
- CS Unplugged. (n.d.). Binary numbers. University of Canterbury Computer Science Education Research Group. csunplugged.org
- Wikipedia contributors. (n.d.). Binary number. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). ASCII. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Bit. Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Pixel. Wikipedia. en.wikipedia.org
- Key terms
- Bit
- One switch, which is either on, written 1, or off, written 0.
- Byte
- Eight bits together, which can make 256 different patterns.
- Binary
- Counting with only two symbols, where each place is worth double the one to its right.
- ASCII
- An agreed list giving every letter and symbol a number, with capital A at 65.
- Pixel
- One small coloured square of a picture, stored as three numbers.
- Place value
- What each position in a number is worth: 1, 2, 4, 8, 16 in binary.
What People Build With Code
- Give five examples of things code is used for that are not games.
- Explain why the people who write code have to think about who might be left out.
- Plan a small project of your own using the ideas from this course.
Twelve hundred and one
On 20 July 1969, with the lunar module a few minutes from the surface of the Moon, the guidance computer flashed an alarm: 1201. Then 1202. The astronauts asked what it meant. Mission control had seconds to answer.
It meant the computer had been given more work than it could do at once. And it did not crash, because the software had been written to handle exactly that. It threw away the least important jobs and kept the ones needed to land.
That software was built by a team at MIT led by Margaret Hamilton, who is often photographed beside the printed listings of it, a stack of paper as tall as she is. She is also one of the people who pushed for the phrase software engineering to be taken seriously, at a time when writing programs was not considered real engineering.
The landing worked because somebody had thought, years earlier, about what should happen when everything went wrong at the worst possible moment.
Key idea: Code matters most in the moments nobody planned for, which is why people think about them beforehand.
Where the code actually is
Most people think of games and apps. Those exist, and they are a small part of it.
| Field | What the code does |
|---|---|
| Space | Lands rovers on Mars and drives them, since a signal takes minutes to arrive |
| Medicine | Turns hundreds of scan slices into one picture a doctor can turn around |
| Weather | Runs a model of the atmosphere forward to predict tomorrow |
| Travel | Finds the shortest route out of millions of possible ones, in under a second |
| Film | Draws every frame of an animated film, and the crowd scenes in the live action ones |
| Access | Reads a screen aloud, adds subtitles, turns speech into text |
| Science | Sorts through telescope images and reads long strings of DNA |
| Music | Records, edits and layers sound, and makes instruments that do not exist |
Every single one of those is built from what you have learned in this course. A route finder is an algorithm. A scan viewer is decomposition and reuse. A screen reader is events. All of them contain loops and conditions and all of them were debugged for months.
The route finder, in one paragraph
Take the map app that finds a route. There might be millions of possible ways to get across a city, so checking them all one at a time would take longer than walking.
Instead it uses an algorithm that spreads out from the start, always going next to the place it can reach soonest, and stops when it arrives. That way it never has to look at most of the map at all.
It is the same lesson as binary search: a better method beats trying everything. Somebody worked that method out, and now it is in every phone.
Who gets left out
Here is a part of the job that does not get talked about enough.
If a website has small pale grey writing, some people cannot read it. If a video has no subtitles, deaf people cannot follow it. If a form insists on a two part name, people whose names do not work that way cannot sign up. If a game needs fast, precise finger movements, some players are shut out.
None of that is caused by anybody being unkind. It happens when the person building something imagines a user exactly like themselves.
Remember: The question every builder should ask is who this does not work for, and it has to be asked early, because it is expensive to fix late.
It is not one job
People imagine one person in a dark room typing. Real projects involve many people, and most of them are not writing code all day.
- Somebody works out what the thing should do at all, by talking to the people who will use it.
- Designers decide how it looks and how it feels to use.
- Programmers build it.
- Testers try very hard to break it, which is a real job and a satisfying one.
- Writers explain it.
- Somebody keeps it working after it is finished, which is usually the longest part.
And a huge number of people use a little code inside another job entirely: biologists, historians counting words in old books, farmers, accountants, musicians. Code is a tool, like writing. You do not have to be a novelist to find writing useful.
What you already have
Five ideas were built up in this course, and every programming language that exists is made of them.
- Sequence. One thing after another, in order.
- Loops. Doing something again without writing it again.
- Conditions. Choosing between two roads.
- Events. Waiting, and reacting when something happens.
- Debugging. Finding out why it did something else, calmly, one change at a time.
On top of those sit the habits: break it into pieces, name what you have solved, pick a better method, and check what happens at the edges.
Learning a language after this is mostly learning where the full stops go.
If you want to carry on
Nothing here is required, and none of it costs anything.
- Scratch, made by MIT, lets you drag blocks together to make games and animations. The blocks are named after exactly the ideas in this course.
- Code.org has short puzzle courses for this age group, including the Hour of Code.
- Paper still works. Design a game as an event table. Write an algorithm for a card trick. Trace a friend's instructions and find the bug.
Three pieces of advice from people who do this for a living. Make something small. Finish it, even if it is worse than you hoped. Show it to somebody, because a program nobody has ever used is a program whose bugs are all still in it.
Try it: plan something
Pick anything: a quiz about your family, a maze game, a program that tells you what to pack for a trip.
- Write one sentence saying what it does.
- Split it into four to six pieces.
- List the events it has to wait for.
- Find one thing that repeats, and describe it as a loop.
- Find one choice it has to make, and write it as IF and ELSE.
- Write down two things that could go wrong, and what should happen when they do.
That page is a design. Professionals produce almost exactly the same thing before they write anything, and step six is the one that separates a program that works in a demonstration from one that works in a house.
Common misconceptions
- Mistake: you have to be brilliant at maths. Some fields need heavy maths and most do not. Being careful, patient and clear matters far more.
- Mistake: programmers work alone. Almost all real software is built by teams, and explaining your work to other people is a large part of the job.
- Mistake: you need an expensive computer to start. Everything in this course was done with paper. Scratch and Code.org run in a browser and cost nothing.
- Mistake: code is mostly for games. Games are a small corner. Hospitals, weather, farms, films, telescopes and buses all run on code.
What you now know
- The Apollo landing software survived an overload in 1969 because somebody had planned for it.
- Code runs scanners, forecasts, routes, films, screen readers, telescopes and buses, not only games.
- A route finder uses a better method rather than checking every possibility, exactly like binary search.
- Builders have to ask early who their thing does not work for.
- Real projects need designers, testers, writers and maintainers, not only programmers.
- Sequence, loops, conditions, events and debugging are in every language there is, and you now have all five.
Sources
- Wikipedia contributors. (n.d.). Margaret Hamilton (software engineer). Wikipedia. en.wikipedia.org
- Wikipedia contributors. (n.d.). Apollo Guidance Computer. Wikipedia. en.wikipedia.org
- NASA. (n.d.). Mars 2020: Perseverance Rover. NASA Science. science.nasa.gov
- Code.org. (n.d.). Computer science for ages 5 to 11. Code.org. code.org
- Scratch Team, MIT Media Lab. (n.d.). Scratch: imagine, program, share. Massachusetts Institute of Technology. scratch.mit.edu
- Key terms
- Software
- The programs a computer runs, as opposed to the machine itself.
- Software engineering
- Building programs carefully enough that other people can rely on them.
- Accessibility
- Making something usable by people with different bodies, eyes, ears and hands.
- Tester
- A person whose job is to try to break a program before anybody else does.
- Design
- The plan for a program, written before the program is.
- Maintenance
- Keeping a program working after it is finished, usually the longest part of its life.