# How to Fix Python Indentation Error
IndentationError occurs when Python code has inconsistent or incorrect indentation. Unlike other languages, Python uses indentation to define code blocks.
Error Patterns
Basic Indentation Error
```text IndentationError: expected an indented block
IndentationError: unexpected indent
IndentationError: unindent does not match any outer indentation level ```
Tab Error
```text TabError: inconsistent use of tabs and spaces in indentation
TabError: inconsistent use of tabs and spaces in indentation (N,) ```
Common Causes
- 1.Mixed tabs and spaces - Using both tabs and spaces in the same file
- 2.Inconsistent indentation depth - Not using consistent spacing (2 or 4 spaces)
- 3.Missing indentation - Forgetting to indent after a colon
- 4.Extra indentation - Indenting when not needed
- 5.Misaligned closing - Unindenting to wrong level
- 6.Copy-paste issues - Code copied from different sources
Problematic Code Examples
Mixed Tabs and Spaces
def example():
if True:
print("spaces") # Spaces
print("tabs") # Tab - TabError!Inconsistent Indentation
def calculate(x):
if x > 0:
return x * 2
return x # Wrong: only 2 spaces instead of 4Missing Indentation
def greet(name):
print(f"Hello, {name}") # IndentationError: expected indented blockUnexpected Indentation
x = 10
print(x) # IndentationError: unexpected indentMisaligned Unindent
def outer():
def inner():
return 1
return inner() # This is correct
return None # IndentationError: unindent doesn't matchSolutions
Solution 1: Use Consistent Spaces (Recommended)
Configure your editor to use 4 spaces (PEP 8 standard):
# Good: Consistent 4 spaces
def calculate(x):
if x > 0:
return x * 2
return xVS Code settings.json:
{
"[python]": {
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.formatOnSave": true
}
}PyCharm:
Settings > Editor > Code Style > Python > Tab size: 4, Use tab character: OFF
Vim/Neovim:
autocmd FileType python setlocal expandtab shiftwidth=4 softtabstop=4Emacs:
(add-hook 'python-mode-hook
(lambda ()
(setq indent-tabs-mode nil)
(setq python-indent 4)))Solution 2: Convert Tabs to Spaces
In Python script:
```python # Convert tabs to spaces in a file def tabs_to_spaces(filename, spaces_per_tab=4): with open(filename, 'r') as f: content = f.read()
content = content.replace('\t', ' ' * spaces_per_tab)
with open(filename, 'w') as f: f.write(content) ```
Using command line:
```bash # Expand tabs to spaces expand -t 4 input.py > output.py
# Or use unexpand to convert spaces to tabs (not recommended) ```
Solution 3: Use autopep8
```bash pip install autopep8
# Fix a file autopep8 --in-place --aggressive --aggressive file.py
# Fix all Python files in directory autopep8 --in-place --aggressive --aggressive -r . ```
Solution 4: Use Black Formatter
```bash pip install black
# Format a file black file.py
# Format all Python files black . ```
Solution 5: Use flake8 for Detection
```bash pip install flake8
# Check for indentation errors flake8 --select=E1,W1 file.py ```
Solution 6: Fix Specific Patterns
#### Empty Blocks
```python # Wrong def empty_function(): pass # But missing indentation
# Correct def empty_function(): pass ```
#### Nested Conditions
```python # Wrong if condition1: if condition2: do_something() else: # Wrong level pass
# Correct if condition1: if condition2: do_something() else: pass ```
#### Multi-line Statements
```python # Wrong result = some_function( arg1, arg2, ) # Closing paren misaligned
# Correct result = some_function( arg1, arg2, ) # Aligned with statement start ```
Solution 7: Fix Copy-Paste Issues
```python # Use reindent script import re
def reindent_code(code, spaces=4): lines = code.split('\n') result = [] for line in lines: stripped = line.lstrip() if stripped: # Count original indentation indent = len(line) - len(stripped) # Reapply with consistent spaces result.append(' ' * spaces * (indent // 8) + stripped) else: result.append('') return '\n'.join(result) ```
Solution 8: Editor Configuration File
Create .editorconfig in your project:
```ini root = true
[*.py] indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true ```
Debugging Indentation Errors
Visualize Whitespace
VS Code:
- View > Render Whitespace
- Or add to settings: "editor.renderWhitespace": "all"
Vim:
``vim
:set list
:set listchars=tab:>-,space:.,trail:~
Less command:
``bash
cat -A file.py # Shows tabs as ^I and line endings as $
Python Verbose Mode
python -m py_compile file.pyCommon Patterns and Their Fixes
After Function Definition
```python # Wrong def greet(): print("Hello") # Missing indent
# Correct def greet(): print("Hello") ```
After Control Structures
```python # Wrong if x > 0: return x # Missing indent
# Correct if x > 0: return x ```
Hanging Indent
```python # Wrong (hanging indent with wrong alignment) def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
# Correct (align with opening delimiter) def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
# Or (hanging indent with extra level) def long_function_name( var_one, var_two, var_three, var_four): print(var_one) ```
Prevention Tips
- 1.Use a linter: Install flake8 or pylint in your editor
- 2.Use a formatter: Configure Black or autopep8 to run on save
- 3.Enable visible whitespace: Show tabs and spaces in your editor
- 4.Configure .editorconfig: Ensure consistent settings across team
- 5.Pre-commit hooks: Use pre-commit with Black and flake8
# .pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8