One unusual feature of Python is the way that the
indentation of your source program organizes it into
blocks within blocks within blocks. This is contrary to
the way languages like C and Perl organize code blocks by
enclosing them in delimiters such as braces {
... }.
Various Python branching statements like if and for control the execution of blocks
of lines.
At the very top level of your program, all statements must be unindented—they must start in column one.
Various Python branching statements like if and for control the execution of one
or more subsidiary blocks of lines.
A block is defined as a group of adjacent lines that are indented the same amount, but indented further than the controlling line. The amount of indentation of a block is not critical.
You can use either spaces or tab characters for indentation. However, mixing the two is perverse and can make your program hard to maintain. Tab stops are assumed to be every eight columns.
Blocks within blocks are simply indented further. Here is an example of some nested blocks:
if i < 0:
print "i is negative"
else:
print "i is nonnegative"
if i < 10:
print "i has one digit"
else:
print "i has multiple digits"
If you prefer a more horizontal style, you can always
place statements after the colon (:) of a
compound statement, and you can place multiple statements
on a line by separating them with semicolons (;). Example:
>>> if 2 > 1: print "Math still works"; print "Yay!" ... else: print "Huh?" ... Math still works Yay!
You can't mix the block style with the horizontal style:
the consequence of an if or else must either be on the same line or in a
block, never both.
>>> if 1: print "True"
... print "Unexpected indent error here."
File "<stdin>", line 2
print "Unexpected indent error here."
^
IndentationError: unexpected indent
>>>