Why do I get an indentation error in Python?
Short answerPython uses indentation to define code blocks, so inconsistent indentation causes IndentationError. This happens when lines in the same block have different leading whitespace or when a block isn't indented after a colon.
What causes it
Python expects consistent indentation within a block. If you mix tabs and spaces, or if you indent some lines but not others in the same block, Python raises IndentationError: unexpected indent or expected an indented block.
The error message shows the line where the problem was detected. Often the real issue is on the previous line, such as a missing colon or an extra space.
- Mixing tabs and spaces in the same file
- Forgetting to indent after a colon (if, for, while, def, class)
- Indenting a line that shouldn't be indented
- Using inconsistent number of spaces (e.g., 2 spaces then 4 spaces)
How to fix it
Configure your editor to show whitespace characters and to insert spaces instead of tabs. The official Python style guide (PEP 8) recommends 4 spaces per indentation level.
If you have mixed tabs and spaces, convert all tabs to spaces. Many editors have a 'Convert indentation to spaces' command. Then re-indent the problematic block consistently.
- Use 4 spaces per indentation level consistently
- Set your editor to replace tabs with spaces
- Check that all lines in a block have the same indentation
- Use a linter like flake8 to catch indentation issues
Common mistakes
- Thinking Python cares about the number of spaces as long as it's consistent; it does, but mixing tabs and spaces is still an error.
- Assuming the error is on the reported line; it's often on the previous line.
- Believing that any indentation is fine as long as it looks aligned; Python requires exact consistency.
