View as PDF

COMPUTING AND DIGITAL LITERACY

Debugging

Difficulty level: Intermediate

Computing and Digital Literacy

This document was made by AI and there may be mistakes. If a question or answer looks wrong, use the Flag a mistake button to let Brett know so he can fix it.

Overview of the concept

This is how you find and fix what is wrong when a program or an app does not work. Instead of giving up and starting over, you track down the one thing that is off, the way you would find out why a bike will not shift gears instead of buying a new one. You test one part at a time until the fault shows itself. It is a patient skill, and it is the same skill you use to fix anything that stops working.

Worked examples

Example 1

Read the error message

Solution

total = 0

for n in [1, 2, 3]:

total = total + n

print(totai) -> NameError: name 'totai' is not defined

Read the error: NameError says a name is not defined, and it names 'totai'.

Compare with your variables: you defined total, not totai, so it is a spelling mistake.

Fix the spelling to print(total) and run again; the output is 6.

Example 2

Trace values by hand

Solution

x = 5

x = x + 1

print(x) -> Output: 6, but you expected 5.

Fix: you added 1, so 6 is correct; change the expectation, not the

code.

Write down each variable's value after each line: x starts at 5.

After x = x + 1, x holds 6.

Compare with what you expected: if the code did what you wrote, fix your expectation; if not, fix the line that went wrong.

Practice questions

1

This code gives NameError name 'totl' is not defined. total = 0; for n in [1, 2, 3]: total = total + n; print(totl). What is wrong, and what is the fix?

2

This code gives TypeError: can only concatenate str (not 'int') to str. age = 25; print('Age: ' + age). What is wrong, and what is the fix?

3

This code runs but prints the wrong answer. total = 0; for n in [1, 2, 3]: total = total - n; print(total). It prints -6 but should print 6. What is wrong, and what is the fix?

4

Trace this code x = 7; x = x + 3; print(x). What prints, and what is x after each line?

5

Trace this code y = 3; y = y + 2; y = y + 4; print(y). What prints?

6

Trace this code total = 0; for n in [2, 4, 6]: total = total + n; print(total). What prints?

7

Trace this code x = 5; y = x + 2; x = 9; print(y). What prints?

8

An error message names a line number. Why read the error message first?

9

What is a syntax error?

10

What is a logic error?

ANSWER KEY

1. totl is a spelling mistake for total; change print(totl) to print(total).

2. age is a number, but + with a string needs text; change print('Age: ' + age) to print('Age: ' + str(age)).

3. The loop subtracts instead of adding; change total = total - n to total = total + n.

4. 10 prints. x is 7, then 10.

5. 9

6. 12

7. 7

8. Because it says what went wrong and where.

9. Code that breaks the language's grammar rules, so it cannot run

10. Code that runs but gives the wrong answer