Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Finding and Fixing Errors: Syntax, Run-Time and Logic

A4.1 A4.3 A4.2About 70 minutes
Learning goals
  • I can tell syntax errors, run-time errors and logic errors apart.
  • I can read a Python error message (traceback) and find the line and cause.
  • I can fix common errors such as missing colons, bad indentation, misspelled names, type mismatches and division by zero.
  • I can follow a step-by-step process to debug a program, one error at a time.

Words to know

bug / debugging
A bug is an error in a program. Debugging is finding and fixing it.
syntax error
Code that breaks the rules of the language (a missing colon, quote or parenthesis). Python finds it before running anything, so no line runs.
run-time error (exception)
An error that happens while the program runs, such as dividing by zero or converting "abc" to an int. The program stops at that line.
logic error
The program runs without any message but gives the wrong result, because the algorithm or a formula is wrong.
traceback
Python's run-time error report: where the error happened and, on the last line, its type and a message.
debugger
An IDE tool that runs a program one line at a time and shows the variables, so you can watch what happens.

Everyone writes bugs

Professional programmers make mistakes every day. What makes them professionals is that they find and fix errors calmly and systematically. Error messages are not insults; they are clues. This lesson teaches you to read them.

Three kinds of errors

1. Syntax errors break the grammar of Python: a missing colon, an unclosed quote or parenthesis, bad indentation, a misspelled keyword like whlie. Before running your program, Python first translates (compiles) the whole file into an internal form called bytecode. Syntax errors are found during that step, so not a single line runs.

2. Run-time errors happen while the program is running, when a statement cannot be carried out: dividing by zero, int("abc"), adding a string to a number, using a variable that was never assigned. The lines before the error have already run; the program stops at the bad line.

3. Logic errors produce no message at all. The program runs and finishes, but the answer is wrong: a formula without parentheses, < instead of <=, an accumulator reset inside a loop. Only careful testing and tracing find them.

writingeditor coloursshow typosbefore runningSYNTAX errors:nothing runswhile runningRUN-TIME errors:program stopstestingLOGIC errors:wrong outputThe later an error is found, the harder it usually is to find.Logic errors give no message at all: only testing reveals them.
When each kind of error shows up during development.
Error typeTypical causeExample message (Python 3.13)
SyntaxErrormissing colon, quote or bracketexpected ':', '(' was never closed
IndentationErrormissing or uneven indentationexpected an indented block after 'if' statement on line 1
NameErrormisspelled or unassigned variablename 'Count' is not defined
TypeErrormixing types, such as str + intcan only concatenate str (not "int") to str
ValueErrorright type, bad value, such as int("abc")invalid literal for int() with base 10: 'abc'
ZeroDivisionErrordividing (or //, %) by zerodivision by zero
Errors you will meet most often in this unit. The first two are syntax errors; the rest are run-time errors.

Reading a traceback

When a run-time error happens, Python prints a traceback. Read it from the bottom up:

  1. The last line gives the error type and a message. This tells you what went wrong.
  2. The lines above give the file and line number, show the line of code, and often mark the exact spot with ^ or ~ characters. This tells you where.

For syntax errors the layout is similar but there is no "Traceback" heading: you get the line number, the line with a ^ under the problem, and SyntaxError: with a message.

Traceback (most recent call last):  File "main.py", line 4, in <module>    print(Count)          ^^^^^NameError: name 'Count' is not defined.1. which line (line 4)2. the code on that line3. ^ marks the exact spot4. error TYPE and message:read this line FIRSTRead from the bottom up:what went wrong, then where.(Python 3.13 also adds: Did you mean: 'count'?)
The parts of a run-time error message (a traceback). The last line names the error type; the lines above it say where. Older Python versions show fewer hints, but the layout is the same.

The error is not always on the reported line

Python reports where it noticed the problem, which can be after the real mistake. If the reported line looks fine, check the line above it, especially for a missing ), ] or closing quote. Messages also vary between Python versions and IDEs: older versions might just say invalid syntax. The type of error and the line number are always the best clues.

A debugging process

  1. Read the last line of the message. Identify the error type.
  2. Go to the line number. Look at the marked spot, then the line above.
  3. Form a hypothesis: "I think Count should be count."
  4. Fix one thing and run again. A new error message usually means progress: Python got further.
  5. For logic errors, trace the program by hand or print the values of variables at key points (Lesson 15), or use your IDE's debugger: in Thonny press Debug and step through line by line; in IDLE, turn on Debug → Debugger in the shell window, then run your program and press Step. Watch each variable change.

Good habits prevent bugs: run your program often (after every few lines), use clear names, and indent consistently with 4 spaces.

Worked example

Example 1: Fixing syntax errors

This program has three syntax errors. Find and fix them in the order Python reports them.

  • total = 0
  • for i in range(1, 4)
  •     total += i
  • if total > 5
  • print("Big total")
  1. Run it. Python stops at line 2: SyntaxError: expected ':'. Add a colon: for i in range(1, 4):. Run again.
  2. Next: line 4, SyntaxError: expected ':'. Add the colon: if total > 5:. Run again.
  3. Next: line 5, IndentationError: expected an indented block after 'if' statement on line 4. Indent the print by 4 spaces.
  4. Run again: it prints Big total (1 + 2 + 3 = 6, and 6 > 5). Python reported each syntax error only after the previous one was fixed, so fix one at a time.

Corrected: a colon after range(1, 4), a colon after total > 5, and the print indented under the if.

price = float(input("Price: "))
qty = 3
total = price * qty
print("Total: " + total)

Example 2's program. With input 4.50, lines 1 to 3 run, then line 4 stops with TypeError: can only concatenate str (not "float") to str. With input abc, it stops at line 1 with ValueError: could not convert string to float: 'abc'.

Worked example

Example 2: Run-time errors depend on the input

Explain the two different errors the program above can produce, and fix the one that is a real bug.

  1. With input 4.50: lines 1 to 3 run (total = 13.5). Line 4 tries to join a string and a float with +: TypeError. This is a bug in the code: fix it with print(f"Total: {total:.2f}") or print("Total:", total).
  2. With input abc: line 1 cannot convert "abc" to a float: ValueError. The code is reasonable; the input is bad. Exception handling, taught in the unit Software Development, can deal with it. (A validation loop like the one in Lesson 11 only helps once the input is a number.)
  3. Lesson: a program can pass one test and crash on another, so test with several kinds of input.

The TypeError is fixed by formatting the output properly. The ValueError is caused by invalid input, which the program should be designed to handle.

Worked example

Example 3: A logic error

This should print the average of 80, 90 and 70, which is 80. It prints 193.33333333333334. Find and fix the error.

  • a = 80
  • b = 90
  • c = 70
  • average = a + b + c / 3
  • print(average)
  1. There is no error message, so it is a logic error.
  2. Check the formula with the order of operations: c / 3 is done first (23.33...), then 80 + 90 + 23.33... = 193.33.
  3. Fix: average = (a + b + c) / 3.
  4. Test: (80 + 90 + 70) / 3 = 240 / 3 = 80.0. ✓

Add parentheses: (a + b + c) / 3.

Just for fun

In 1947, operators of the Harvard Mark II computer found a real moth stuck in a relay. They taped it into their logbook with the note "First actual case of bug being found." The joke was that engineers already called faults "bugs"; this time it was a real one.

Hands-on activity

Bug hunt with a partner

You need: Python and a family member or friend (they do not need to know Python).

  1. Take a program you wrote in an earlier lesson that works (for example, the HST calculator or the weather program). Save a copy.
  2. Turn your back. Your partner makes three small changes to the copy: deleting a colon, a quote or a parenthesis, changing a variable's capital letter, changing a < to >, removing an indent, or changing a number in a formula.
  3. Find all three bugs. For each one, write: the error type (syntax, run-time or logic), the message (if any), the line, and your fix.
  4. Swap: you plant bugs in a program while your partner watches what you change, and explain each kind of error to them.

What to look for: syntax errors are found immediately; a misspelled variable gives a NameError only when that line runs; a changed < or number gives no message, so you find it only by testing with values whose answer you already know. That is why every program needs test cases with known answers.

Your turn

1

Classify each as a syntax, run-time or logic error: (a) print("Hi" (b) x = 5 / 0 (c) using + instead of * in an area formula (d) if x > 3 with no colon (e) int("twelve")

2

What does the last line of a traceback tell you?

3

A program prints three lines and then shows ZeroDivisionError. Is it a syntax or run-time error? How do you know?

4

Fix this program so it prints Count: 5.

  • count = 0
  • for i in range(5):
  •     count += 1
  • print("Count: " + count)
5

What error does this give, and on which line? Fix it.

  • name = "Ava
  • print(name)
6

This program has no error message but prints 0. What kind of error is it? Fix it.

  • total = 0
  • for n in range(1, 4):
  •     total = 0
  •     total *= n
  • print(total)
7

Why should you fix one error at a time and rerun?

More practice: warm-up

1

Which kind of error gives no error message?

2

Which kind of error stops any line from running?

3

What error type does print(totl) give if totl was never assigned?

4

Which error type does int("3.5") give?

5

In which direction should you read a traceback?

More practice: on your own

1

Python reports IndentationError: unindent does not match any outer indentation level on line 4. What is wrong?

  • x = 5
  • if x > 3:
  •     print("big")
  •   print("done")
2

Find all the errors and say what kind each is.

  • Total = 0
  • for i in range(3):
  •     total += i
  • print(Total)
3

A temperature program uses if temp > 0: to print Freezing. When is the output wrong, and what kind of error is this?

4

Explain why print("there" on line 2 might be reported as an error on line 3 in some versions of Python or IDEs.

5

Write a test that would reveal the logic error in if mark > 50: print("Pass") when the rule is "50 or more passes".

Challenge

1

This program crashes for some inputs and gives wrong answers for others. Find all the problems.

  • n = int(input("How many marks? "))
  • total = 0
  • for i in range(n):
  •     total = int(input("Mark: "))
  • print("Average:", total / n)
2

A student says, "My program has no errors because it runs without any messages." Explain why this is wrong, with an example.

3

Explain the difference between how a compiler and Python report syntax errors, using this lesson.

Check your understanding

Quiz

1.

A program runs and finishes but prints the wrong total. What kind of error is it?

2.

Which line causes a SyntaxError?

3.

A traceback ends with NameError: name 'scroe' is not defined. What is the most likely fix?

4.

In a traceback, where is the error type?

5.

Why do lines before a run-time error still run?

6.

Which is the best first step when the reported line looks correct?

For parents and teachers

Big idea: expectation A4.1 (identify and correct syntax, logic and run-time errors) and A4.3 (interpret the error messages of programming tools at different stages), with clean, consistent code (A4.2) as prevention.

How to help: the bug hunt is a perfect activity for a parent who does not program: you plant the bugs, your teen finds them. Praise the process (reading the message, checking the line, testing) as much as the fix.

Common difficulties:

  • Panicking at long messages instead of reading the last line first.
  • Looking only at the reported line when the cause is the line above.
  • Changing many things at once, then not knowing which change mattered.
  • Believing a program that runs is correct. Logic errors need tests with known answers.