PYTHON INDENTATION - Complete Guide For Python Programming (2015)

Complete Guide For Python Programming (2015)

PYTHON INDENTATION

Whitespace is very important in Python. The whitespace at the beginning of the line is called indentation. Leading whitespace at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. Each set of statements is called a block.

For example:

i = 5

# Error below! Notice a single space at the start of the line

print 'Value is ', i

print 'I repeat, the value is ', i

When you run this, you get error:

File "whitespace.py", line 5

print 'Value is ', i

^

IndentationError: unexpected indent

Notice that there is a single space at the beginning of the second line. The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. Use four spaces for indentation. This is the official Python language recommendation. Good editors will automatically do this for you. Make sure you use a consistent number of spaces for indentation; otherwise your program will show errors. Python always use indentation for blocks and will never use braces.