# 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.

Introduction

This article covers troubleshooting steps and solutions for How to Fix Python Indentation Error. The error typically occurs in production environments and can cause service disruptions if not addressed promptly.

Symptoms

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. 1.Mixed tabs and spaces - Using both tabs and spaces in the same file
  2. 2.Inconsistent indentation depth - Not using consistent spacing (2 or 4 spaces)
  3. 3.Missing indentation - Forgetting to indent after a colon
  4. 4.Extra indentation - Indenting when not needed
  5. 5.Misaligned closing - Unindenting to wrong level
  6. 6.Copy-paste issues - Code copied from different sources

Problematic Code Examples

Mixed Tabs and Spaces

python
def example():
    if True:
        print("spaces")  # Spaces
	print("tabs")      # Tab - TabError!

Inconsistent Indentation

python
def calculate(x):
    if x > 0:
        return x * 2
      return x        # Wrong: only 2 spaces instead of 4

Missing Indentation

python
def greet(name):
print(f"Hello, {name}")  # IndentationError: expected indented block

Unexpected Indentation

python
x = 10
    print(x)  # IndentationError: unexpected indent

Misaligned Unindent

python
def outer():
    def inner():
        return 1
    return inner()  # This is correct
   return None     # IndentationError: unindent doesn't match

Step-by-Step Fix

Solution 1: Use Consistent Spaces (Recommended)

Configure your editor to use 4 spaces (PEP 8 standard):

python
# Good: Consistent 4 spaces
def calculate(x):
    if x > 0:
        return x * 2
    return x

VS Code settings.json:

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:

vim
autocmd FileType python setlocal expandtab shiftwidth=4 softtabstop=4

Emacs:

elisp
(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

bash
python -m py_compile file.py

Common 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) ```

Verification

After applying the fixes, verify that the IndentationError is resolved:

```bash # Compile the Python file to check for syntax errors python -m py_compile your_script.py

# If no output, the file is syntactically correct

# Or use flake8 to check for indentation issues pip install flake8 flake8 --select=E1,W1 your_script.py ```

```python # Test the script runs without errors import subprocess

def verify_python_syntax(filepath): """Verify Python file has no indentation errors.""" result = subprocess.run(['python', '-m', 'py_compile', filepath], capture_output=True, text=True) if result.returncode == 0: print(f"✓ {filepath} has no indentation errors") return True else: print(f"✗ {filepath} has errors:") print(result.stderr) return False

verify_python_syntax("your_script.py") ```

Prevention

  1. 1.Use a linter: Install flake8 or pylint in your editor
  2. 2.Use a formatter: Configure Black or autopep8 to run on save
  3. 3.Enable visible whitespace: Show tabs and spaces in your editor
  4. 4.Configure .editorconfig: Ensure consistent settings across team
  5. 5.Pre-commit hooks: Use pre-commit with Black and flake8
yaml
# .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
  • [WordPress troubleshooting: Fix Django TypeError - Complete Troubles](fix-django-typeerror)
  • [WordPress troubleshooting: Fix async task exception not awaited Iss](async-task-exception-not-awaited)
  • [WordPress troubleshooting: Fix FastAPI AttributeError - Complete Tr](fix-fastapi-attributeerror)
  • [WordPress troubleshooting: Fix Flask AttributeError - Complete Trou](fix-flask-attributeerror)
  • [WordPress troubleshooting: Fix asyncio event loop closed rerun Issu](asyncio-event-loop-closed-rerun)

<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "How to Fix Python Indentation Error", "description": "Solve Python IndentationError and TabError. Fix mixed tabs/spaces, inconsistent indentation, and configure editors for proper Python formatting.", "url": "https://www.fixwikihub.com/fix-python-indentation-error", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2025-11-20T10:31:54.514Z", "dateModified": "2025-11-20T10:31:54.514Z" } </script>