Today’s lesson comes from Python Program Lexical Structure.

Python Statements

Like the Ruby interpreter, the Python interpreter when loading a file loads the file one line at a time, executing the states of those lines accordingly, until the end-of-file is encountered.

Line Continuation

PEP 8: Maximum Line Length “limits” all lines to be no longer than 79 characters long, with the exception that docstrings/comments be limited to 72 characters in length.

This can get tricky to implement though because the interpreter treats the newline character as statement terminators.

Implicit Line Continuation

Parentheses ('('), brackets ('['), and curly braces ('{'), while open, are incomplete until the matching character is found by the interpreter, so you can use them to create more space when required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = [
    [
        ['foo', 'bar'],
        [1, 2, 3]
    ],
    {1, 3, 5},
    {
        'a': 1,
        'b': 2
    }
]

Explicit Line Continuation

Like Bash, and less preferred, Python lets you use a backslash ('') character to ignore the proceeding newline character and to treat the next line as a continuation of the previous.

1
2
3
x = 1 + 2 \
    + 3 + 4 \
    + 5 + 6

Multiple Statements Per Line

A semicolon (';') character can be used to separate multiple statements on a single line. It’s generally frowned upon to use semicolons though as it typically detracts from readability.

Comments

A pound/hash/bang character ('#') signifies a comment, and a docstring ('""" “""') lets you document methods, but shouldn’t be used as a substitute for Python’s lack of a multiline comment device.

Comments after Explicit Line Continuation are not possible because the backslash character must be the last character, and putting the comment before the backslash with - ha - comment it out:

1
2
3
4
5
x = 1 + 2 + \   # I wish to be comment, but I'm not.
# SyntaxError: unexpected character after line continuation character
# vs:
x = 1 + 2 + # I wish to be comment, but I'm not. \
# SyntaxError: invalid syntax

Whitespace

Use it where it seems natural to split variable names between keywords, and values between one another for readability.

Unlike most other programming languages, Python does however care deeply about the indentation of a statement because it uses indentation to group control structures instead of your typical curly brackets or keywords.