Indentation

August 9, 2010 at 11:26 pm (Python)

Whitespace is important in Python. Actually, whitespace at the beginning of the line is important.

This is called indentation. Leading whitespace (spaces and tabs) 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.
This means that statements which go together must have the same indentation. Each such set of statements is called a block. One thing we should remember is how wrong indentation can give rise to errors. For example:

i = 2

print 'Value is', i # Error! we made a single space at the start of the line

print 'the value is', i

When you run this, you get the following error:
File "intendation.py", line 4
print 'Value is', i # Error!
we made a single space at the start of the line
^
SyntaxError: invalid syntax

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. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the main block which you have been using all along, of course).


How to indent

Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. I strongly recommend that you use a single tab or two or four spaces for each indentation level. Choose any of these three indentation styles. More importantly, choose one and use it consistently i.e. use that indentation style only.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: