curriculum/challenges/english/blocks/lecture-understanding-error-handling/68420bacf395f15cd73f8118.md
When writing Python code, it's common to run into errors. Understanding these errors is key to debugging your code quickly and efficiently. These messages tell you exactly what went wrong, if you know how to read them.
Common Python errors include SyntaxError, NameError, TypeError, IndexError, and AttributeError. These occur when Python doesn't understand your code, or when your logic doesn't match the data you're working with.
Here is an example of a SyntaxError:
print("Hello, world!"
# SyntaxError: unexpected EOF while parsing
This line is missing a closing parenthesis. Python raises a SyntaxError because the code doesn't follow proper syntax rules.
Here is an example of a NameError:
print(name)
# NameError: name 'name' is not defined
You're trying to print a variable that hasn't been defined yet. Python raises a NameError when it can't find a variable by that name.
Here is an example of a TypeError:
5 + "5"
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
You can't add an integer and a string together. Python raises a TypeError when you try to perform an operation on incompatible data types.
Here is an example of an IndexError:
my_list = [1, 2, 3]
print(my_list[5])
# IndexError: list index out of range
You're trying to access an index that doesn't exist in the list. Python raises an IndexError when you go out of bounds.
Here is an example of an AttributeError:
num = 42
num.append(5)
# AttributeError: 'int' object has no attribute 'append'
The int object doesn't have an append() method. Python raises an AttributeError when you try to use a method or property that doesn't exist for that data type.
Recognizing common Python error messages helps you fix problems faster. Instead of guessing, read the error message carefully, it often tells you exactly what went wrong and where to look.
What does a NameError mean in Python?
A variable is misspelled.
Refer back to the section of the lesson on NameError.
A variable is not defined.
An index is out of range.
Refer back to the section of the lesson on NameError.
A data type is incorrect.
Refer back to the section of the lesson on NameError.
2
Which error occurs when trying to add an integer to a string?
NameError
Refer back to type errors in the lesson.
SyntaxError
Refer back to type errors in the lesson.
TypeError
AttributeError
Refer back to type errors in the lesson.
3
What causes an IndexError?
A function is missing.
Refer back to the section on IndexError in the lesson.
A string is not formatted correctly.
Refer back to the section on IndexError in the lesson.
Accessing an element outside the bounds of an iterable.
Using an undefined variable.
Refer back to the section on IndexError in the lesson.
3