Fixing programs
Three kinds of error
- A syntax error breaks the rules of the language, such as a missing colon or bracket. The program will not run at all.
- A runtime error happens while the program runs: it starts, then stops part way with an error message, such as dividing by zero or using an index that does not exist.
- A logic error lets the program run to the end, but the result is wrong, such as a total that is one item short.
Python names the line where it found a syntax or runtime error, and the kind of error: SyntaxError, IndexError, TypeError, ValueError or ZeroDivisionError. A logic error gives no message, so the tests are how you find it.
A method for fixing a program
- Run the program as it is and read any error message: it names the line.
- Fix syntax errors first, one at a time, running the program after each.
- Then fix anything that makes the program stop part way.
- Now compare the output with a test you have worked out by hand. Where they first differ is near the logic error.
- Trace the loop for a small input, writing down each variable as it changes.
- Fix the smallest thing that makes the tests pass. Do not rewrite code that works.
The bugs that come up most
Limits. "Under 16" is < 16; "16 or over" is >= 16; "from 1 to 10" includes both, so >= 1 and <= 10. Boundary tests, the limits themselves, find these bugs.
Loops one short. range(1, n) stops at n minus 1, so a loop that must include n needs range(1, n + 1).
Input never converted. input() always gives a string, so "3" + "4" is "34". Convert with int() or float() first.
And or or. No number is below the lower limit and above the upper limit at once. Outside a range joins the two checks with or.
total = 0
for s in scores:
total = total + s
return total # after the loop, lined up with for
Indentation. Set a running total up once, before the loop, and return it after the loop. A return indented inside the loop ends the function on the first item.