Data Structures and Object-Oriented Programming

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 areHow you'll noticeTypical causesQuick 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.

ExceptionWhen it happensHow to avoid / repair
TypeErrorWrong data type in an operation ("abc" + 5).Convert types (str(5)), or check with isinstance.
ValueErrorValue can't be converted (int("xyz")).Validate input first ("xyz".isdigit()).
IndexErrorList index is outside range (lst[5] on [1,2,3]).Check length with len(lst) or iterate directly (for item in lst).
KeyErrorDict key not present (d['b']).Use d.get('b') with a default, or test 'b' in d.
AttributeErrorObject 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.

SymptomCommon root causesDebugging 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

  1. Program won't start? → Read the SyntaxError message, fix colons/indentation first.
  2. Crashes mid-run? → Note the exception type & line; check types, values, indices, keys.
  3. 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.

Click to reveal
for i in range(5)
    print(i)

Syntax: add : after range(5) and indent the print(i) line.

Click to reveal
def accumulateSum(nums):
    total = 0
    for n in nums:
        total = n
print(total)

Semantic: change total = n to total += n to accumulate the sum.

Click to reveal

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-except and good input checks.
  • Semantic errors require logical thinking and systematic debugging – tests and stepping through code are your best friends.
Back to Data Structures and Object-Oriented Programming