Here in Stack Overflow we often see duplicates talking about the same errors:
"ImportError: No module named '??????',
SyntaxError: invalid syntax or
NameError: name '???' is not defined. This is an effort to reduce them and to have some documentation to link to.
assert statement exists in almost every programming language. When you do:
It's equivalent to this:
Assertions can include an optional message, and you can disable them when you're done debugging.
Note: the built-in variable debug is True under normal circumstances, False when optimization is requested (command line option -O). Assignments to debug are illegal. The value for the built-in variable is determined when the interpreter starts.
Error raised when the user presses the interrupt key, normally Ctrl + C or del.
You tried to calculate
1/0 which is undefined. See this example to find the divisors of a number:
ZeroDivisionError because the
for loop assigns that value to
x. Instead it should be:
IndentationErrors (or indentation SyntaxErrors)
In most other languages indentation is not compulsory, but in Python (and other languages: early versions of FORTRAN, Makefiles, Whitespace (esoteric language), etc.) that is not the case, what can be confusing if you come from another language, if you were copying code from an example to your own, or simply if you are new.
IndentationError/SyntaxError: unexpected indent
This exception is raised when the indentation level increases with no reason.
There is no reason to increase the level here:
Here there are two errors: the last one and that the indentation does not match any indentation level. However just one is shown:
IndentationError/SyntaxError: unindent does not match any outer indentation level
Appears you didn't unindent completely.
IndentationError: expected an indented block
After a colon (and then a new line) the indentation level has to increase. This error is raised when that didn't happen.
Note: Use the keyword
pass (that makes absolutely nothing) to just put an
definition but not say what will happen if called/condition is true (but do it later, or in the case of
except: just do nothing):
IndentationError: inconsistent use of tabs and spaces in indentation
How to avoid this error
Don't use tabs. It is discouraged by
PEP8, the style guide for Python.
- Set your editor to use 4 spaces for indentation.
- Make a search and replace to replace all tabs with 4 spaces.
- Make sure your editor is set to display tabs as 8 spaces, so that you can realize easily that error and fix it.
See this question if you want to learn more.
NameError: name '???' is not defined
Is raised when you tried to use a variable, method or function that is not initialized (at least not before). In other words, it is raised when a requested local or global name is not found. It's possible that you misspelt the name of the object or forgot to
import something. Also maybe it's in another scope. We'll cover those with separate examples.
It's simply not defined nowhere in the code
It's possible that you forgot to initialize it, specially if it is a constant
Maybe it's defined later:
Or it wasn't
Python scopes and the LEGB Rule:
The so-called LEGB Rule talks about the Python scopes. It's name is based on the different scopes, ordered by the correspondent priorities:
- Local: Variables not declared global or assigned in a function.
- Enclosing: Variables defined in a function that is wrapped inside another function.
- Global: Variables declared global, or assigned at the top-level of a file.
- Built-in: Variables preassigned in the built-in names module.
As an example:
d is accesible because the
for loop does not mark a new scope, but if it did, we would have an error and its behavior would be similar to:
NameError: name 'd' is not defined
Syntax Error on good code
The gross majority of the time a SyntaxError which points to an uninteresting line means there is an issue on the line before it (in this example, it's a missing parenthesis):
The most common reason for this issue is mismatched parentheses/brackets, as the example shows.
There is one major caveat for print statements in Python 3:
print() function, so you want:
These exceptions are caused when the type of some object should be different
TypeError: [definition/method] takes ? positional arguments but ? was given
A function or method was called with more (or less) arguments than the ones it can accept.
If more arguments are given:
If less arguments are given:
Note: if you want use an unknown number of arguments, you can use
**kwargs. See *args and **kwargs
TypeError: unsupported operand type(s) for [operand]: '???' and '???'
Some types cannot be operated together, depending on the operand.
+ is used to concatenate and add, but you can't use any of them for both types. For instance, trying to make a
set by concatenating (
'tuple1' gives the error. Code:
Some types (eg:
string) use both
+ but for different things:
Or they may not be even used for anything:
But you can for example add a
float to an
TypeError: '???' object is not iterable/subscriptable:
For an object to be iterable it can take sequential indexes starting from zero until the indexes are no longer valid and a
IndexError is raised (More technically: it has to have an
__iter__ method which returns an
__iterator__, or which defines a
__getitem__ method that does what was previously mentioned).
Here we are saying that
bar is the zeroth item of 1. Nonsense:
This is a more discrete version: In this example
for tries to set
amount, the first item in an iterable but it can't because amount is an int:
TypeError: '???' object is not callable
You are defining a variable and calling it later (like what you do with a function or method)