Skip to content

Python Indentation

How Python uses indentation (whitespace) instead of curly braces to define code blocks, including best practices for consistent spacing and avoiding IndentationError.

Python Indentation

Python uses indentation to define a block of code, unlike most programming languages that use curly brackets { }, such as C, C++, Java.

Unlike most programming languages, such as C, C++, Java, which use curly brackets to define a block of code,

A code block (i.e. body of a function, of a loop, etc.) starts with indentation and ends with the first unindented line.

For example:

for i in range(1,11):
    print(i)
    if i == 5:
        break

Through the use of indentation, code in Python comes out neat and clean. In this way, Python programs appear similar and consistent.

Indentation and line Continuation

Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes the code more readable.

For example:

if True:
    print('Hello World')
    count = 10

and

if True: print('Hello World'); count = 5

Both are valid and do the same thing, but the first snippet is clearer.

Navigation