How to Fix IndentationError unexpected indent in Python With Examples

Explanation:

The error IndentationError: unexpected indent occurs when Python finds an unexpected level of indentation. Python uses indentation to define blocks of code, so any irregularity can trigger this error.

Common Causes and How to Fix Them:

1. Code Starts with Unnecessary Indent

Incorrect:

    print("Hello")

Error:

IndentationError: unexpected indent

Fix:
Remove the extra indent:

print("Hello")

2. Mixing Tabs and Spaces

Incorrect:

if True:
→(tab)print("Line one")
→(space)print("Line two")

Fix:
Use only spaces or only tabs, not both:

if True:
    print("Line one")
    print("Line two")

3. Inconsistent Indentation Inside a Block

Incorrect:

if x > 0:
    print("Positive")
     print("More than zero")

Fix:
Make indentation consistent:

if x > 0:
    print("Positive")
    print("More than zero")

4. Indenting Code Outside Any Block

Incorrect:

print("Start")
    print("Too far")

Fix:
Remove the unnecessary indent:

print("Start")
print("Too far")

General Tips:

  • Turn on "Show Whitespace" in your code editor.
  • Use auto-format tools like autopep8, Black, or the format feature in VS Code.
  • In VS Code: press Shift + Alt + F to auto-format your file.

0 Comments:

Post a Comment