How to Fix Python IndentationError: Unexpected Indent with Examples

Python’s readability and elegance are some of the reasons why it has become one of the most popular programming languages. A significant part of Python’s clean and easy-to-read code is its reliance on indentation. However, this can sometimes lead to frustration when you encounter an “IndentationError: unexpected indent” message. In this article, we will explore what this error means, why it occurs, and how to fix it with examples.

1. Understanding Indentation in Python.

In Python, indentation is not just for visual aesthetics; it is a fundamental part of the language’s syntax. Instead of using braces or other delimiters like many other languages, Python uses whitespace (indentation) to define code blocks.

This makes Python code more readable but also means that improper indentation can result in errors. The standard indentation in Python is four spaces, and consistent indentation is crucial. Mixing tabs and spaces or using different numbers of spaces can lead to indentation errors.

2. What is the “IndentationError: unexpected indent”?

The “IndentationError: unexpected indent” is a common error message in Python, indicating that the interpreter has encountered an unexpected level of indentation in your code.

This error typically occurs when the indentation of a line or block does not match the expected level based on the surrounding code. Let’s dive into some common scenarios that lead to this error and how to fix them.

2.1 Example 1: Incorrect Indentation in Python Script String Passed To exec() Function.

Below is an example that uses the Python exec() function to run a for loop.

def use_exec_to_run_for_loop(): 
    python_code = """ 
for i in range(5): 
    print(f"Iteration {i}!") 
""" 
    return python_code 


if __name__ == "__main__":
    
    python_code = use_exec_to_run_for_loop() 
    exec(python_code)

When you run the above code, it will generate the below output.

Iteration 0!
Iteration 1!
Iteration 2!
Iteration 3!
Iteration 4!

You should note that the python_code variable is a multiple-line string that contains the Python source code that will be executed.

The Python source code in the double “”” should start from the beginning of the code line with the correct indents, otherwise, when you run the code, it will throw the IndentationError: unexpected indent.

Below is an incorrect Python code content string that will throw the IndentationError: unexpected indent.

def use_exec_to_run_for_loop(): 
    python_code = """ 
    for i in range(5): 
        print(f"Iteration {i}!") 
""" 
    return python_code

In the above Python source code string, the for loop does not start from the beginning of the string, there are 4 whitespaces before the for keyword, which will lead to the IndentationError: unexpected indent.

You can use the strip() function to remove the whitespaces from the beginning and end of the string to fix this error.

def use_exec_to_run_for_loop(): 
    python_code = """ 
    for i in range(5): 
        print(f"Iteration {i}!") 
""" 
    return python_code.strip() # trip the whitespaces on the string both sides.

2.2 Example 2: Incorrect Indentation Level.

Source code.

def my_function():
    print("Hello, World!")
   print("Indentation Error")  # This line has an extra space

In this example, the line `print(“Indentation Error”)` has one extra space compared to the previous line. Python expects consistent indentation within a block, so this extra space triggers the “IndentationError: unexpected indent“.

>>> def my_function():
...     print("Hello, World!")
...    print("Indentation Error")  # This line has an extra space
  File "<stdin>", line 3
    print("Indentation Error")  # This line has an extra space
                                                              ^
IndentationError: unindent does not match any outer indentation level

Fix: To resolve this issue, ensure that all lines within the same block have the same level of indentation. Remove the extra space before the problematic line.

def my_function():
    print("Hello, World!")
    print("Indentation Error")  # Corrected indentation

2.3 Example 3: Mixing Tabs and Spaces.

Source code.

def my_function():
    print("Hello, World!")
        print("Indentation Error")  # Mixing tabs and spaces

This error can also occur if you mix tabs and spaces for indentation within the same block. Python treats tabs and spaces differently, so it’s important to use one consistent method.

Fix: Choose either tabs or spaces for indentation and stick to it throughout your codebase. Most Python developers prefer using spaces, with four spaces as the standard.

3. Conclusion.

Understanding and maintaining proper indentation is crucial when writing Python code. The “IndentationError: unexpected indent” error can be frustrating, but it serves as a reminder of the importance of consistent and correct indentation.

By following the examples and fixes discussed in this article, you’ll be better equipped to resolve indentation errors and write clean, readable Python code. Remember to use a consistent indentation style throughout your codebase to avoid these issues in the first place.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.