A. Programming Concepts and Skills · Programming Basics: Data, Decisions and LoopsFinding 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.
When each kind of error shows up during development.| Error type | Typical cause | Example message (Python 3.13) |
|---|
SyntaxError | missing colon, quote or bracket | expected ':', '(' was never closed |
IndentationError | missing or uneven indentation | expected an indented block after 'if' statement on line 1 |
NameError | misspelled or unassigned variable | name 'Count' is not defined |
TypeError | mixing types, such as str + int | can only concatenate str (not "int") to str |
ValueError | right type, bad value, such as int("abc") | invalid literal for int() with base 10: 'abc' |
ZeroDivisionError | dividing (or //, %) by zero | division 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:
- The last line gives the error type and a message. This tells you what went wrong.
- 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.
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
- Read the last line of the message. Identify the error type.
- Go to the line number. Look at the marked spot, then the line above.
- Form a hypothesis: "I think
Count should be count." - Fix one thing and run again. A new error message usually means progress: Python got further.
- 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 exampleExample 1: Fixing syntax errors
This program has three syntax errors. Find and fix them in the order Python reports them.
total = 0for i in range(1, 4) total += iif total > 5print("Big total")
- Run it. Python stops at line 2:
SyntaxError: expected ':'. Add a colon: for i in range(1, 4):. Run again. - Next: line 4,
SyntaxError: expected ':'. Add the colon: if total > 5:. Run again. - Next: line 5,
IndentationError: expected an indented block after 'if' statement on line 4. Indent the print by 4 spaces. - 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 exampleExample 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.
- 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). - 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.) - 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 exampleExample 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 = 80b = 90c = 70average = a + b + c / 3print(average)
- There is no error message, so it is a logic error.
- Check the formula with the order of operations:
c / 3 is done first (23.33...), then 80 + 90 + 23.33... = 193.33. - Fix:
average = (a + b + c) / 3. - Test: (80 + 90 + 70) / 3 = 240 / 3 = 80.0. ✓
Add parentheses: (a + b + c) / 3.
Just for funIn 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 activityBug hunt with a partner
You need: Python and a family member or friend (they do not need to know Python).
- Take a program you wrote in an earlier lesson that works (for example, the HST calculator or the weather program). Save a copy.
- 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. - 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.
- 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
1Classify 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")
(a) syntax (b) run-time (c) logic (d) syntax (e) run-time.
2What does the last line of a traceback tell you?
The type of error and a message describing it.
3A program prints three lines and then shows ZeroDivisionError. Is it a syntax or run-time error? How do you know?
Run-time: some lines ran first. A syntax error would stop the program before any line ran.
4Fix this program so it prints Count: 5.
count = 0for i in range(5): count += 1print("Count: " + count)
Line 4 is a TypeError (string + int). Use print("Count: " + str(count)) or print("Count:", count).
5What error does this give, and on which line? Fix it.
SyntaxError: unterminated string literal on line 1: the closing quote is missing. Fix: name = "Ava".
6This program has no error message but prints 0. What kind of error is it? Fix it.
total = 0for n in range(1, 4): total = 0 total *= nprint(total)
A logic error. Two problems: total is reset inside the loop, and a product must start at 1. Fix: total = 1 before the loop only, and remove the reset; it then prints 6 (1 × 2 × 3).
7Why should you fix one error at a time and rerun?
Python reports only the first syntax error it finds, and one mistake can cause misleading messages later. Rerunning after each fix shows real progress and avoids "fixing" code that was fine.
More practice: warm-up
1Which kind of error gives no error message?
2Which kind of error stops any line from running?
3What error type does print(totl) give if totl was never assigned?
4Which error type does int("3.5") give?
5In which direction should you read a traceback?
From the bottom up: the error type first, then where it happened.
More practice: on your own
1Python reports IndentationError: unindent does not match any outer indentation level on line 4. What is wrong?
x = 5if x > 3: print("big") print("done")
Line 4 is indented by 2 spaces, which matches neither the if block (4 spaces) nor the outer level (0). Use 0 spaces if done should always print, or 4 if it belongs to the if.
2Find all the errors and say what kind each is.
Total = 0for i in range(3): total += iprint(Total)
Line 3 uses total, but the variable was created as Total, so total += i raises a NameError (run-time) on the first iteration. Fix: use the same name, total, everywhere (lower case is the convention).
3A temperature program uses if temp > 0: to print Freezing. When is the output wrong, and what kind of error is this?
It prints Freezing for warm temperatures and nothing for freezing ones. It is a logic error: the comparison is reversed; it should be temp <= 0 (or temp < 0, depending on the specification).
4Explain why print("there" on line 2 might be reported as an error on line 3 in some versions of Python or IDEs.
Python keeps reading, expecting the ). It only notices something is wrong when the next line starts something that cannot be part of the same statement. Newer versions point at the unclosed (, but older ones may report the next line. Always check the line above.
5Write a test that would reveal the logic error in if mark > 50: print("Pass") when the rule is "50 or more passes".
Test with exactly 50. The expected output is Pass, but the program prints nothing. Boundary values reveal > versus >= mistakes.
Challenge
1This program crashes for some inputs and gives wrong answers for others. Find all the problems.
n = int(input("How many marks? "))total = 0for i in range(n): total = int(input("Mark: "))print("Average:", total / n)
(1) Logic: total = int(...) replaces the total instead of adding; use total += int(...). (2) Run-time: if the user enters 0, total / n raises a ZeroDivisionError; guard with if n > 0:. (3) Run-time: a non-number such as ten raises a ValueError at the int() call; validation or exception handling is needed.
2A student says, "My program has no errors because it runs without any messages." Explain why this is wrong, with an example.
No messages only means there are no syntax or run-time errors for that input. There can still be logic errors (for example a + b / 2 for an average gives a wrong answer silently), and other inputs may trigger run-time errors (such as 0 in a division). Only testing with known answers and a range of inputs shows it works.
3Explain the difference between how a compiler and Python report syntax errors, using this lesson.
A compiler (as in C++ or Java) translates the whole program to machine code before it runs and reports syntax errors (often many at once) at compile time. Python also translates the whole file first (to bytecode), so syntax errors also stop everything before any line runs, but it reports them one at a time. Run-time errors are only found when the line actually runs, in both kinds of language.
Check your understandingQuiz
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 teachersBig 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.