What Is IndentationError in Python? Causes & Fixes

Python IndentationError causes and fixes
Spread the love

22 min read

Table of Contents

What Is IndentationError in Python?

A Python IndentationError is one of the most common errors developers encounter when writing Python code, especially when learning the language or working with nested code blocks. Unlike programming languages that use curly braces to define blocks, Python relies on indentation and whitespace to determine how statements are grouped. Even a single misplaced space, an unexpected tab, or a missing indentation level can prevent a Python program from running.

Understanding Python indentation rules is essential for writing readable, maintainable, and error-free code. Whether you are working with functions, classes, loops, conditional statements, or exception handling, consistent indentation helps Python interpret your code correctly. Fortunately, most indentation errors are easy to fix once you understand their causes and know how to identify the problematic line.

In this guide, you will learn what an IndentationError in Python means, why it occurs, how to fix common indentation problems, and how to prevent them using code editors, linters, and automated formatting tools. You will also explore practical Python indentation error examples and step-by-step solutions for popular development environments.

What Is IndentationError in Python?

An IndentationError occurs when Python encounters unexpected or incorrect indentation that violates its syntax rules. Indentation refers to the spaces or tabs placed at the beginning of a line of code.

Python uses indentation to identify code blocks instead of relying on braces such as {}. Statements belonging to the same block must follow a consistent indentation level, while nested blocks require additional indentation.

Consider this example:

if 10 > 5:
    print("10 is greater than 5")

The print() statement is indented by four spaces, indicating that it belongs to the if statement’s body.

Now consider an incorrect example:

if 10 > 5:
print("10 is greater than 5")

Python raises an error because the statement following the if condition must be indented.

This is a typical example of an IndentationError. Python cannot determine a valid block structure because the required indentation is missing.

Why Python Requires Indentation

Understanding why Python requires indentation helps explain why these errors occur so frequently.

Python uses indentation to represent the structure of a program. It identifies which statements belong inside functions, classes, loops, conditional statements, and other compound statements.

For example:

def greet():
    print("Hello")
    print("Welcome to Python")

greet()

Both print() statements belong to the greet() function because they share the same indentation level.

If the second statement is moved outside the function accidentally, the program’s behavior changes. If the indentation is inconsistent or unexpected, Python may raise an error before executing the program.

Consistent indentation therefore serves two purposes: it makes code easier to read and communicates the intended program structure to the Python interpreter.

Common Types of Python IndentationError

Python provides different error messages to help developers identify indentation problems. Learning these messages makes Python IndentationError troubleshooting much easier.

1. Python Unexpected Indent

A Python unexpected indent error occurs when a line begins with indentation that is not expected in its current context.

Example:

name = "Alex"
    age = 25

print(name)

The age assignment contains unnecessary leading spaces. Because it does not belong to an indented block, Python raises an error.

How to fix it: Remove the unnecessary indentation.

name = "Alex"
age = 25

print(name)

How Do You Fix Unexpected Indent in Python?

To fix unexpected indentation, check the line mentioned in the traceback and compare it with the surrounding statements. Remove extra leading spaces unless the statement intentionally belongs to a function, loop, condition, or another valid block.

Unexpected indentation after function definition can also occur when a function declaration is followed by an incorrectly indented statement elsewhere in the code.

2. Expected an Indented Block

The expected an indented block error appears when a statement requires a body but the following line is not indented correctly.

For example:

if True:
print("This statement needs indentation")

The if statement requires an indented body.

Correct code:

if True:
    print("This statement is correctly indented")

Expected Indented Block After If Statement

An expected indented block after an if statement usually means that the code following the condition is missing indentation.

The same issue can occur with elif and else statements.

Incorrect:

if score >= 50:
print("Passed")
else:
print("Failed")

Correct:

if score >= 50:
    print("Passed")
else:
    print("Failed")

Expected Indented Block After For Loop

A for loop requires an indented body.

Incorrect:

for number in range(3):
print(number)

Correct:

for number in range(3):
    print(number)

The same principle applies to while loops, function definitions, class definitions, and exception-handling blocks.

3. Unindent Does Not Match Any Outer Indentation Level

The unindent does not match any outer indentation level error occurs when a line moves back to an indentation level that does not match a previously established block.

Example:

def calculate():
    total = 10
      result = 20
    return total + result

The result assignment has an inconsistent indentation level.

Correct code:

def calculate():
    total = 10
    result = 20
    return total + result

Python expects statements within the same block to use a consistent indentation level.

This error frequently occurs when developers manually insert spaces, paste code from different sources, or combine tabs and spaces.

4. TabError: Inconsistent Use of Tabs and Spaces

A TabError is closely related to IndentationError. It commonly appears when Python encounters inconsistent use of tabs and spaces in indentation.

Example:

def example():
    print("First line")
	print("Second line")

The first statement may use spaces, while the second uses a tab. Depending on the actual whitespace and context, Python can raise a TabError.

How to fix it: Convert indentation throughout the affected block to spaces, preferably four spaces per level.

TabError is a specific indentation-related error, so understanding the difference between IndentationError and TabError helps narrow down the cause.

Python Indentation Rules You Must Know

Following Python indentation rules consistently is the best way to avoid unnecessary syntax errors.

Use Four Spaces for Each Indentation Level

PEP 8, Python’s widely used style guide, recommends four spaces per indentation level.

Correct:

def greet():
    if True:
        print("Hello")

The function body uses four spaces, while the nested conditional body uses eight spaces.

How Many Spaces Should Python Indentation Use?

Four spaces per indentation level is the standard recommendation for Python code. You can configure an editor to insert four spaces automatically whenever you press Tab.

Although Python can process certain alternative indentation styles, using four spaces improves consistency and makes code easier to maintain.

Maintain Consistent Indentation Within a Block

Statements at the same logical level should have matching indentation.

Incorrect:

if True:
    print("First")
      print("Second")

Correct:

if True:
    print("First")
    print("Second")

Indent After Compound Statements

Statements ending with a colon generally introduce a block, including if, for, while, def, class, try, except, finally, with, and other compound statements.

For example:

try:
    value = int("123")
except ValueError:
    print("Invalid number")
finally:
    print("Finished")

Each block is indented according to its position in the program.

Understand Nested Indentation

Nested blocks require additional indentation for each new level.

for number in range(3):
    if number % 2 == 0:
        print(number)

The for loop body uses four spaces, while the nested if body uses eight.

Python Indentation Error Examples in Different Code Structures

Indentation problems can appear in almost any Python program. The following Python indentation error examples demonstrate how to recognize and correct them.

Python Indentation Error in Functions

A function definition introduces a block that must contain an indented statement.

Incorrect:

def add(a, b):
return a + b

Correct:

def add(a, b):
    return a + b

An indentation error after def typically occurs because the function body is not indented.

If you intentionally want an empty function body while developing the program, use pass:

def add(a, b):
    pass

Python Indentation Error After Class

Class definitions also require an indented body.

Incorrect:

class Student:
name = "Alex"

Correct:

class Student:
    name = "Alex"

You can also define methods inside a class, using an additional indentation level.

class Student:
    def introduce(self):
        print("Hello")

The class body and method body have different indentation levels.

Python Indentation Error in Loops

Both for loops and while loops require correctly indented bodies.

Incorrect:

for i in range(5):
print(i)

Correct:

for i in range(5):
    print(i)

For a while loop:

count = 0

while count < 3:
    print(count)
    count += 1

A missing indentation level after a loop declaration can trigger an expected indented block error.

Python Indentation Error in If-Else Statements

Conditional statements use indentation to define which instructions execute when a condition is true or false.

age = 20

if age >= 18:
    print("Adult")
else:
    print("Minor")

The if and else statements align with each other, while their bodies are indented.

Python Indentation Error After Try

Exception handling requires properly indented blocks following try, except, and optionally else and finally.

Incorrect:

try:
print(10 / 2)
except ZeroDivisionError:
print("Cannot divide by zero")

Correct:

try:
    print(10 / 2)
except ZeroDivisionError:
    print("Cannot divide by zero")

The error is not caused by exception handling itself. It occurs because the statements inside the blocks are not indented.

Python Indentation Error in Nested Loops

Nested loops can become difficult to read when several indentation levels are involved.

Incorrect:

for i in range(2):
    for j in range(2):
    print(i, j)

Correct:

for i in range(2):
    for j in range(2):
        print(i, j)

Each inner block needs an additional indentation level.

Python Indentation Error in Nested Functions

A nested function is a function defined inside another function.

def outer():
    message = "Hello"

    def inner():
        print(message)

    inner()

outer()

The inner() definition belongs to the outer function, and its body belongs to the inner function.

Misaligning either block can cause indentation errors or change the program’s intended structure.

Python Indentation Error in List Comprehensions

List comprehensions can span multiple lines, so their indentation must remain syntactically valid.

numbers = [
    number
    for number in range(10)
    if number % 2 == 0
]

print(numbers)

This formatting is valid because the expression is inside brackets. Unlike ordinary compound statements, continuation lines inside parentheses, brackets, and braces can use flexible indentation.

A poorly formatted multiline comprehension may be harder to understand, but not every visual indentation inconsistency causes an IndentationError. Python evaluates the actual syntax and whitespace context.

Python Indentation Error in Lambda Functions

Lambda functions create small anonymous functions, and their expressions do not use an indented function body.

Correct:

square = lambda number: number ** 2
print(square(4))

A lambda expression does not require the same block indentation as a function declared with def. However, placing a lambda assignment under an incorrectly indented statement can still cause an indentation error.

Python Indentation Error in Multiline Strings

Multiline strings can contain leading spaces as part of their content.

message = """Hello
    Welcome to Python
    Learn indentation"""

The spaces inside this string are part of the string’s content. They do not automatically represent indentation for executable statements.

An indentation error in multiline strings usually occurs when surrounding Python statements are incorrectly indented or when copied code introduces whitespace outside the string.

How to Fix IndentationError in Python: Step-by-Step Solutions

If your program displays an IndentationError, follow these steps to identify and resolve it.

Step 1: Read the Error Message

Run your Python program and inspect the traceback.

For example:

File "example.py", line 3
    print("Hello")
    ^
IndentationError: expected an indented block after 'if' statement on line 2

This message identifies the file, line number, and type of error.

Step 2: Inspect the Line Before the Error

The line highlighted by Python is not always the original source of the problem. Sometimes, the actual mistake occurs in the preceding statement.

Check whether the previous line ends with a colon and whether its body is indented correctly.

Step 3: Check Tabs vs Spaces in Python

Mixed tabs and spaces are a frequent source of indentation problems.

Open the file in a code editor and enable whitespace visibility if available. Inspect whether indentation consists of spaces, tabs, or a mixture of both.

How to Convert Tabs to Spaces in Python

Most modern editors provide commands for converting indentation.

A typical process is:

  1. Open the Python file.
  2. Find the indentation settings.
  3. Select spaces instead of tabs.
  4. Choose four spaces per indentation level.
  5. Convert existing indentation to spaces.
  6. Save and rerun the program.

The exact command depends on the editor. Verify the affected block after conversion because automated replacement may not preserve the intended structure in every situation.

Step 4: Fix Mixed Tabs and Spaces

If Python reports inconsistent use of tabs and spaces, standardize the entire affected block.

For example, do not indent one statement with a tab and the next with four spaces. Configure your editor to insert spaces when you press Tab, then correct existing lines.

Step 5: Restore the Correct Block Structure

Check every function, class, conditional statement, loop, and exception-handling block.

For each block:

  • Keep statements at the same logical level aligned.
  • Indent statements inside the block.
  • Reduce indentation when returning to an outer block.
  • Make sure each compound statement has a valid body.

Step 6: Run the Program Again

Save the file and execute it again. Python may reveal additional indentation errors after the first one is fixed.

Continue correcting the reported lines until the program runs successfully.

Fixing Python IndentationError in Popular Code Editors

The process of correcting indentation depends partly on the environment in which you write Python code.

Python IndentationError in VS Code

Visual Studio Code includes indentation settings and Python extensions that help identify formatting issues.

To fix an indentation error in VS Code:

  1. Open the Python file.
  2. Inspect the highlighted line and traceback.
  3. Check the indentation indicator in the editor.
  4. Open the Command Palette.
  5. Search for Convert Indentation to Spaces.
  6. Set the tab size to four spaces.
  7. Save the file and run it again.

You can also enable whitespace rendering to see tabs and spaces more clearly.

How to Fix Indentation Errors in VS Code Automatically

VS Code supports automatic indentation and formatting features. Configure the editor to use spaces and install a Python formatter such as Black or Ruff.

Automatic formatting can correct many inconsistent indentation problems, but you should still review syntax errors and make sure the code’s logical structure is correct.

Python IndentationError in PyCharm

PyCharm offers configurable code-style settings for Python.

To resolve indentation issues:

  1. Open the affected file.
  2. Inspect the line mentioned in the error.
  3. Open the Python code-style settings.
  4. Configure indentation to use four spaces.
  5. Convert existing indentation if necessary.
  6. Reformat the code and rerun the script.

PyCharm’s reformatting functionality helps standardize whitespace. However, it cannot always repair code with incomplete or invalid syntax.

Python IndentationError in Jupyter Notebook

Python IndentationError in Jupyter Notebook commonly occurs when entering code into a cell with incorrect indentation.

Example:

if True:
print("Hello")

Correct the cell before executing it:

if True:
    print("Hello")

When copying code between cells, inspect the leading spaces and ensure that each block is complete.

If an error persists, review the entire cell rather than only the highlighted line.

Python IndentationError in Google Colab

Google Colab uses Python notebooks, so the underlying indentation rules are the same as those in standard Python scripts.

To fix an error:

  1. Open the cell containing the traceback.
  2. Find the indicated line.
  3. Check the surrounding block.
  4. Replace inconsistent indentation with four spaces.
  5. Execute the cell again.

If you copy code from a website, document, or AI-generated response, verify that the indentation is preserved when you paste it into Colab.

Indentation Error in Online Python Compilers

Online Python compilers sometimes display indentation errors when code is copied from tutorials or other editors.

The compiler itself is not necessarily the problem. Hidden whitespace, missing block bodies, or incorrect nesting may be responsible.

Paste the code into a plain-text editor, normalize indentation, and verify that every compound statement contains a valid body before running it again.

Python Whitespace Errors: Tabs, Spaces, and Formatting

Python whitespace errors are not limited to indentation. Spaces and tabs can also affect how code is interpreted around multiline expressions, strings, and continuation lines.

Tabs vs Spaces in Python

A tab is a whitespace character that may display differently depending on editor settings. Spaces are individual whitespace characters.

Python can process tabs in indentation, but mixing them with spaces is discouraged because it can produce inconsistent visual alignment and TabError.

Using spaces exclusively is the most reliable approach for new Python projects.

Python 2 vs Python 3 Indentation

Python 2 and Python 3 both use indentation to define code blocks. Neither version uses braces as the standard method for defining function, class, loop, or conditional bodies.

Both versions support indentation-based block structure, and mixing tabs and spaces can cause problems in either version.

Python 3 is the modern standard for new development. Its indentation rules remain consistent with the widely used PEP 8 recommendation of four spaces per indentation level.

PEP 8 Indentation Guidelines

PEP 8 provides recommendations for Python code formatting, including:

  • Use four spaces per indentation level.
  • Maintain consistent indentation within a block.
  • Use consistent continuation-line formatting.
  • Avoid mixing tabs and spaces.
  • Format multiline expressions so that their structure is easy to understand.

Following these recommendations makes code easier to review, debug, and maintain across teams.

Python Formatter Tools for Automatic Indentation

Python formatter tools help enforce consistent formatting and reduce avoidable whitespace problems.

Format Python Code with Black

Black is an opinionated Python code formatter that automatically formats valid Python code according to its conventions.

You can install it using:

python -m pip install black

Format a file with:

python -m black example.py

Black can standardize indentation, spacing, and other formatting details. It is especially useful when working on larger codebases.

However, Black is not a universal repair tool for syntactically invalid code. If the file cannot be parsed, you may need to correct the underlying error first.

Use Ruff for Python Formatting and Linting

Ruff provides Python linting and formatting capabilities.

Install it with:

python -m pip install ruff

Check a file for supported linting issues:

ruff check example.py

Format the file:

ruff format example.py

Ruff can help maintain consistent formatting and identify many code-quality problems. Its formatter does not replace the need to fix incomplete or invalid syntax manually.

Format Python Code with autopep8

autopep8 is another tool for automatically correcting many PEP 8 style violations.

Install it:

python -m pip install autopep8

Format a Python file:

autopep8 --in-place --aggressive example.py

Review the resulting file before using it in production. Automated formatters can improve style, but they do not guarantee that every indentation or logic problem will be resolved.

Python Indentation Checker and Linters

A Python indentation checker can help identify formatting problems before execution.

You can use:

  • Your editor’s indentation diagnostics.
  • Python linters such as Ruff.
  • Code formatters such as Black and autopep8.
  • Continuous integration checks that validate formatting.
  • Editor extensions that display whitespace and indentation levels.

These tools are particularly helpful when several developers contribute to the same project.

Python Syntax Errors vs Indentation Errors

Python syntax errors and indentation errors are related, but they are not identical.

A SyntaxError occurs when Python encounters code that does not follow the language’s grammar. An IndentationError is a specialized syntax-related error involving indentation.

For example, this code contains a missing closing parenthesis:

print("Hello"

Python raises a SyntaxError because the expression is incomplete.

This code contains incorrect indentation:

if True:
print("Hello")

Python raises an IndentationError because the body is not indented.

Both errors prevent normal execution, but the solution depends on the specific message and the underlying problem.

What Is the Difference Between IndentationError and TabError?

IndentationError is the broader category for invalid indentation. TabError is a more specific error associated with inconsistent use of tabs and spaces.

In practice, an IndentationError may indicate a missing block, an unexpected indent, or an invalid unindent. A TabError usually points toward mixed indentation characters.

Understanding the exact message helps you choose the correct fix instead of repeatedly changing whitespace without identifying the cause.

How to Read Python Traceback Indentation Errors

A Python traceback indentation error usually includes the filename, line number, source line, and error description.

For example:

File "app.py", line 5
    print("Welcome")
    ^
IndentationError: unexpected indent

The traceback indicates that Python encountered unexpected indentation in app.py on line 5.

Follow These Debugging Steps

  1. Open the file named in the traceback.
  2. Navigate to the reported line.
  3. Inspect the previous statement and its block.
  4. Compare the indentation of nearby lines.
  5. Check for hidden tabs or spaces.
  6. Correct the block structure.
  7. Run the program again.

When debugging Python indentation errors, remember that the line reported by the interpreter may be where the inconsistency becomes detectable, not necessarily where the original mistake was introduced.

Common Python Beginner Mistakes That Cause IndentationError

Beginners often encounter indentation errors while learning Python’s block structure.

Common Python beginner mistakes include:

  • Forgetting to indent the body of an if statement.
  • Adding unnecessary spaces before a top-level statement.
  • Using different indentation levels in the same block.
  • Mixing tabs and spaces.
  • Copying code with incorrect whitespace.
  • Forgetting to indent statements after def or class.
  • Misaligning nested loops.
  • Leaving a compound statement without a body.
  • Using a formatter without checking the resulting code.
  • Assuming that every visually aligned line contains the same whitespace characters.

These problems become easier to avoid with regular practice and consistent editor settings.

How to Prevent IndentationError

You can prevent most indentation errors by adopting a few reliable habits.

Follow Python Code Formatting Best Practices

Use four spaces per indentation level, keep nested blocks aligned, and avoid mixing indentation styles.

Auto-Indent Python Code

Enable automatic indentation in your editor so that pressing Enter after a compound statement places the next line at the appropriate level.

Still inspect the result when working with nested blocks or multiline expressions.

Review Code Before Execution

Before running a script, check every function, class, loop, and conditional statement for a complete body and consistent indentation.

Use Linters and Automated Code Formatters

Integrate tools such as Ruff, Black, and autopep8 into your development workflow. Configure your editor to use spaces and run formatting checks before committing code.

Test Small Sections of Code

When learning Python, write and execute small examples before combining them into larger programs. This makes it easier to isolate indentation problems.

Step-by-Step Python IndentationError Solutions

Consider the following incorrect program:

def check_number(number):
if number > 0:
print("Positive")
else:
print("Zero or negative")

check_number(5)

The function body and conditional blocks are not indented correctly.

Step 1: Indent the Function Body

The if statement must belong to the check_number() function.

def check_number(number):
    if number > 0:
print("Positive")
else:
print("Zero or negative")

Step 2: Indent the Conditional Body

The print() statements must belong to their corresponding branches.

Correct code:

def check_number(number):
    if number > 0:
        print("Positive")
    else:
        print("Zero or negative")

check_number(5)

Output:

Positive

Step 3: Verify the Final Structure

The function body uses four spaces. The if and else statements use the same indentation level, and their bodies use eight spaces.

The final function now follows Python indentation rules and runs successfully.

This approach is useful for solving many real-world indentation errors: identify the intended block structure first, then correct the whitespace.

Frequently Asked Questions About Python IndentationError

What Causes an IndentationError in Python?+

An IndentationError occurs when indentation violates Python’s syntax rules. Common causes include missing indentation after a compound statement, unexpected leading spaces, inconsistent unindentation, and improperly formatted code.

Why Does Python Say Expected an Indented Block?+

Python displays this message when a statement requires an indented body but the following code does not provide one. Add an indented statement after the relevant declaration or use pass when an intentionally empty block is needed.

How Do You Fix Unexpected Indent in Python?+

Inspect the reported line, remove unnecessary leading whitespace, and make sure the statement belongs to a valid block. If it should be inside a function, loop, or conditional statement, indent it consistently.

How Many Spaces Should Python Indentation Use?+

Four spaces per indentation level is the standard recommendation in PEP 8. Configure your editor to insert spaces instead of tabs to maintain consistent formatting.

Can Tabs and Spaces Be Mixed in Python?+

Mixing tabs and spaces in indentation is discouraged and may trigger a TabError. Use spaces consistently, preferably four spaces per indentation level.

How Do You Fix Indentation Errors in VS Code?+

Open the affected Python file, inspect the traceback, convert indentation to spaces, set the tab size to four spaces, and correct the block structure. You can also use Python formatting extensions to standardize valid code.

Can Python Automatically Fix Indentation Errors?+

Some code editors and formatting tools can correct indentation and other formatting issues automatically. However, tools such as Black, Ruff, and autopep8 may require the underlying syntax errors to be fixed before formatting can succeed.

Why Does an IndentationError Appear After Copying Code?+

Copied code may contain tabs, unexpected spaces, or missing indentation caused by formatting changes. Paste it into your editor, inspect whitespace, and normalize indentation throughout the affected block.

Is IndentationError the Same as SyntaxError?+

IndentationError is a specialized syntax-related error. A general SyntaxError can involve other problems, such as missing parentheses, invalid expressions, or malformed statements.

Does IndentationError Occur in Jupyter Notebook and Google Colab?+

Yes. Jupyter Notebook and Google Colab execute Python code, so they follow the same indentation rules as regular Python scripts. Correct the whitespace in the affected cell and execute it again.

Conclusion

Python IndentationError is a common but manageable problem that occurs when code does not follow Python’s indentation rules. Errors such as unexpected indent, expected an indented block, and unindent does not match any outer indentation level usually indicate missing spaces, inconsistent block structure, or incorrect whitespace.

The most reliable solution is to use four spaces per indentation level, avoid mixing tabs and spaces, and inspect the traceback before changing your code. Editors such as VS Code and PyCharm, notebook environments such as Jupyter Notebook and Google Colab, and formatter tools such as Black, Ruff, and autopep8 can help you maintain consistent formatting.

By learning how indentation works in functions, classes, loops, conditional statements, and exception handling, you can debug errors more efficiently and write cleaner Python programs. Consistent indentation, regular code reviews, and automated formatting checks will help prevent these errors as your projects grow.

For more programming tutorials, explore ccodelearner and learn about other common coding issues, including JavaScript undefined vs null, to strengthen your understanding of programming fundamentals.

Leave a Reply

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