An IndentationError: unexpected indent
in Python usually means that there’s an issue with inconsistent indentation. Here’s how you can fix it:
Common Causes and Fixes
- Mixing Spaces and Tabs
- Python enforces consistent indentation (use 4 spaces per indent).
- Avoid mixing tabs and spaces.
- Fix: Convert tabs to spaces in your editor.
def example(): print("Hello") # 4 spaces
- Accidental Extra Indentation
- Check if there’s an extra space before a statement.
print("Hello") # Extra space at the beginning
✅ Correct:print("Hello") # No extra indentation
- Incorrect Indentation in Blocks
- Make sure all lines inside a block are properly indented.
def my_function(): print("Hello") print("World") # Misaligned indentation
✅ Correct:def my_function(): print("Hello") print("World") # Aligned properly
- Unexpected Indentation Outside a Block
- Ensure there’s no unnecessary indentation before standalone statements.
x = 10 # This should not be indented
✅ Correct:x = 10 # Properly aligned
How to Fix in an Editor
- VS Code: Press
Ctrl + Shift + P
→ Select “Convert Indentation to Spaces”. - PyCharm: Go to Code → Reformat Code.
- Notepad++: Use Edit → Blank Operations → Tab to Space.