Python Indentation Rules

Posted: | Tags: Python

In Python, code blocks are denoted by indentation, i.e., leading whitespace.

Though Python's syntax allows tabs or any number of spaces to denote code blocks, the PEP8 coding convention recommends using four spaces.

Python's indentation-based blocks

Unlike many programming languages that use brackets to denote code blocks for compound statements such as if and for, Python uses indentation.

Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program. Most people learn to love this feature after a while. Design and History FAQ - Why does Python use indentation for grouping of statements? — Python 3.11.4 documentation

for i in range(3):
    print(i)
# 0
# 1
# 2

Nested blocks (compound statements within compound statements) increase their indentation level with additional leading spaces. Here's an example using function definitions with def, loops with for, and conditional branches with if.

def test(n):
    for i in range(n):
        if i % 2:
            print(i * 10)
        else:
            print(i)
    print('FINISH')

test(5)
# 0
# 10
# 2
# 30
# 4
# FINISH

PEP8 recommends four spaces for indents

PEP8, the Python coding convention, recommends using four spaces for indentation. Adhering to this guideline is beneficial unless there's a compelling reason not to.

Use 4 spaces per indentation level. PEP 8 - Indentation – Style Guide for Python Code | peps.python.org

Spaces are the preferred indentation method. PEP 8 - Tabs or Spaces? – Style Guide for Python Code | peps.python.org

Many Python-supporting editors and IDEs insert four spaces when the Tab key is pressed, eliminating the need to press the space bar four times.

In Jupyter Notebook, for example, selecting multiple lines and pressing the Tab key adds four spaces to all lines, while pressing Shift + Tab reduces the indent. Similar shortcuts are available in other editors.

Python syntax allows any number of spaces or tabs for indentation

Python syntax allows using any number of spaces or tabs for indentation.

The following code will not raise an error.

def test(n):
 for i in range(n):
   if i % 2:
                print(i * 10)
   else:
    print(i)
 print('FINISH')

test(5)
# 0
# 10
# 2
# 30
# 4
# FINISH

While this is syntactically correct, it's usually best to use four spaces for indentation unless there's a specific reason.

Note that you must use a consistent number of spaces or tabs for indents at the same level, such as if and else. Mismatched indent widths can cause an IndentationError.

# def test(n):
#  for i in range(n):
#    if i % 2:
#                 print(i * 10)
#      else:
#        print(i)
#  print('FINISH')
# IndentationError: unindent does not match any outer indentation level

No indent is necessary for the block with only simple statements

If a block is comprised only of simple statements, such as expressions or return statements, it can be written without indentation. You achieve this by writing the simple statement right after the colon : without starting a new line.

def test(n):
    print(n)

test(5)
# 5
def test(n):print(n)

test(5)
# 5

You can write multiple simple statements on a single line, separating them with semicolons ;.

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. 7. Simple statements — Python 3.11.4 documentation

def test(n):
    n += 10
    print(n)
    print('FINISH')

test(5)
# 15
# FINISH
def test(n):n += 10;print(n);print('FINISH')

test(5)
# 15
# FINISH

This approach applies only when the block consists entirely of simple statements. If the block contains compound statements, you must use indentation.

def test(n):
    for i in range(n):
        print(i)

test(3)
# 0
# 1
# 2
# def test(n):for i in range(n):print(i)
# SyntaxError: invalid syntax
def test(n):
    for i in range(n):print(i)

test(3)
# 0
# 1
# 2

While this writing style of using semicolons is grammatically correct, there's no need to use it unless there's a specific reason to do so.

Related Categories

Related Articles