TabError: inconsistent use of tabs and spaces in indentation
What it means
The indentation in one block mixes tab characters and spaces in a way Python cannot read safely. A tab can look like 2, 4 or 8 spaces depending on the editor, so Python refuses to guess how deep the line is. Indent with spaces only and the error goes away.
1. One line indented with a tab, the others with spaces
This raises the error
Broken
temperature = 30
if temperature > 25:
print("It is hot") # starts with 4 spaces
print("Drink water") # starts with a tab
Output
Traceback (most recent call last):
File "<exec>", line 4
print("Drink water") # starts with a tab
^
TabError: inconsistent use of tabs and spaces in indentationThe fix
Fixed
temperature = 30
if temperature > 25:
print("It is hot") # 4 spaces
print("Drink water") # 4 spaces
Output
It is hot Drink water
Both lines now start with 4 spaces, so Python sees them at the same depth. Spaces look the same in every editor. Tabs do not.
2. Pasted lines that use tabs next to typed lines that use spaces
This raises the error
Broken
for n in range(3):
square = n * n # pasted: starts with a tab
print(n, square) # typed: starts with 8 spaces
Output
Traceback (most recent call last):
File "<exec>", line 3
print(n, square) # typed: starts with 8 spaces
TabError: inconsistent use of tabs and spaces in indentationThe fix
Fixed
for n in range(3):
square = n * n
print(n, square)
Output
0 0 1 1 2 4
Python treats a tab as reaching column 8, so these two lines would line up, but Python still refuses to mix the two characters in one block. Retyping the pasted indent with spaces fixes it.
When you see this error, check
- Indent with spaces only, 4 per level.
- Re-indent pasted code: delete the whitespace at the start of each pasted line and indent it again with spaces.
- Use your editor's "convert indentation to spaces" or "show whitespace" option to find the tabs.
- On your own computer,
python -m tabnanny yourfile.pylists the lines that mix tabs and spaces.
Related errors
All Python errors · How to read a traceback · Step through your code