Be the computer
A phone app says the average of your two test scores, 4 and 6, is 7. That cannot be right. It should be 5.
How do you find the mistake? You do what the computer does. You follow each step, one at a time, and write down every value.
Key words
| Word | What it means | Example |
|---|---|---|
| Trace table | A table where you write the value of each variable after every step. | n is 1, then 2, then 3 |
| Algorithm | A list of clear steps in order that solves a problem. | a recipe |
| Loop | Steps that repeat. | add 1 until n is 5 |
| Variable | A name that holds a value. | total |
| Output | What the program shows or gives back. | the total |
| Syntax error | A mistake in the spelling or rules of the language. The program will not start. | a missing colon |
| Logic error | The program runs but gives a wrong answer. | using > when you need >= |
| Runtime error | The program starts but crashes while it runs. | divide by zero |
| Debug | Find and fix mistakes. | change > to >= |
The cells students fill in are left blank in this preview.
Try it: what does it do?
a = 8
b = 5
if a > b:
biggest = a
else:
biggest = b
print(biggest)
# What is the purpose of this algorithm?
# Change a and b and run it again.
Find the purpose
To find what an algorithm is for, ask three questions. What goes in? What comes out? What happens in the middle?
The code above takes two numbers. It gives back the bigger one. Its purpose is to find the biggest of two numbers.
An algorithm to trace
total = 0
n = 1
while n <= 4:
total = total + n
n = n + 1
print(total)
Worked example: a trace table
| Step | n | total | Is n 4 or less? | Output |
|---|---|---|---|---|
| Start | 1 | 0 | yes | |
| After loop 1 | 2 | 1 | yes | |
| After loop 2 | 3 | 3 | yes | |
| After loop 3 | 4 | 6 | yes | |
| After loop 4 | 5 | 10 | no, stop | |
| 5 | 10 | 10 |
The cells students fill in are left blank in this preview.
How to read the table
Each row is one moment while the program runs. In loop 1, total goes from 0 to 0 + 1 = 1. In loop 2, it goes to 1 + 2 = 3. In loop 3, 3 + 3 = 6. In loop 4, 6 + 4 = 10.
When n becomes 5, the question "is n 4 or less?" is no. The loop stops and the program shows 10.
Finish the trace
Have a go
Finish the trace
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.