Common Python
Errors
Learn to recognize and fix the five most common Python exceptions: NameError, IndexError, KeyError, TypeError, and ValueError.
What Are Python Errors?
When Python encounters code it cannot execute, it raises an exception: a message that tells you what went wrong and where it happened. These are not punishments: they are your code trying to communicate with you.
Anatomy of a Traceback
The Big Five Errors
NameError: Undefined Names
scroe instead of scoreIndexError: Out of Range
KeyError: Missing Keys
TypeError: Wrong Types
Python does not automatically convert between types. If age is a string "25" and you add an integer 5, Python doesn't know whether you want "255" (concatenation) or 30 (math). You must be explicit.
ValueError: Wrong Content
ValueError means: "I understand what you gave me, but the specific content doesn't make sense for this operation."
TypeError vs ValueError
| TypeError | ValueError | |
|---|---|---|
| Problem | Wrong type entirely | Right type, wrong content |
| Analogy | Plugging USB into a power outlet | Right plug, wrong voltage |
| Example | "5" + 3 |
int("five") |
| Fix strategy | Convert with int(), str() |
Validate input before converting |
How to Debug Step by Step
print() or type() to inspect variables near that lineExample 1: NameError Fix
Example 2: IndexError Fix
Example 3: Multiple Errors
Common Mistakes
Summary Table
| Error | Cause | Quick Fix |
|---|---|---|
| NameError | Undefined variable or typo | Check spelling, ensure assignment |
| IndexError | Index beyond list length | Use range(len(lst)) or check bounds |
| KeyError | Missing dictionary key | Use .get(key, default) |
| TypeError | Incompatible types in operation | Convert with int(), str() |
| ValueError | Right type, invalid content | Validate input before converting |
Question 1 of 5
What error does this code produce?x = [1, 2, 3]print(x[3])
Question 2 of 5
What error does this code produce?result = "10" + 5
int("10") + 5 or "10" + str(5).Question 3 of 5
What error does int("hello") produce?
int() function accepts strings, so the type is fine. But the value "hello" cannot be interpreted as a number, so Python raises a ValueError.Question 4 of 5
A student writes:data = {"name": "Bob"}print(data["age"])
Which error is raised?
data has only the key "name". Accessing "age" raises a KeyError because that key doesn't exist. Use data.get("age", "N/A") for safe access.Question 5 of 5
A student wrote a program to calculate the total price of items in a shopping cart. The code is:
cart = ["apple", "banana", "milk"]
prices = {"apple": 1.50, "banana": 0.75}
total = 0
for item in cart:
total += prices[item]
print(total)
The program crashes when it reaches the third item in the cart.
What error type is raised, and why?
prices dictionary contains keys for "apple" and "banana" but not "milk". When the loop reaches "milk", prices["milk"] raises a KeyError. Fix: add "milk" to the dictionary or use prices.get(item, 0).