Learn Without Walls
← Module 12 Home Lesson 1 of 4 Next Lesson →

Lesson 12.1: Common Python Errors

What you will learn:

1. Reading Error Messages

When Python encounters an error, it displays a traceback - a message that tells you what went wrong and where. Learning to read these messages is one of the most valuable skills you can develop.

Traceback: Python's error report that shows the file, line number, and type of error that occurred. Always read from the bottom up - the last line tells you the error type and message.

Anatomy of an Error Message

Traceback (most recent call last):
  File "program.py", line 3, in <module>
    print(score / 0)
          ~~~~~~^~~
ZeroDivisionError: division by zero

This tells you: the error is in program.py, on line 3, and it is a ZeroDivisionError caused by dividing by zero.

2. SyntaxError

A SyntaxError means Python cannot understand your code because it does not follow Python's grammar rules. This happens before your code runs.

Common Causes

# Missing colon
if x > 5       # SyntaxError! Missing :
    print("big")

# Mismatched parentheses
print("hello"  # SyntaxError! Missing closing )

# Wrong assignment
5 = x            # SyntaxError! Can't assign to a number
SyntaxError: expected ':'
Fix: Check for missing colons, parentheses, quotes, or commas. Python usually points to where it got confused.

3. NameError

A NameError occurs when you use a variable or function name that Python does not recognize.

Common Causes

# Misspelled variable name
username = "Alice"
print(usrname)     # NameError! Typo: usrname

# Using a variable before defining it
print(score)       # NameError! score not defined yet
score = 100

# Forgetting to import a module
result = math.sqrt(16)  # NameError! math not imported
NameError: name 'usrname' is not defined
Fix: Check your spelling carefully. Make sure variables are defined before you use them. Import modules before using them.

4. TypeError

A TypeError occurs when you try to perform an operation on an incompatible data type.

Common Causes

# Adding a string and a number
result = "Age: " + 25    # TypeError!
# Fix: "Age: " + str(25)

# Calling a non-callable
length = 5
length()                   # TypeError! int is not callable

# Wrong number of arguments
def greet(name):
    print(f"Hello, {name}")
greet()                    # TypeError! Missing argument
TypeError: can only concatenate str (not "int") to str
Fix: Convert types explicitly with str(), int(), or float(). Check that you are passing the right number of arguments to functions.

5. ValueError

A ValueError occurs when a function receives a value of the right type but an inappropriate value.

Common Causes

# Converting non-numeric string to int
number = int("hello")     # ValueError!

# Converting float string to int directly
number = int("3.14")      # ValueError!
# Fix: int(float("3.14"))

# Too many values to unpack
x, y = [1, 2, 3]         # ValueError!
ValueError: invalid literal for int() with base 10: 'hello'
Fix: Validate user input before converting. Use try/except to handle invalid input gracefully (covered in the next lesson).

6. IndexError and KeyError

IndexError: List Index Out of Range

colors = ["red", "blue", "green"]

print(colors[0])    # red - works fine
print(colors[3])    # IndexError! Only indices 0, 1, 2 exist
print(colors[-1])   # green - negative indices work
IndexError: list index out of range

KeyError: Dictionary Key Not Found

student = {"name": "Alice", "age": 20}

print(student["name"])    # Alice - works fine
print(student["grade"])   # KeyError! "grade" not in dictionary

# Fix: use .get() with a default value
print(student.get("grade", "N/A"))  # N/A - no error!
KeyError: 'grade'
Fix for IndexError: Check list length with len() before accessing. Use negative indices for the end.
Fix for KeyError: Use .get(key, default) or check with if key in dictionary:.

Check Your Understanding

What type of error would you get from this code: print("Score: " + 95)?

TypeError - you cannot concatenate a string and an integer. Fix it with print("Score: " + str(95)) or use an f-string: print(f"Score: {95}").

Key Takeaways

← Module 12 Home Lesson 1 of 4 Next Lesson →