Incorrect indentation
Raised when a line of code is not indented correctly. Python uses indentation to define the structure of code blocks, so this is a critical syntax issue.
- 1Missing indentation for a code block that requires it (e.g., after an `if` statement).
- 2Having inconsistent indentation levels within the same code block.
- 3Mixing tabs and spaces for indentation in the same file (a common hidden issue).
This error occurs when a code block is expected after a statement ending in a colon, but it is not indented.
def my_function():
print("This line is not indented correctly")
expected output
File "<stdin>", line 2
print("This line is not indented correctly")
^
IndentationError: expected an indented blockFix 1
Add proper indentation
WHEN After any line ending with a colon (`:`), such as `def`, `class`, `if`, `for`, `while`.
def my_function():
print("This line is now correctly indented")
Why this works
Indenting the line with four spaces places it inside the `my_function` block, as Python requires.
Fix 2
Configure your editor to use spaces for tabs
WHEN To prevent mixing tabs and spaces, which Python treats as different indentation levels.
# No code, this is an editor configuration. # In VS Code, set "editor.insertSpaces": true and "editor.tabSize": 4.
Why this works
This ensures that pressing the Tab key inserts a consistent number of spaces, avoiding `IndentationError` from mixed whitespace.
def foo():
print("oops") # IndentationError: expected an indented blocktry:
compile("def f():\npass", "<string>", "exec")
except IndentationError as e:
print(f"Bad indentation at line {e.lineno}")# .editorconfig # [*.py] # indent_style = space # indent_size = 4 # Prevents mixed tabs/spaces.
✕ Randomly adding or removing spaces until the error disappears
This can lead to incorrect program logic and create further indentation errors elsewhere. Understand why the indentation is required.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev