01 / 21
>_ ERR

Common Python
Errors

Learn to recognize and fix the five most common Python exceptions: NameError, IndexError, KeyError, TypeError, and ValueError.

Python

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

Traceback (most recent call last): File " main.py ", line 3 , in <module> print(username) NameError : name 'username' is not defined Location: file + line Offending code line Error type + message Tip: Always read the last line first: it tells you the error type. Then look at the line number to find where it happened.

The Big Five Errors

NameError
Using a variable that doesn't exist yet
IndexError
Accessing a list position that's out of range
KeyError
Looking up a dictionary key that doesn't exist
TypeError
Performing an operation on incompatible types
ValueError
Right type, but wrong content for the operation

NameError: Undefined Names

# Attempting to use an undefined variable print(score) NameError: name 'score' is not defined
1
Typo in variable name: scroe instead of score
2
Using before assigning: referencing a variable before giving it a value
3
Scope issue: the variable was defined inside a function and used outside it

IndexError: Out of Range

colors = ["red", "blue", "green"] print(colors[3]) IndexError: list index out of range
"red" index 0 "blue" index 1 "green" index 2 ??? index 3

KeyError: Missing Keys

student = {"name": "Alice", "grade": 10} print(student["age"]) KeyError: 'age'
# Safe alternative age = student.get("age", "unknown") print(age) # "unknown" (no crash!)

TypeError: Wrong Types

age = "25" result = age + 5 TypeError: can only concatenate str (not "int") to str

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.

# Fix: convert to the type you need result = int(age) + 5 # 30 (math) result = age + str(5) # "255" (concatenation)

ValueError: Wrong Content

number = int("hello") ValueError: invalid literal for int() with base 10: 'hello'

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

1
Read the last line: identify the error type (NameError, IndexError, etc.)
2
Read the description: the text after the colon explains what specifically went wrong
3
Find the line number: go to the file and line indicated in the traceback
4
Check your assumptions: use print() or type() to inspect variables near that line
5
Apply the fix: based on the error type, apply the appropriate remedy

Example 1: NameError Fix

# Buggy code def greet(): message = "Hello, " + usrname print(message) username = "Alice" greet() # NameError: name 'usrname' is not defined
# Fixed code def greet(username): message = "Hello, " + username print(message) username = "Alice" greet(username) # "Hello, Alice"

Example 2: IndexError Fix

# Buggy code scores = [88, 92, 75, 95] for i in range(1, len(scores) + 1): print(scores[i]) # IndexError: list index out of range
# Fixed code: use range(len(scores)) for i in range(len(scores)): print(scores[i]) # Even better: iterate directly for score in scores: print(score)

Example 3: Multiple Errors

# This function has TWO bugs def get_average(data): total = 0 for item in data: total = total + item # Bug 1: what if item is a string? avg = total / len(dta) # Bug 2: typo! 'dta' not 'data' return avg get_average([10, "20", 30]) # TypeError on line 4 (adding str to int) # NameError on line 5 (dta is undefined)
# Fixed def get_average(data): total = 0 for item in data: total = total + int(item) # Convert to int avg = total / len(data) # Fix typo return avg

Common Mistakes

✕ Ignoring the Error Type
Jumping to the code without reading whether it's a NameError, TypeError, etc. The type tells you what category of fix you need.
✕ Off-by-One Indexing
Forgetting that Python indices start at 0. A list of length 5 has indices 0 through 4, not 1 through 5.
✕ Confusing TypeError and ValueError
Both involve type conversions, but TypeError means wrong type while ValueError means right type, wrong content.

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

Question 3 of 5

What error does int("hello") produce?

Question 4 of 5

A student writes:
data = {"name": "Bob"}
print(data["age"])
Which error is raised?

Question 5 of 5

What error type is raised, and why?