~/learn/Python · Fundamentals
Reading errors and fixing mistakes
Recognise common errors, inspect values and distinguish a crash from a wrong answer.
why this matters
Learning to diagnose a small mistake is more valuable than memorising a perfect example. Debugging is part of normal programming.
An error message is a clue, not a judgement. A syntax error means Python cannot understand the program's structure. A runtime error means Python understood it but hit a problem while executing it. A logic error means it ran, but the result is wrong.
A simple debugging routine
1. Read the last line: error type and message. 2. Find the relevant line in your own code. 3. Inspect the values and their types. 4. Change one thing, then run again. 5. Check normal inputs and edge cases.
A traceback lists where an error happened. Lesson examples may include setup instructions before your snippet, so the reported line number can include earlier examples. Look for the named variable or expression, not only the line number.
Recognise the clue
SyntaxError: invalid structure, often a missing colon or quote. IndentationError: a block is not indented correctly. NameError: a name has not been defined, or was misspelled. TypeError: an operation received an unsuitable type. ValueError: the type is acceptable but the value is not. ZeroDivisionError: division by zero.
Try it: The expression raw_score + 2 would fail. Explain why the conversion fixes it, then use "58" instead.
Use temporary print statements to compare what you expected with what actually happened. A wrong total might come from a variable being reset inside a loop, not from the addition itself. A boundary error often comes from > instead of >=.
Try it: If 60 should pass, which comparison is correct? Test score = 59 too.
assert checks that a condition is true and raises AssertionError if it is false. It is useful for small development checks: a silent successful assert means the check passed. It is not a replacement for handling invalid input in a real application.
Try it: Add a check that 59 is below 60.
Check the edges
Test an empty collection, zero, a single value and a value exactly at a threshold. For numeric text, consider invalid text too. Change one thing at a time so you can tell what fixed the problem.
key takeaways
- Read the error type and message, then inspect your own expression.
- Use print and type to check what values you actually have.
- A program can run successfully and still have a logic error.
- assert checks a condition; test empty inputs and threshold values too.
check your understanding
raw_score = "40" Why does raw_score + 2 fail?
free practice
Build confidence with a question you can solve without Pro.