Debugging and testing: finding the bugs
AdvancedThree error kinds: syntax (bad format, won't start), runtime (stops halfway, e.g. divide by zero), logic (finishes but wrong); verify with known-answer test data; trace with printouts and paper.
- Three error kinds: syntax, runtime, logic.
- Syntax won't start; runtime stops halfway; logic finishes but wrong.
- The message's last line names the type, the lines above give the location — read first, fix second.
文體小知識:方法指導課教你一套有系統的做法,照步驟練習,遇到問題就不會毫無頭緒。
§Text Passage
1Programs go wrong all the time; finding and fixing the errors is debugging. Errors come in three kinds: syntax errors — wrong format, like a missing colon, so the program never starts; runtime errors — it stops halfway, e.g. dividing by zero or reaching a missing index; and logic errors — the program finishes but the result is wrong, e.g. + written as *, the hardest to spot.
2Python reports syntax and runtime errors directly: SyntaxError: invalid syntax, ZeroDivisionError: division by zero. Reading the last line of the message (the error type) and the line number above (where it happened) solves half the problem at once. Reading error messages is a programmer's basic skill.
3Logic errors raise no complaint, so you must test: run the program with data whose answer you already know. For an averaging program, [10, 20, 30] should give 20; if it gives 6000 (multiplied by mistake), something is wrong. Such 'know-then-verify' inputs are test data, and they should include boundary cases: an empty list, all zeros, a single number.
4Tracing is the essential technique: on paper, write down each variable as the lines run, e.g. n=1 → print 1 → n=2 → print 2 → n=3 → print 3 → n=4 fails the condition, end. You can also add print(n) inside the program to watch variables. Fix one small thing, test again — and bugs never pile up.
1Summary 重點摘要
Three error kinds: syntax (bad format, won't start), runtime (stops halfway, e.g. divide by zero), logic (finishes but wrong); verify with known-answer test data; trace with printouts and paper.
2Vocabulary cards Vocabulary
An error or flaw in a program that stops it running or gives wrong results.
The process of locating errors and fixing them.
Breaking the language's format rules (e.g. a missing colon) so the program cannot even start.
An error that appears while running, e.g. division by zero or an out-of-range index.
The program runs to the end but the result is wrong because the method was; the hardest kind to spot.
Python's error report: the last line names the error type, with the line number above.
Inputs with known answers used to verify a program, including boundary cases.
A table recording each variable's value line by line, to locate where logic goes wrong.
Extreme inputs: the smallest, largest, zero, an empty list, a single item.
3Step by step Steps
- Spotting syntax errorsA syntax error means the program's 'grammar' is wrong: if x > 5 missing its colon, or print('hi' missing the closing bracket — Python reports SyntaxError. The giveaway is stark: the program cannot run even one line and complains the moment it starts, with the message naming the line. Beginners most often drop colons, leave brackets unpaired, or mix full-width and half-width punctuation, e.g. a full-width colon. On seeing SyntaxError, check the symbols on that line and the line above first.
- Spotting runtime errorsA runtime error happens halfway through execution: 10 / 0 raises ZeroDivisionError; taking the element at index 5 from the list [1, 2], which has only two items, raises IndexError because index 5 does not exist. The giveaway: the program starts fine, then stops suddenly at some line, and the message names where. How to handle it: jump to that line and check whether a divisor can be zero, whether an index runs past the end, whether a file exists, and so on.
- Spotting logic errorsA logic error is the most dangerous: the program finishes normally with no complaint, but the answer is wrong. For example, intending an average but writing sum(nums) * len(nums), with [10, 20, 30] the output is 1800 instead of the correct 20. The computer never warns you; the only defence is testing with data whose answer you know. Other common logic errors: plus written as times, >= written as >, a loop count off by one. Make testing a habit and logic errors have nowhere to hide.
- Reading the messagePython's error message is the best clue. When ZeroDivisionError: division by zero appears with a line number, the last line names the error type and the number above says where it happened. Read the last line first to learn the type, then jump to that line and inspect the code. Reading error messages is a programmer's basic skill; when a message's name is unfamiliar, search what it means first, then compare it with your own code step by step.
- Verify with test dataTest data is data whose answer you know in advance, used to verify the program. For an averaging program: try [10, 20, 30] and the mental answer is 20; try [5] — a single number, answer 5; try [0, 0] — answer 0. Normal values, single values and boundary values all deserve a run, because different cases trigger different faults — with a single number, some implementations go wrong. Exams often ask you to list test data with reasons; state the expected output for every set.
- The paper trace tableThe paper trace table is the basic tool for hunting logic errors. Draw a table on paper and record every variable's value line by line. For example, n = 1 with the program while n < 4: print(n), then n = n + 1: round one, n is 1, printing 1; round two, n is 2, printing 2; round three, n is 3, printing 3; round four, n is 4, the condition fails, the loop ends. The moment a variable diverges from expectation, the table shows it — and the fault is found.
- The print methodWhen the result looks wrong, add print at key spots to watch intermediate values, e.g. print('total:', total) — seeing the actual total tells you whether the problem lies in the first half or the second. Once fixed, remove these temporary prints to keep the program clean. The most important rule: one small change, one test — never five changes at once, or you will never know which change worked. Keep this discipline and debugging pays off doubly.
4Diagrams Diagrams
5Worked example Example
Example: this program should average [8, 9, 10] but prints 27. Identify the error type and fix it. The code: total = 0; for s in [8, 9, 10]: total = total + s; average = total * 3; print(average)
- Classify first: the program runs to the end without any error, so syntax and runtime errors are ruled out — it is a logic error.
- Verify with mental maths: 8 + 9 + 10 = 27, the total is right; but the task asks for the average, and 27 is the total, not the average.
- Inspect line by line to find the faulty line: average = total * 3 uses multiplication where division was meant — it should be average = total / 3.
- Test after fixing: 27 divided by 3 gives 9.0, correct; re-test with [10, 20, 30], the output is 20, and both test sets pass.
- Answer: It is a logic error: no complaint, wrong result. Change average = total * 3 to average = total / 3 and the output becomes 9.0; testing again with [10, 20, 30] gives 20 — both test sets pass and the fix is complete.
6Common mistakes Mistakes
7Quick check Quick check
Q1print("hello (missing closing bracket) is which type of error?
Q2What happens when 10 / 0 runs?
Q3A program finishes fine but the average is wrong. Which error type, and why is it hardest to find?
Q4When testing an averaging program with [10, 20, 30], what result should you expect?
Q5Name any three good debugging methods.
8Recap Recap
- Three error kinds: syntax, runtime, logic.
- Syntax won't start; runtime stops halfway; logic finishes but wrong.
- The message's last line names the type, the lines above give the location — read first, fix second.
- Verify with known-answer test data, including boundary cases.
- Debugging habit: one small change, one test; use prints and trace tables.