2 Braces? We Don't Need No Stinking Braces!

Indentation counts! (and it is all that counts.)

This is perhaps the most controversial feature of Python for newcomers. Python does not use begin/end statements or braces to denote statement blocks. Instead, indentation is used to delimit blocks. Everything at the same level of indentation is considered in the same block. For example,

if x > 0:
   print "x is greater than 0"
   print "but I don't care"
if y > 0:
   print "y is greater than 0"

The first if block consists of two print statements, and the second consists of one. The amount of indentation does not matter (as long as it increases for nested blocks), but it must be consistent within a block.

The main source of problems with indentation as a blocking scheme is inconsistent mixing of tabs and spaces. Python treats tabs as 8 spaces. If you use an editor that treats tabs as anything but 8 spaces, and you mix spaces and tabs, you may see indentations in your editor's display that appear identical but are different as far as Python is concerned. So the general rule is: Don't mix tabs and spaces for indentation. Use one or the other exclusively.

It may take a little time to adjust to the use of indentation for blocking, but if your experience is like ours, you will soon be wondering why all programming languages don't work this way. It leads to clear, easy-to-read code and is far less likely to lead to errors in blocking than approaches that use braces.

Questions or comments? Contact help@stsci.edu
Documented updated on 2004 Jun 1