Linux/Unix > Python Essential Reference, Second Edition > 2. Lexical Conventions and Syntax > Line Structure and Indentation | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104026065052201181119006

### Line Structure and Indentation

Each statement in a program is terminated with a newline. Long statements can span multiple lines by using the line-continuation character (`\`), as shown in the following example:

    a = math.cos(3*(x-n)) + \
        math.sin(3*(y-n))

You don’t need the line-continuation character when the definition of a triple-quoted string, list, tuple, or dictionary spans multiple lines. More generally, any part of a program enclosed in parentheses `(...)`, brackets `[...]`, braces `{...}`, or triple quotes can span multiple lines without use of the line-continuation character.

Indentation is used to denote different blocks of code, such as the bodies of functions, conditionals, loops, and classes. The amount of indentation used for the first statement of a block is arbitrary, but the indentation of the entire block must be consistent. For example:

    if a:
       statement1     # Consistent indentation
       statement2
    else:
       statement3
         statement4   # Inconsistent indentation (error)

If the body of a function, conditional, loop, or class is short and contains only a few statements, they can be placed on the same line, like this:

    if a:  statement1
    else:  statement2

To denote an empty body or block, use the `pass` statement. For example:

    if a:
       pass
    else:
       statements

Although tabs can be used for indentation, this practice is discouraged. When tab characters are encountered, they’re converted into the number of spaces required to move to the next column that’s a multiple of 8. (For example, a tab appearing in column 11 inserts enough spaces to move to column 16.) Running Python with the `-t` option prints warning messages when tabs and spaces are mixed inconsistently within the same program block. The `-tt` option turns these warning messages into `TabError` exceptions.

To place more than one statement on a line, separate the statements with a semicolon (`;`). A line containing a single statement can also be terminated by a semicolon.

The `#` character denotes a comment that extends to the end of the line. A `#` appearing inside a quoted string doesn’t start a comment, however.

Finally, the interpreter ignores all blank lines except when running in interactive mode.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.