A Byte of Python

Indentation

Whitespace is important in Python. To be precise, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (tabs and spaces) at the beginning of the logical line are used to determine the indentation level of the logical line which in turn is used to determine the grouping of statements. In our programs till now, we wrote programs with the same indentation level and hence all the steps were in the same group.

A group of statements that have to go together are marked by an indentation level and they are referred to as a block of statements. We will see examples of this in the next chapter.

One thing that you should keep in mind is that wrong indentation can give rise to errors. For example:

i = 5
 print 'Value is', i # Error! Notice a single space at the start of the line
print 'I repeat, the value is', i

When you run this, you will get the following error:

  File "e:/byte-of-python/code/indentation.py", line 2 
    print 'Value is', i # Error! Notice a single space at the start of the line 
    ^ 
SyntaxError: invalid syntax

Notice that there is a single space extra at the beginning of the second line of the program. This caused Python to get confused about the grouping of statements and hence gave an error that the syntax is invalid, that is, the program is not following the rules of the language. This also means that you cannot arbitrarily start new blocks of statements (except for the main block which you have been using all along). We will learn where we can use blocks in the control flow chapter.

How to Indent

Do not use a mixture of spaces or tabs for the indentation as this will not work reliably. I strongly recommend that you use either four spaces or tabs for each indentation level.

Use any of these two styles. More importantly, choose one and use it consistently.

If you are using DrPython, you do not need to worry, since it will automatically help you with indentation. In case, you want to specify the indentation style that you want to use, click on Edit -> Whitespace -> Set Indentation to Tabs... or Set Indentation to Spaces....