Python for AIPython for AI
Python Basics

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.

python
with open('nonexistent_file.txt', 'r') as f:
    content = f.read()
Make sure your file path is correct, especially when moving between different operating systems (Windows, macOS, Linux).

ValueError

A ValueError occurs when a function receives an argument of the correct type, but an inappropriate value.

python
int("hello") # Trying to convert a non-numeric string to an integer
list.remove(10) # 10 is not in the list

KeyError

Dictionaries store data as key-value pairs. A KeyError happens when you try to access a key that doesn't exist in the dictionary.

python
my_dict = {'name': 'Alice', 'age': 30}
print(my_dict['city']) # 'city' is not a key in my_dict
You can check if a key exists using if '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).

python
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.

python
print(5 + "hello") # Cannot add an integer and a string
len(123) # len() expects a sequence, not an integer

AttributeError

An AttributeError occurs when you try to access an attribute or method that an object does not possess.

python
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()' method

Reading 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.
text
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 KeyError or AttributeError.
  • Case sensitivity: Python is case-sensitive (myVar is different from myvar).
  • Off-by-one errors: Often leads to IndexError when using loops or ranges.
  • Incorrect data types: Feeding a function a string when it expects a number, resulting in TypeError or ValueError.
  • 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.

Quiz
Not started
Calling a variable that doesn't exist raises…

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!