Indentation in Python refers to the spaces or tabs at the beginning of a line of code. Unlike many other programming languages that use curly braces {} or keywords to define blocks of code, Python uses indentation to define the structure and scope of loops, conditionals, functions, classes, and other code blocks.

Correct indentation is crucial because Python relies on it for code execution. If the indentation is incorrect, Python will raise an IndentationError, which prevents the program from running.

Why Does Python Use Indentation?

Python enforces indentation for the following reasons:

  • Readability: Indented code is easier to read and understand;
  • Consistency: It enforces a uniform coding style;
  • Structure: It eliminates ambiguity in defining code blocks;

Indentation Rules in Python

Consistent Indentation

  • Use spaces or tabs, but do not mix them in the same code block;
  • The PEP 8 style guide recommends using 4 spaces per indentation level;

Indentation in Control Structures

Blocks following if, for, while, try, except, def, class, etc., must be indented.

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

Indentation in Functions

def my_function():
    print("Hello, World!")  # Indented inside the function

Indentation in Loops

for i in range(5):
    print(i)  # Indented inside the loop

Common Indentation Errors

Python raises an IndentationError if there is an issue with indentation. Let's look at common indentation errors:

IndentationError: Expected an Indented Block

This occurs when a block of code that requires indentation is not properly indented.

# Incorrect Code
if True:
print("This will cause an error")  # No indentation

# Correct Code:
if True:
    print("This is correctly indented")  # Indented properly

- IndentationError: Unexpected Indent

This occurs when an extra or unnecessary indentation is used.

# Incorrect Code
print("Hello")
    print("This will cause an error")  # Unexpected indentation


# Correct Code
print("Hello")
print("No unnecessary indentation here")

- IndentationError: Unindent Does Not Match Any Outer Indentation Level

This happens when indentation levels do not align properly.

# Incorrect Code
def my_function():
    print("Inside function")
  print("This line has inconsistent indentation")

# Correct Code
def my_function():
    print("Inside function")
    print("This line is correctly indented")

This also occurs when mixing spaces and tabs.

# Incorrect Code
def my_function():
    print("First line with spaces")
	print("Second line with tabs")  # Mixing tabs and spaces

# Correct Code (Using spaces only, PEP 8 style)
def my_function():
    print("First line with spaces")
    print("Second line with spaces")

Missed Colons and Indentation Issues

Python requires a colon (:) at the end of statements that introduce an indented block. Forgetting a colon results in a SyntaxError.

# Incorrect Code (Missing Colon)
if True
    print("This will cause a SyntaxError")

# Correct Code
if True:
    print("This is correctly formatted")

Best Practices for Indentation in Python

  • Use 4 Spaces Per Indentation Level (Recommended by PEP 8);
  • Avoid Mixing Spaces and Tabs - Always use spaces for indentation;
  • Use an Editor That Supports Auto-Indentation - IDEs like VS Code, PyCharm, and Sublime Text help maintain consistent indentation;
  • Follow PEP 8 Style Guide - This ensures your code is readable and standardized;
  • Be Careful with Copy-Pasting Code - Different environments may introduce mixed indentation;

Indentation is a fundamental part of Python programming. Incorrect indentation leads to IndentationError or SyntaxError, preventing code execution. Following best practices like using spaces instead of tabs and maintaining consistency will ensure that your Python code remains error-free and readable.