Skip to content
LumenaryAcademy
Start 45 min

What a computer does

Instructions, algorithms, and your very first programs in Python.

Code tested · 6AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Computer Scientist, Margaret · The Experimenter, Gideon · The Verifier

MotivationH

A fast, obedient machine

Look around you and count the computers. There is probably one in your pocket (a phone), and others hiding in places you would not call "computers" at all: inside a washing machine, a car, a bank card, a traffic light, a hearing aid.

What do all these machines have in common? Each one does exactly three things, and does them astonishingly well:

  1. It stores information: numbers, words, pictures, sounds, all kept as patterns of tiny electrical charges.
  2. It follows instructions, one simple step after another.
  3. It does this very fast and without getting tired or bored. A phone can carry out billions of simple steps every second, all day long, and it will do the ten-billionth step as carefully as the first.

That's it. A computer is not clever in the way a person is clever. It does not understand what a photograph shows or what a message means. What it has is speed, memory and perfect obedience. All of the cleverness comes from the instructions people give it, and writing those instructions is called programming.

This lesson is about what those instructions look like, why they must be so precise, and how to write your first ones in a language called Python. By the end you will have run several programs of your own, right here on this page.

IntuitionH

Algorithms: recipes with nothing left to guess

People have been writing down instructions for thousands of years. Think of how you might teach a friend to make a pot of Moroccan mint tea:

  1. Boil water.
  2. Rinse a spoonful of green tea leaves in the pot with a little hot water, and pour that water away.
  3. Add a handful of fresh mint and some sugar.
  4. Fill the pot with boiling water and let it stand for a few minutes.
  5. Pour from high above the glass, so that a little foam forms.

Or how a grandmother in Gujarat teaches the folding of a samosa, how a Ghanaian weaver follows a counted pattern of coloured threads, or how a teacher in Seoul shows a class the steps of long division. Each is a list of steps that, followed carefully, produces a result: an algorithm.

Definition— algorithm

An algorithm is a finite list of precise steps that, followed exactly, solves a problem or produces a result. Each step must be clear enough to carry out without guessing, and the steps must eventually come to an end.

Notice the word precise. A recipe for people can say "add sugar to taste" or "cook until golden", because a person fills in the gaps with experience and common sense. A computer has no common sense at all. It will do exactly what the instructions say, even when that is obviously silly.

Example— Instructions for a very literal robot

Imagine giving a robot the instruction "Put the kettle on." A person knows you mean "switch the kettle on to boil water". A perfectly literal robot might lift the kettle and put it on top of something, perhaps on your head. Now try "Fill the kettle with water." With how much water? From which tap? What if the kettle is already full? What if there is no kettle?

To write instructions a machine can follow, you have to answer every one of those questions in advance. That is the real work of programming: thinking so clearly about a task that nothing is left to guess.

Algorithms are built from just three kinds of step, and every program you will ever write uses these three:

  • Sequence: do this, then this, then this, in order. (Boil the water before pouring it.)
  • Choice: if something is true, do one thing; otherwise do another. (If the tea is too strong, add water.)
  • Repetition: do something again and again, until a condition is met. (Keep stirring until the sugar dissolves.)

You will meet choice and repetition properly in Decisions and loops. For now, sequence is enough to get started.

Analogy, not a formal construction

An algorithm is like the score of a piece of music. The score is not the music itself: it is a precise description that a musician can follow to make the music. In the same way, a program is not the result you want (a sorted list, a map route, a game). It is the precise description that a computer follows to produce it.

DefinitionsH

Programs, languages, input and output

An algorithm can be written in any language, including ordinary English or Swahili. But a computer cannot read ordinary language reliably, because ordinary language is full of double meanings. So we write algorithms for computers in special languages with strict rules.

Definition— program

A program is an algorithm written in a form a computer can carry out. Running (or executing) a program means making the computer follow its instructions.

Definition— programming language

A programming language is a language with exact rules of grammar (its syntax) and exact meanings, designed for writing programs. Python, JavaScript, C, Java and Rust are programming languages. The text of a program is often called its code or source code.

The chip at the heart of a computer, its processor, only understands very simple instructions written as numbers, such as "add these two numbers" or "if this number is zero, jump to that instruction". Programming languages let us write in something much closer to human language, and a translator program turns our code into the processor's instructions. You will see how, much later, in Compilers and interpreters.

Almost every program, large or small, has the same shape:

Definition— input, processing, output

A program takes input (information coming in), does some processing (follows its steps, using the input), and produces output (information going out).

InputProcessOutputkeys pressed, a photothe program's stepstext, sound, a picture
The shape of almost every program: information comes in, the program follows its steps, and results go out.
Worked examplesH

Input, process, output everywhere

Once you look for this shape, you see it everywhere:

Machine or appInputProcessingOutput
A pocket calculatorthe keys you pressdoes the arithmeticdigits on the screen
A mobile-money transferthe amount and the phone number you typechecks your balance, moves the money, records ita confirmation message to both phones
A map appwhere you are and where you want to gosearches through roads for a short routea route drawn on the map, spoken directions
A washing machinethe programme you choose, sensor readings of water level and temperaturedecides when to fill, heat, spin and draina motor turning, a pump running, a beep when it is done
A translation appa sentence in Spanishworks out a likely English versionthe English sentence

Input may be typed by a person, read from sensors (a thermometer, a camera) or received from other computers; output may be text on a screen, a motor turning or a message sent elsewhere. The middle part, the processing, is where the algorithm lives.

Example— A shopkeeper's algorithm

Amina runs a small shop in Mombasa. Each evening she starts from zero, goes through her notebook adding each sale, then subtracts what she spent on new stock. The input is her notebook; the processing is adding and subtracting, line by line; the output is one number, the day's profit. Written as a program, the same steps could do the job for a thousand shops in a second. Only the speed would change.

ExplanationH

Programming languages, and why Python

There are hundreds of programming languages. Some are designed to make programs run as fast as possible (C, C++, Rust), some to run inside web pages (JavaScript), some for phones (Swift, Kotlin), some for huge business systems (Java, C#). The good news is that the core ideas, values, decisions, loops, functions, lists, are the same in nearly all of them. Learn them well in one language and the next language is mostly new spelling.

This course uses Python. It was created by Guido van Rossum, a Dutch programmer, and first released in 1991 (the name comes from the British comedy show Monty Python's Flying Circus, not the snake). We chose it for honest reasons:

  • It is readable. Python code looks a lot like structured English, with few strange symbols, so beginners can focus on ideas instead of punctuation.
  • It is used for real work. Scientists use it to analyse telescope images and genetic data, companies use it to run websites and handle data, and nearly all research in machine learning is done with Python tools. You will use it all the way to the last lessons of this course.
  • It comes with a lot built in. Python's "batteries included" standard library, and a huge collection of free packages, mean you rarely start from nothing.

Python also has weaknesses. Its programs usually run more slowly than the same program in C or Rust, sometimes ten times more slowly or worse, which is why the speed-critical parts of popular Python tools are often written in a faster language underneath. For learning, and for much professional work, the trade-off is worth it: your time matters more than the computer's.

ComputationC

Your first programs

How the Run button works

Below are some boxes of Python code. Each has a Run button and an Edit button. When you press Run, the code runs inside your own web browser, on your own device. This works thanks to a project called Pyodide, which is the real Python interpreter (the program that reads and carries out Python code) translated into a form that browsers can run. Nothing you type is sent to a server, and the code runs in a closed-off "sandbox", so it cannot touch your files or harm your device.

The first Run may take a few seconds, because your browser has to load Python itself. After that, runs are quick. Press Edit to change the code, and then Run again to see what your change does. You cannot break anything: if you make a mess, reload the page and the original code comes back.

Saying hello

The tradition in programming is that your first program greets the world. Press Run:

python
print("Hello, world!")
print("Hola, mundo!")
print("Habari, dunia!")
print("你好,世界!")
print("नमस्ते दुनिया!")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Here is what is going on, line by line.

  • print is a built-in instruction (Python calls it a function) that shows something as output.
  • The parentheses ( ) hold what you want printed.
  • The quotation marks " " mark the beginning and end of a piece of text. Python calls a piece of text a string, because it is a string of characters, like beads on a thread.
  • The lines run in sequence, from top to bottom, and each print starts a new line of output.

Try editing it: change the messages, add a line, or swap two lines and watch the output order change too.

Doing arithmetic

Python is also a calculator. Without quotation marks, Python treats 7 * 24 as a calculation and prints the answer. With quotation marks, it is just text, and Python prints it exactly as written.

python
print(7 * 24)                  # hours in a week
print("7 * 24")                # just text: printed exactly as written
print("Hours in a week:", 7 * 24)
print("Minutes in a year:", 365 * 24 * 60)
print(2 ** 10)                 # 2 to the power 10
print(17 / 4)                  # division
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

A few things to notice:

  • * means multiply, / means divide and ** means "to the power of". Addition + and subtraction - are what you expect.
  • Everything after a # on a line is a comment. Python ignores it completely. Comments are notes for human readers, including your future self.
  • You can give print several things separated by commas. It prints them on one line with a space between.

Pictures made of text

Here is a small surprise: in Python you can multiply a string by a whole number, and it repeats the string. That is enough to draw simple pictures.

python
print("    *")
print("   " + "*" * 3)
print("  " + "*" * 5)
print(" " + "*" * 7)
print("*" * 9)
print("   " + "| |")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The + between two strings joins them together. So " " + "*" * 3 is three spaces followed by three stars. Edit the program to draw a bigger tree, or a house, or the first letter of your name.

A taste of what is coming

Writing many print lines by hand gets tiring. In Decisions and loops you will make the computer repeat work for you. Here is a preview; just notice how two lines of code produce ten lines of output.

python
for n in range(1, 11):
    print(n, "times 7 is", n * 7)
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

When something goes wrong

Try deleting a closing quotation mark above and pressing Run. Python stops with an error message, perhaps a SyntaxError: "this doesn't follow Python's grammar". That is completely normal; every programmer sees error messages every day. They are not the computer telling you off, but telling you where it got confused. You will learn to read them like a detective in Finding and fixing mistakes.

How the exercises check your work

In the exercises at the end of this lesson, you will see lines like this:

python
hours_in_a_week = 7 * 24

This gives the result of the calculation a name, hours_in_a_week, so that the checker can look at your answer after your code runs. Names like this are called variables, and they are the main subject of the next lesson, Values, variables and expressions. For now, think of the line as a labelled answer box.

History & global context

From clay tablets to chips

Computing did not start with electronic machines. It started with people writing down procedures, and it took many cultures and many centuries to get from there to the phone in your pocket.

Written procedures. In ancient Mesopotamia, around 1800 to 1600 BCE, scribes pressed step-by-step worked problems into clay tablets: how to find a length from an area, how to divide an inheritance. One famous tablet, known as YBC 7289, records an approximation of the square root of 2 that is correct to about six decimal places. Around 300 BCE, Euclid's Elements described a procedure for finding the greatest common divisor of two numbers, which is still taught and used today as Euclid's algorithm (see Divisibility, Euclid's algorithm and unique factorisation in Lumenary Math). In China, the abacus came with exact rules for moving beads, and in India, mathematicians developed the decimal place-value system with zero, which made written calculation dramatically simpler.

The word itself. In the ninth century, Muhammad ibn Musa al-Khwarizmi worked at the House of Wisdom in Baghdad. He wrote a book explaining how to calculate with the Indian numerals, the ancestors of the digits 0 to 9 we use today. When it was translated into Latin, his name was written Algoritmi, and the Latin version opens with words meaning "So said al-Khwarizmi". Over time, "algorism" and then algorithm came to mean a method of calculation. Another of his books gave us the word algebra, from the Arabic al-jabr.

Machines that follow instructions. In 1804 the French weaver Joseph-Marie Jacquard built a loom controlled by chains of punched cards: change the cards and the same loom weaves a different pattern. In the 1830s the English mathematician Charles Babbage designed the Analytical Engine, a mechanical general-purpose computer meant to be programmed with punched cards like Jacquard's. It was never finished. But in 1843 Ada Lovelace published a translation of an article about it, together with her own notes, which were longer than the article. In the last of them she set out, step by step, how the Engine could compute a sequence called the Bernoulli numbers, which is why she is often called the first computer programmer. She also saw further than Babbage himself: she suggested that such a machine might work with any symbols, not just numbers, and might one day compose music.

Human computers. For a long time, "computer" was a job title: a person employed to do calculations for astronomy, navigation or engineering. Many were women. At NASA in the 1960s the mathematician Katherine Johnson computed spacecraft trajectories, and the astronaut John Glenn asked for her to check the electronic computer's numbers before his orbital flight.

The idea of a universal machine. In 1936 the English mathematician Alan Turing described an imaginary machine, now called a Turing machine, simple enough to define in a few lines yet able to carry out any algorithm at all. He also showed that one such machine could imitate any other if given a description of it as input: a universal machine, which is exactly what a modern computer is, and why the same device can be a calculator, a camera and a music player depending on the program it runs. In the same paper he proved that some problems cannot be solved by any algorithm whatsoever (see Computability).

Electronics and chips. The 1940s brought electronic computers: Colossus in Britain, built by Tommy Flowers's team for code-breaking, and ENIAC in the United States, whose first programmers were six women who worked out how to set up its thousands of switches and cables. In 1948 a machine in Manchester, nicknamed the Baby, ran the first program stored in the computer's own electronic memory, as all computers do today. The transistor (1947), the integrated circuit (late 1950s) and the microprocessor (1971, with a few thousand transistors on one chip) made computers smaller, cheaper and faster, decade after decade. A chip in a phone or a data centre today holds billions of transistors, many of the largest tens of billions.

No step of this story was the work of one lone genius: each idea was built by many people, across many countries, on the work of others.

Common misconceptionsH

Common misconceptions

Misconception

"The computer understands what I mean." It doesn't. It does exactly what your instructions say. When a program does something unexpected, the question to ask is not "why is the computer being stupid?" but "what did my instructions actually say?"

Misconception

"If the answer is wrong, the computer made a mistake." Hardware faults do happen, but they are very rare. Almost always, a wrong answer comes from the instructions: a step is missing, in the wrong order, or not quite what was intended. That is good news, because instructions are something you can fix.

Misconception

"You have to be a maths genius to program." Programming uses careful, step-by-step thinking, which is something you get better at with practice, like playing an instrument or a sport. Some areas of computer science use a lot of mathematics, and this course will teach it when it is needed, but you can write useful programs with nothing more than arithmetic.

Misconception

"Programming is mostly typing code." Typing is the smallest part. Most of programming is thinking: understanding the problem, breaking it into steps, and checking that the steps do what you want.

Optional Christian reflection · made to make

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Christians believe that human beings are made in the image of a God who creates, and that our urge to make things (a loom pattern, a recipe, a song, a program) is one small way that image shows itself. Writing an algorithm is an act of care: you think ahead about every situation so that someone, or something, can follow your steps safely. None of this is needed to learn programming; it is offered only as one way of thinking about the work.

Exercises

Exercises

Some exercises ask you to think, and two ask you to write a little Python. For the Python ones, change the code in the box, press Run, and the checker will tell you how you did.

1. What a computer does

Warm-upHuman

You are writing instructions for a robot cook that has no common sense at all. Which instruction could it follow without guessing?

Choose one

2. What a computer does

Warm-upHuman

At a bus station, you tap your travel card on a machine. The machine reads the card's balance, subtracts the fare, writes the new balance back to the card, and shows it on a little screen. Which part is the processing?

Choose one

3. What a computer does

CoreComputational

How many lines of output does this program produce? Count blank lines too.

print("Karibu!")
print()
print("1 + 1 =", 1 + 1)
print("Kwaheri")

4. What a computer does

CoreComputational

What does this program print?

print("3 + 4")
print(3 + 4)
Choose one

5. What a computer does

Warm-upComputational

Replace each ... with a Python calculation (not the final number!) so that:

  • seconds_in_a_day is the number of seconds in one day;
  • hours_in_a_year is the number of hours in a year of 365 days.

Use * to multiply. Press Run to check.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

6. What a computer does

CoreComputational

A recipe for pilau rice that serves 4 people uses 500 grams of rice and 750 millilitres of water. You are cooking for 10 people.

Replace each ... with a calculation that scales the recipe: first work out how much is needed for one person, then multiply by 10. Use / to divide.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

7. What a computer does

Warm-upHuman

The word algorithm comes from the name of…

Choose one

8. What a computer does

Warm-upHuman

When you press Run on a Python box in these lessons, where does your code actually run?

Choose one

Further reading and resources