Next / Previous / Contents / TCC Help System / NM Tech homepage

23.1. Python's block structure

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.

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
>>>