Chapter 6: Common Python Errors
Chapter 6 Recap – Understanding & Fixing Common Python Errors
I'll guide you through the three big categories of mistakes Python programmers run into, show you how to spot them, and give you quick tactics for fixing or avoiding them.
1. Syntax Errors – "Python can't read this"
| What they are | How you'll notice | Typical causes | Quick fix |
|---|---|---|---|
| The code breaks before it even runs. Python's parser stops at the first line it can't interpret. | The interpreter prints SyntaxError (or IndentationError) and highlights a spot with a little caret ^. | * Missing : after if, for, def, etc.* Unmatched brackets/quotes. * Bad indentation mixing spaces & tabs. | Read the error line and the one just above it; the true problem is often there. Use an editor that shows indentation guides and bracket matching. |
Example & fix
# ❌ Missing colon
if score > 90 # ← add ':'
print("Great job!")2. Runtime Errors (Exceptions) – "It runs... then crashes"
Python starts running but hits something it can't do. Each built-in exception tells you the kind of problem.
| Exception | When it happens | How to avoid / repair |
|---|---|---|
TypeError | Wrong data type in an operation ("abc" + 5). | Convert types (str(5)), or check with isinstance. |
ValueError | Value can't be converted (int("xyz")). | Validate input first ("xyz".isdigit()). |
IndexError | List index is outside range (lst[5] on [1,2,3]). | Check length with len(lst) or iterate directly (for item in lst). |
KeyError | Dict key not present (d['b']). | Use d.get('b') with a default, or test 'b' in d. |
AttributeError | Object lacks a method (lst.appendd). | Double-check spelling or inspect with dir(obj). |
🛠️ Defense:
Wrap risky code in a try-except block and print/log the exception so the rest of the program can keep going.
try:
total = prices[3] * qty
except (IndexError, TypeError) as err:
print("Oops:", err)3. Semantic (Logic) Errors – "It runs quietly... but gives the wrong answer"
These are the sneakiest: the program is valid Python and raises no exception, yet it doesn't do what you meant.
| Symptom | Common root causes | Debugging tips |
|---|---|---|
| Wrong output, missing output, infinite loops, etc. | - Typos in variable names (nmae).- Wrong operator ( = vs ==).- Incorrect formulas or loop logic ( sum = numbers[i] instead of +=). | 1. Print values at key steps (print(sum)).2. Use a debugger ( breakpoint()) to step line-by-line.3. Write unit tests for the function's expected behaviour. 4. Rubber-ducking – explain the algorithm aloud; many flaws pop out. |
4. Putting it all together – a mini checklist
- Program won't start? → Read the SyntaxError message, fix colons/indentation first.
- Crashes mid-run? → Note the exception type & line; check types, values, indices, keys.
- Runs but wrong result? → Add prints or a debugger, inspect variable values, and write small tests.
5. Quick Practice
What is the error type in each of these cases? And how can you fix them?
nums = [10, 20, 30]
print(nums[10])Runtime: use a valid index like nums[2] or use a loop/try-except to access elements safely.
for i in range(5)
print(i)Syntax: add : after range(5) and indent the print(i) line.
def accumulateSum(nums):
total = 0
for n in nums:
total = n
print(total)Semantic: change total = n to total += n to accumulate the sum.
6. Key Takeaways
- Syntax errors are caught by Python's parser – fix them before anything else.
- Runtime exceptions signal bad operations – handle them with
try-exceptand good input checks. - Semantic errors require logical thinking and systematic debugging – tests and stepping through code are your best friends.