Lesson 12.1: Common Python Errors
What you will learn:
- How to read Python error messages (tracebacks)
- Six common error types and what causes each one
- How to fix each type of error
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.
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
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
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
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!
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
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!
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
- SyntaxError: Your code has a grammar mistake (missing colon, parenthesis, etc.)
- NameError: You used a name that Python does not recognize (typo or undefined variable)
- TypeError: You used the wrong data type for an operation
- ValueError: The value is wrong even though the type is right
- IndexError: You tried to access a list index that does not exist
- KeyError: You tried to access a dictionary key that does not exist
- Always read error messages from the bottom up