Interpreting Python Errors
Python errors tell you what is wrong with your code and where you can go to fix it. There are different types of errors (sometimes called exceptions) that can be raised.
Common exceptions: | |||
---|---|---|---|
ValueError | AttributeError | NameError | IndentationError |
ModuleNotFoundError | IndexError | SyntaxError | TypeError |
Example
You may have seen a red error that looks like this:
Here, we can see that we have a ValueError. A ValueError is when an operation or function receives an argument that has the right type (string, int) but an inappropriate value (“tree” vs. “142”).
This screenshot of the terminal gives us info about the error. It tells us which line it has a problem with, and we see that it says “line 88”.
int("tree")
is the specific block of code that is failing. We are trying to turn “tree” into an int, which doesn’t work.
“Invalid literal for int()
” means that we are using int() like a function—note the parentheses. The int()
function got an invalid literal: the string literal “tree” is invalid.
AttributeError
An AttributeError occurs when you try to use an attribute on a variable of a type that doesn’t support that attribute. In the example above, we tried to use the add
attribute on an variable (total) that is of type int
.
Note: Look at the last line reference to most likely identify where the error is. In this example, the piece that is broken would be on line 3, not line 8.
ModuleNotFoundError
A ModuleNotFoundError happens when you try to use a library that you have not properly included. In this case, we spelled “byubit” wrong, leading PyCharm to not recognize the library that we tried to import:
import byubits
We are then told:
ModuleNotFoundError: No module name 'byubits'
A ModuleNotFoundError can also occur when you try to import a library that doesn’t exist or one that you have not downloaded.
IndexError
This code is ran with this list: lst = [1, 2, 3, 4, 5]
An IndexError will happen when you try to access an element from an index such as a list or tuple that is not present.
Here, we are trying to access lst[5]
, which is the 6th item in the list. Our list only has 5 items, so it gives an error, telling us that our specified list index is out of range.
Note: Remember, indexing starts at 0, so our items in lst
would be indexed as items 0, 1, 2, 3, 4. When we try to access index 5 using lst[5]
, it doesn’t exist, even though there are 5 elements in our list.
NameError
NameErrors most commonly occur when built-in functions are misspelled, or when undefined variables are called.
In the above example, we created our list called lst
. When we printed it, we accidentally said print(lstt)
, misspelling the variable name, which threw an exception (along with a suggestion).
Note: the variable lstt
is considered an undefined variable, since we did not create it anywhere in our code.
Consider the following code:
dog = inupt("Dog: ")
print(dog)
This would give an error saying something like:
NameError: name inupt is not defined
This would be an example of spelling a built-in function wrong, by spelling input
as inupt
.
SyntaxError
Syntax errors are the most common type of error you will encounter. They occur when you write code that is not valid Python. You could think of it like grammar or punctuation for python. For example, if you forget to close a parenthesis, you will get a syntax error:
print("Hello, world!"
This code will produce the following error:
File "main.py", line 1
print("Hello, world!"
^
SyntaxError: unexpected EOF while parsing
In the screenshot above, we can see that a SyntaxError can also occur from forgetting a colon at the end of a for loop statement. This would be the same case with if statements, while loops, function definitions, etc.
IndentationError
An IndentationError is another error that has to do with formatting. These occur when a line is incorrectly indented.
Python requires specific indentation, such as when you use a for loop, if statement, or function definition.
Imagine the function containing line 7 looked like this:
def hi():
arr = [1, 2, 3, 4, 5]
for i in range(arr)
print(arr)
This throws an error because the line that starts with “for” should be indented back so it lines up with “arr”. The print statement should then be indented inside the for loop.
TypeError
Type errors occur in python when a data type used in an operation is inappropriate.
In this example, we are trying to divide a string by an integer.
num = "tree" / 5
This doesn’t work, because strings do not support division.
Our error tells us that the operator ”/” is not supported between operands ‘str’ and ‘int’.
Note: You can multiply strings by integers. For example, this:
num = 5
my_string = "hello " * num
print(my_string)
Would output:
hello hello hello hello hello