blog / guides

what a computer program does: 6 examples you can try

by Luke published 8 min read

the short answer

Every program, however small, takes something in, keeps it in memory, works something out and gives a result back. The six short Python programs on this page show that pattern in real code: a temperature converter, a password checker, a times table, a shopping basket, a word counter and a heating controller. Run each one, then change a value and run it again.

A computer program takes something in, keeps it in memory, works something out and gives a result back. Our guide to what a computer program does explains those four jobs. This page is the hands-on follow-up: six small programs you can run right now, each one showing the pattern in a different everyday task.

Every example is written in Python and runs in your browser. Under each one, you will find what goes in, what is remembered, what is worked out and what comes out, plus an idea for changing it.

1. A temperature converter

try it · python
for c in [0, 18, 37, 100]:
    f = c * 9 / 5 + 32
    print(f"{c}°C is {f:.1f}°F")
0°C is 32.0°F
18°C is 64.4°F
37°C is 98.6°F
100°C is 212.0°F
  • In: four temperatures in Celsius.
  • Remembered: each temperature in turn, as c, and its converted value, as f.
  • Worked out: the conversion formula, once for each temperature.
  • Out: one line per temperature.

The for line repeats the two lines below it once for each number in the list. :.1f shows one decimal place.

Try changing it: add -40 to the list. It is the one temperature that is the same on both scales.

2. A password checker

try it · python
for password in ["cat", "sunflower", "sunflower7"]:
    if len(password) < 8:
        print(password, "- too short")
    elif password.isalpha():
        print(password, "- letters only, add a number")
    else:
        print(password, "- passes both checks")
cat - too short
sunflower - letters only, add a number
sunflower7 - passes both checks
  • In: three passwords to test.
  • Remembered: the current password.
  • Worked out: two checks. len counts the characters, and isalpha() is True when every character is a letter.
  • Out: a verdict for each one.

This is the program deciding. if, elif and else pick exactly one message for each password. Real sign-up forms run checks like these, though length matters far more for a strong password than any single rule.

3. A times table

try it · python
number = 7
for i in range(1, 6):
    print(number, "x", i, "=", number * i)
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
  • In: the number 7.
  • Remembered: number, and the counter i.
  • Worked out: one multiplication per line.
  • Out: five lines of the table.

range(1, 6) counts from 1 up to, but not including, 6. That stopping point catches out nearly everyone at first.

Try changing it: make it print the full table up to 12 times 7.

4. A shopping basket

try it · python
basket = [("Bread", 1.35), ("Milk", 0.95), ("Apples", 2.10)]
total = 0
for item, price in basket:
    print(f"{item:<8} £{price:.2f}")
    total = total + price
print(f"{'Total':<8} £{total:.2f}")
Bread    £1.35
Milk     £0.95
Apples   £2.10
Total    £4.40
  • In: three items, each with a price.
  • Remembered: the basket, and a running total that starts at 0.
  • Worked out: the total, added to one price at a time.
  • Out: a tidy receipt.

The running total is one of the most useful patterns in programming. Start at zero, then add each value as the loop passes it. :<8 pads each name to eight characters so the prices line up.

5. A word counter

try it · python
sentence = "the cat sat on the mat with the hat"
words = sentence.split()
print("Words:", len(words))
print("Times 'the' appears:", words.count("the"))
print("Longest word length:", max(len(w) for w in words))
Words: 9
Times 'the' appears: 3
Longest word length: 4
  • In: one sentence.
  • Remembered: the sentence, and the list of words made from it.
  • Worked out: split() breaks the text at every space, count counts one word, and max finds the biggest length.
  • Out: three facts about the sentence.

Word processors run the same idea on whole documents to show you a word count.

6. A heating controller

try it · python
readings = [16, 18, 20, 22, 19]
target = 20
for t in readings:
    if t < target:
        print(t, "degrees: heating on")
    else:
        print(t, "degrees: heating off")
16 degrees: heating on
18 degrees: heating on
20 degrees: heating off
22 degrees: heating off
19 degrees: heating on
  • In: five temperature readings, as a thermostat might take through the day.
  • Remembered: the readings and the target.
  • Worked out: one comparison per reading.
  • Out: on or off, each time.

A real thermostat runs this decision again every few minutes for as long as it is switched on. The loop is the same idea: check, decide, act, repeat.

The order of lines matters

A program carries out its lines from top to bottom, one at a time. Swap two lines and you get a different program. Here the total is printed before the adding has happened:

try it · python
prices = [1.35, 0.95, 2.10]
total = 0
print("Total:", total)
for price in prices:
    total = total + price
Total: 0

Nothing went wrong from the computer’s point of view. It did exactly what the lines said, in the order they said it. Moving the print to the bottom, after the loop, fixes it. When a program gives a strange answer, check the order of its steps first.

Following a program by hand

When you meet a program you did not write, you can work out what it does without running it. Go through it one line at a time, the way the computer does, and keep a note of every variable’s value as it changes. Programmers call this tracing.

Here is the basket total from example 4, traced step by step:

Step                     price   total
total = 0                  -     0
first time round loop    1.35    1.35
second time round loop   0.95    2.30
third time round loop    2.10    4.40
loop finished              -     4.40

Each row is one moment in the program’s life. You can see the running total grow and check that the final answer is right before you ever press run.

Tracing feels slow at first, but it is the most reliable way to find out why a program does something unexpected. Most bugs show up as a row where a value is not what you thought it would be. When a program is too long to trace on paper, a print inside the loop does the same job for you, showing each value as it changes.

Try it yourself: trace the times table in example 3 for its first three rows, noting i and the answer each time. Then run it and compare.

Common misunderstandings

The computer knows what you meant

It only knows what you wrote. If the instructions are in the wrong order or use the wrong name, it follows them anyway, or stops with an error.

A program remembers things between runs

Variables live only while the program is running. Run the basket again and the total starts from zero. Keeping things for next time means saving them somewhere, such as a file or a database.

Bigger programs work differently

They are longer and better organised, but they are built from the same parts you used here: values, lists, loops, decisions and output.

A short exercise

Write a program that converts a list of distances from miles to kilometres. Use 1 mile = 1.609 km, and the distances 1, 5 and 26.2. Print each one on its own line with one decimal place, like 5 miles is 8.0 km. Try it in the playground from the button at the bottom of the page, choosing Python.

One possible answer

try it · python
for miles in [1, 5, 26.2]:
    km = miles * 1.609
    print(f"{miles} miles is {km:.1f} km")
1 miles is 1.6 km
5 miles is 8.0 km
26.2 miles is 42.2 km

It is the temperature converter again with a different formula. Notice that the first line says “1 miles”. Fixing that with an if is a good next step.

Your next step

Each of these programs uses the same few ideas: values, sequence, decisions and loops. Gwecode’s Start Here course gives each idea its own short lesson, 13 in all and about an hour and a half altogether, and ends with your first real code. Every lesson is free and runs in your browser, so there is nothing to install. Create a free account to keep your progress, and try the lesson below.

practise this · lessonWhat a Computer Actually Doesstart the lesson

questions

What is the simplest computer program?

A single line that shows a message, such as print("Hello") in Python. It has no input and no decisions, but it is a complete program: an instruction the computer carries out.

Do I need to understand every line before I run a program?

No. Running code and watching what it does is one of the best ways to understand it. Change one thing at a time and see what changes in the output.

Why do these examples use Python?

Python reads almost like English, so the ideas show through without much extra punctuation. The same programs could be written in JavaScript, Java or any other language, and they would do the same jobs.

Does a program remember anything after it finishes?

Not by itself. Variables live in memory only while the program runs. To keep something for next time, a program has to save it, for example in a file or a database.

How do I change these examples?

The boxes on this page run the code as written. To edit and rerun it, open the playground from the button at the bottom of the page, choose Python and paste the code in.

keep going.