Skip to main content

Python Indentation

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.

note

The amount of indentation (spaces) can be freely chosen, but must be consistent throughout the block, otherwise Python will give you an error!

It has to be at least one.

note

In general, four white spaces are used for indentation and are preferred over tabs.

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.

warning

Incorrect indentation will result in IndentationError.

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.