Python Indentation

Understanding and Applying Proper Indentation in Python

Why Indentation Matters in Python

Python uses indentation to define blocks of code instead of braces or keywords. Proper indentation is mandatory; incorrect indentation causes IndentationError or changes program behavior.

Basic Rules

Example 1: Correct Indentation

def greet(name):
    if name:
        print(f"Hello, {name}!")
    else:
        print("Hello, stranger!")

greet("Alice")

Example 2: IndentationError

def greet(name):
if name:  # IndentationError: expected an indented block
    print(f"Hello, {name}!")
else:
    print("Hello, stranger!")

greet("Alice")

Example 3: Mixing Tabs and Spaces (Causes Error)

def foo():
↹print("Hello")  # Tab
    print("World")  # Spaces

# This will raise:
# TabError: inconsistent use of tabs and spaces in indentation

Tips to Avoid Indentation Problems

How Python Interprets Indentation

Indented blocks define the body of functions, loops, conditionals, and classes. Example:

for i in range(3):
    print(i)
    if i == 1:
        print("One")
print("Done")  # This line is outside the loop

Output:

0
1
One
2
Done