Common errors
Understand Python's error types
Even experienced coders make mistakes. Understanding what different Python errors mean will help you fix problems quickly.
Errors you'll encounter
When Python can't execute your code, it stops and prints an error message. This message is called a "traceback."
You'll see the type of error at the very end of the traceback. Knowing these common types is a big step towards debugging.
FileNotFoundError
This error means Python tried to open a file that doesn't exist at the specified location. Double-check the file name and path.
with open('nonexistent_file.txt', 'r') as f:
content = f.read()ValueError
A ValueError occurs when a function receives an argument of the correct type, but an inappropriate value.
int("hello") # Trying to convert a non-numeric string to an integer
list.remove(10) # 10 is not in the listKeyError
Dictionaries store data as key-value pairs. A KeyError happens when you try to access a key that doesn't exist in the dictionary.
my_dict = {'name': 'Alice', 'age': 30}
print(my_dict['city']) # 'city' is not a key in my_dictif 'key' in my_dict: before trying to access it.IndexError
This error pops up when you try to access an index that is outside the bounds of a sequence (like a list or string).
my_list = [10, 20, 30]
print(my_list[3]) # List has elements at indices 0, 1, 2. Index 3 is out of range.
my_string = "Python"
print(my_string[10])TypeError
A TypeError means an operation was performed on an object of an inappropriate type. For example, trying to add a number and a string.
print(5 + "hello") # Cannot add an integer and a string
len(123) # len() expects a sequence, not an integerAttributeError
An AttributeError occurs when you try to access an attribute or method that an object does not possess.
my_number = 10
my_number.append(5) # Integers do not have an 'append' method
my_list = [1, 2, 3]
my_list.length() # Lists have a 'len()' function, not a 'length()' methodReading error messages
Pay attention to the last line, which tells you the error type and a brief description. The lines above it, the "traceback," show you the sequence of calls that led to the error.
- Start reading the traceback from the bottom up. The last line is the error type.
- The line just above that is usually *where* in your code the error happened.
- The lines further up show the chain of function calls leading to the error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'append'Common mistake patterns
- Misspellings: A common cause of
KeyErrororAttributeError. - Case sensitivity: Python is case-sensitive (
myVaris different frommyvar). - Off-by-one errors: Often leads to
IndexErrorwhen using loops or ranges. - Incorrect data types: Feeding a function a string when it expects a number, resulting in
TypeErrororValueError. - Forgetting to import: Trying to use a function or module you haven't imported yet.
Practice
Try these exercises to lock in what you just learned.
What's next?
With a basic understanding of these common errors, you're better equipped to read and understand Python's feedback. Practice writing code and making mistakes; it's the best way to learn!