1.5. Indenting code

Python functions have no explicit begin or end, no curly braces that would mark where the function code starts and stops. The only delimiter is a colon (“:”) and the indentation of the code itself.

Example 1.7. Indenting the buildConnectionString function

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Code blocks (functions, if statements, for loops, etc.) are defined by their indentation. Indenting starts a block and unindenting ends it; there are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. In this example, the function code (including the doc string) is indented 4 spaces. It doesn’t have to be 4, it just has to be consistent. The first line that is not indented is outside the function.

After some initial protests and several snide analogies to Fortran, you will make peace with this and start seeing its benefits. One major benefit is that all Python programs look similar, since indentation is a language requirement and not a matter of style. This makes it easier to read and understand other people’s Python code.

Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.

Further reading