IndentationError: unexpected indent

Loading

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

  1. 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
  2. Accidental Extra Indentation
    • Check if there’s an extra space before a statement.
    ❌ Incorrect: print("Hello") # Extra space at the beginning ✅ Correct: print("Hello") # No extra indentation
  3. Incorrect Indentation in Blocks
    • Make sure all lines inside a block are properly indented.
    ❌ Incorrect: def my_function(): print("Hello") print("World") # Misaligned indentation ✅ Correct: def my_function(): print("Hello") print("World") # Aligned properly
  4. Unexpected Indentation Outside a Block
    • Ensure there’s no unnecessary indentation before standalone statements.
    ❌ Incorrect: 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.

Leave a Reply

Your email address will not be published. Required fields are marked *