All GCSE 7 35 min read 10 question quiz 16 exam marks

Trace Tables and Debugging

Working through an algorithm by hand with a trace table, saying what it is for, and finding and fixing the errors a question hides in it. These are the marks other candidates lose.

Trace tables

A trace table records the value of every variable after each step of an algorithm. It is how you find out what code really does, as opposed to what you think it does, and it is a standard question on every GCSE paper.

The method never changes:

  1. One column for each variable, plus one for the output
  2. One row for each pass of a loop, or each time a variable changes, working strictly in program order
  3. Write the value a variable has after the pass, and put a dash in a box only if the variable does not have a value yet

Worked example 1: a loop

Python
total = 0
for i in range(1, 5):
    total = total + i * 2
    print(i, total)
itotalOutput
-0-
121 2
262 6
3123 12
4204 20

The loop runs for 1, 2, 3 and 4. It does not run for 5, because range stops before its second value.

Worked example 2: a while loop with MOD and DIV

Python
number = 4721
total = 0
while number > 0:
    digit = number % 10
    total = total + digit
    number = number // 10
    print(digit, total, number)
print("Digit sum:", total)
numberdigittotalOutput
4721-0-
472111 1 472
47232 3 47
47107 10 4
04144 14 0
---Digit sum: 14

number % 10 peels off the last digit and number // 10 throws it away. When number reaches 0 the test number > 0 is false and the loop ends. Notice that the last row has number equal to 0 and yet the digit of that row is 4, because the loop body ran once more with number still 4 before it was cut to 0.

Filling in a trace tableA trace table for a program that adds up the digits of 4721. Before the loop, total is 0 and number is 4721. Pass one takes the last digit, 1, so total becomes 1 and number becomes 472. Pass two takes 2, total 3, number 47. Pass three takes 7, total 10, number 4. Pass four takes 4, total 14, number 0, and the loop stops because number is no longer greater than 0. The program outputs 14.A trace table fills in one pass at a timenumber = 4721total = 0while number > 0: digit = number % 10 total = total + digit number = number // 10print(total)TRACE TABLEpassdigittotalnumberstart04721111472223473710444140output:14
One row for each pass, one column for each variable, and the value after the pass.

Finding the purpose

Often the question does not ask for the table. It asks what the algorithm does. Trace it with small numbers and then describe the result, not the steps.

Python
a = 48
b = 18
while b != 0:
    temp = b
    b = a % b
    a = temp
print(a)
abtemp
4818-
181218
12612
606

It prints 6, which is the highest number that divides both 48 and 18. The algorithm finds the highest common factor of two numbers. It is more than 2,000 years old and is named after Euclid.

Describe the result, not the steps

"It sets temp to b, then b to a MOD b" is a description of the lines and earns nothing. "It outputs the highest common factor of the two numbers" is a description of the purpose and earns the mark. Trace with small values to see the answer, then state it in one sentence.

A trace table for a loop that adds 1, 2 and 3A short program sets total to 0, then loops for i from 1 to 3 adding i to total, then prints total. Beside it is its trace table, with one column for the line number, one for i, one for total and one for the output. Line 1 sets total to 0. Line 2 sets i to 1, line 3 makes total 1. Line 2 sets i to 2, line 3 makes total 3. Line 2 sets i to 3, line 3 makes total 6. Line 4 prints 6, so the output column of the last row holds 6. The method: take one line at a time, give each variable its own column and the output one too, write a new row each time a value changes, and read the answer from the last row.total.py1total = 02for i in range(1, 4):3    total = total + i4print(total)1How to trace2Take one line at a timeand do exactly what it saysOne column per variableand one for the outputWrite a new row each timea value changes, never overwriteCheck the last rowit is the answer the program givesThe trace table3lineitotaloutput10210311221323233336436646 is printed: 1 + 2 + 3
  1. Run the program by hand, one line at a time. Line 3 is the one that repeats.
  2. Follow four rules: one line at a time, one column per variable, a new row for each change, and check the last row.
  3. Each time the loop runs, i goes up by one and total grows: 0, 1, 3, 6.
  4. The output is written when print runs. Here it is 6.
A trace table shows exactly what the program does, one step at a time. It is how you find a logic error.

Finding and fixing errors

The exam gives you an algorithm that does not work, asks you to find the error, and asks for the corrected line. Nearly all of them are one of these:

FaultWhat it doesHow you spot it
Off by oneLoop runs one time too many or too fewCompare the first and last values with the specification
Wrong comparison> for >=, and for orTest at the boundary
Variable started wrongA maximum that begins at 0Test with all negative numbers
Variable reset in the wrong placeA total set to 0 inside the loopTrace two passes of the loop
Return in the loopA function stops after one itemCheck indentation of return
Wrong typeAdding text to a numberRead the error message

Six faults, each one running

An off by one error. The aim is 1 to 5:

Python
for i in range(1, 5):
    print(i, end=" ")        # 1 2 3 4: the 5 is missing
print()
for i in range(1, 6):
    print(i, end=" ")        # 1 2 3 4 5
print()

A total reset in the wrong place. The aim is the average of three marks:

Python
marks = [50, 60, 70]

total = 0
for mark in marks:
    total = 0                # fault: this wipes out the running total
    total = total + mark
print(total / len(marks))    # 23.333333333333332

total = 0
for mark in marks:
    total = total + mark
print(total / len(marks))    # 60.0

A return inside the loop. The aim is to add every number:

Python
def total_of(numbers):
    total = 0
    for n in numbers:
        total = total + n
        return total         # fault: leaves the function on the first pass
    return total

print(total_of([1, 2, 3]))   # 1

The return must line up with the for, so it runs once the loop has finished. Move it left by one level and the answer is 6.

A starting value that is wrong. The aim is the largest number:

Python
numbers = [-4, -9, -2, -7]

largest = 0
for n in numbers:
    if n > largest:
        largest = n
print(largest)               # 0, which is not even in the list

largest = numbers[0]
for n in numbers:
    if n > largest:
        largest = n
print(largest)               # -2

A type error. Text and numbers cannot be joined with a plus:

Python
# raises: TypeError
score = 7
print("Score: " + score)

The fix is print("Score: " + str(score)), or print("Score:", score).

An assignment where a comparison was meant:

Python
# raises: SyntaxError
score = 7
if score = 7:
    print("Seven")

Python catches this one before it runs and says Maybe you meant '==' instead of '='. A logic error you have to find yourself, and a syntax error the computer finds for you.

Correct the line, then say why

A question that says "identify the error and correct it" has a mark for naming the line, a mark for the correct replacement, and often a mark for the effect the error has. State all three.

The three kinds of error: syntax, runtime and logicThe three kinds of programming error, one card each, each with its own bug. A syntax error breaks the rules of the language, like print with an opening bracket that is never closed. The translator cannot understand the line, reports a SyntaxError and the program will not start. A runtime error happens while the program is running: dividing 10 by 0 makes the program start and then crash on that line with a ZeroDivisionError. A logic error is the hardest to find because nothing crashes: the program average equals a plus b divided by 2 runs happily and prints 8.0, when the average of 4 and 8 is 6.0, because division is done before addition. Only testing against the answer you expected finds it.Syntax errora typo in the rules of the languageprint("Hello"resultSyntaxError:'(' was never closedfound how?found before it runs,by the translatorRuntime errorthe program starts, then crashesx = 10 / 0resultZeroDivisionError:division by zerofound how?found while it runs:it stops on that lineLogic errorruns fine, gives a wrong answera, b = 4, 8average = a + b / 2print(average)result8.0(should be 6.0)found how?found only by testing againstthe answer you expected123
  1. Syntax error: the code breaks the rules of the language, so it will not run at all.
  2. Runtime error: the program starts, then crashes when it meets something it cannot do.
  3. Logic error: it runs without complaint but gives the wrong answer, so only testing finds it.
A program that runs is not a program that is right. Test the answers, not only the absence of crashes.

Debugging tools and techniques

Debugging is finding out why a program is wrong. The tools and habits below are in the specification, and they work in this order.

Read the error message

The last line names the error and the line above it gives the position. Python's messages are written to be read.

Print to see inside

The most common technique, and the one professionals still use first: print a variable at the point you are unsure about.

Python
def average(marks):
    total = 0
    for mark in marks:
        total = total + mark
        print("added", mark, "total is now", total)
    return total / len(marks)

print(average([50, 60, 70]))

Test small, test early

Run each subprogram on its own with values you can work out in your head, before you build the next one on top of it.

Check with assert

assert states something that must be true. If it is not, the program stops at that exact line and says so, which is far better than a wrong answer appearing three screens later.

Python
def grade_for(mark):
    if mark >= 70:
        return "Distinction"
    elif mark >= 50:
        return "Merit"
    return "Fail"

assert grade_for(70) == "Distinction"
assert grade_for(69) == "Merit"
assert grade_for(50) == "Merit"
assert grade_for(49) == "Fail"
print("All four tests passed")

What an IDE gives you

An integrated development environment puts the tools in one program. The exam names these:

ToolWhat it does for you
EditorWrites the code, with colour and automatic indentation
Error diagnosticsHighlights faults and reports their line
Run time environmentRuns the program so you can see the output
TranslatorTurns the code into machine code, reporting syntax errors as it does
DebuggerLets you run one line at a time
BreakpointPauses the program at a chosen line
Variable watchShows the value of variables while it is paused
A breakpoint plus a watch is a live trace table

Pause the program at the line you do not trust, step forward one line at a time, and watch each variable change. It does by machine what you do on paper in a trace table.

What an integrated development environment gives youA mock up of an integrated development environment, an IDE, with six features picked out. The editor colours the code and numbers the lines. Auto-complete offers names as you type, here suggesting prices and print. The error check underlines a mistake in red before the program is run: in the picture totl is underlined with the message totl is not defined, because the function is called total. The debugger lets you set a breakpoint, shown as a red dot beside line 4, run to it, step through the code and watch the values of the variables, here t equal to 2, p equal to 3 and prices equal to the list 2, 3. The console shows output and error messages. A file explorer keeps all the project files in one place. A Run button runs the program, a Debug button runs it under the debugger, and Stop ends it.my_project — IDERunDebugStopFILESmain.pyutils.pydata.txt1def total(prices):2    t = 03    for p in prices:4        t = t + p5    return t67print(totl([2, 3]))totl is not definedpricesprintWATCHt2p3prices[2, 3]consolepaused at line 4NameError: name'totl' is not definedEditorcolour and line numbersAuto-completesuggests as you typeError checkred line before you runDebuggerbreakpoint, step, watchConsoleoutput and error messagesProject filesall in one place123456123456
  1. Editor: colours the code and numbers the lines.
  2. Auto-complete: suggests names as you type, which saves typing and typos.
  3. Error check: underlines mistakes in red before you run the program.
  4. Debugger: breakpoints, stepping and a watch window to see what the variables hold.
  5. Console: where output and error messages appear.
  6. Project files: everything in one place.
An IDE is an editor, a translator and a debugger in one window. Learn the features it gives you.

Key terms you must be able to define

Trace table
A table that records the value of each variable after every step of an algorithm.
Dry run
Working through an algorithm by hand, without running it, to check what it will do.
Debugging
Finding and fixing faults in a program.
Syntax error
A mistake in the rules of the language, which stops the program from running.
Logic error
A mistake that lets the program run but produces the wrong result.
Breakpoint
A point in a program where a debugger pauses it, so the programmer can inspect it.
Variable watch
A debugging tool that shows the current value of chosen variables as the program runs.
Off by one error
A fault where a loop or an index is one too many or one too few.
IDE
Integrated development environment: a program that combines an editor, translator and debugging tools.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineTrace table
AnswerA table that records the value of each variable after every step of an algorithm.
DefineDry run
AnswerWorking through an algorithm by hand, without running it, to check what it will do.
DefineDebugging
AnswerFinding and fixing faults in a program.
DefineSyntax error
AnswerA mistake in the rules of the language, which stops the program from running.
DefineLogic error
AnswerA mistake that lets the program run but produces the wrong result.
DefineBreakpoint
AnswerA point in a program where a debugger pauses it, so the programmer can inspect it.
DefineVariable watch
AnswerA debugging tool that shows the current value of chosen variables as the program runs.
DefineOff by one error
AnswerA fault where a loop or an index is one too many or one too few.

Reach the top grade on this topic

Tracing questions are the most reliably gained marks on the paper, and the most reliably thrown away.

  • Give every variable its own column, and write each row in the order the program runs
  • Trace with the exact numbers you were given, never with ones you invent
  • State the purpose of an algorithm as a result: highest common factor, total, count, maximum
  • When asked to correct an error, name the line, write the fixed line, and say what it now does
  • Name the IDE tool and what it does: a breakpoint pauses, a watch shows a value

Mistakes that cost marks here

Avoid these
  • Skipping the final pass of a loop, or doing one pass too many.
  • Describing what each line does instead of what the algorithm achieves.
  • Writing the value before a line runs in a trace table instead of after it.
  • Correcting a symptom, such as adding one to an answer, instead of the fault that caused it.
  • Confusing a syntax error, which stops the program, with a logic error, which does not.
Fun fact

In 1969 the Apollo 11 guidance computer raised overload alarms on the way down to the Moon. Software written by Margaret Hamilton's team had been designed to drop the unimportant jobs and keep the vital ones running, so the landing went ahead. She is credited with coining the phrase software engineering.

Knowledge check

0 of 10 answered
1What does a trace table record?
2x = 1, then y = 10, then while y > 4: with x = x * 2 and y = y - 3 inside. What is x at the end?
3What does number % 10 give for 4721?
4A function adds up a list but has its return inside the loop. What does it return for [1, 2, 3]?
5A program finds the largest number by starting largest = 0. For which list does it give the wrong answer?
6Which of these is a syntax error?
7What does a breakpoint do?
8What does a variable watch show?
9What is the best description of the purpose of a loop that keeps taking a MOD b until b is 0?
10Which is the most useful first step when a program gives an error message?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

16 marks
1The program shown is run. Complete the values of x and y after each pass of the loop, and state the value that is output.3 marks
Complete
Python
x = 1
y = 10
while y > 4:
    x = x * 2
    y = y - 3
print(x)

Mark scheme0 / 3
  • Lx is 2 and y is 7 after the first pass
  • Lx is 4 and y is 4 after the second pass, and the loop then stops because 4 is not greater than 4
  • LThe value output is 4
Model answer

After the first pass x is 2 and y is 7. After the second pass x is 4 and y is 4. The condition y > 4 is now false, because 4 is not greater than 4, so the loop stops without a third pass, and the value output is 4.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2The algorithm shown is run with a = 48 and b = 18. State what the algorithm does, and the value it outputs.3 marks
State
Python
a = 48
b = 18
while b != 0:
    temp = b
    b = a % b
    a = temp
print(a)

Mark scheme0 / 3
  • LIt finds the highest common factor of the two numbers
  • LOf a and b, or 48 and 18
  • LThe value output is 6
Model answer

The algorithm finds the highest common factor of the two numbers, which is the largest whole number that divides exactly into both. For 48 and 18 the values of b are 18, 12, 6 and 0, and the algorithm outputs 6.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3The program is meant to display the largest number in the list. Identify the error, explain what output it gives for this list, and write a corrected version of the line.4 marks
Identify
Python
numbers = [-4, -9, -2, -7]
largest = 0
for n in numbers:
    if n > largest:
        largest = n
print(largest)

Mark scheme0 / 4
  • Llargest is set to 0 before the loop
  • LAll the numbers in the list are negative, so none is greater than 0
  • LThe program outputs 0, which is not in the list
  • LThe corrected line is largest = numbers[0]
Model answer

The error is that largest starts as 0. Every number in the list is negative, so none of them is greater than 0, the test never succeeds, and the program outputs 0, which is not in the list at all. The line should be largest = numbers[0], so the comparison starts from a value that really is in the list. The correct output is -2.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4The line shown is part of a program and it stops the program from running. Name the type of error and write the corrected line.2 marks
Name
Python
score = 7
if score = 7:
    print("Seven")

Mark scheme0 / 2
  • LIt is a syntax error
  • LThe corrected line is if score == 7:
Model answer

This is a syntax error. A single equals sign assigns a value, and a comparison needs two, so the line should read if score == 7: and the program can then run.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Describe two features of an integrated development environment (IDE) that help a programmer to find and correct errors.4 marks
Describe

Mark scheme0 / 4
  • LA breakpoint pauses the program at a chosen line
  • LSo the programmer can inspect the state, or step through one line at a time
  • LError diagnostics highlight the line with a fault and describe the problem
  • LSo the programmer is taken straight to the fault without searching
Model answer

A breakpoint pauses the program at a line chosen by the programmer, so the values of the variables can be inspected, and the program can then be stepped through one line at a time to see exactly where the values stop being what was expected. Error diagnostics highlight the line containing a fault and describe the problem, so the programmer is taken straight to where it is rather than having to search the whole program for it.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 16