Statements and Syntax

This section describes the rules for syntax and variable names.

Syntax Rules

Here are the general rules for writing Python programs:

Control flow

Statements execute one after another, unless control-flow statements are used (if, while, for, raise, calls, etc.).


A block is delimited by indenting all of its statements by the same amount, with spaces or tabs. A tab counts for enough spaces to move the column to a multiple of 8. Blocks can appear on the same line as a statement header if they are simple statements.


A statement ends at the end of a line, but can continue over multiple lines if a physical line ends with a \, an unclosed (), [], or {} pair, or an unclosed, triple-quoted string. Multiple simple statements can appear on a line if they are separated with a semicolon (;).


Comments start with a # (not in a string constant) and span to the end of the line.

Documentation strings

If a function, module file, or class begins with a string literal, it is stored in the object’s __doc__ attribute. See the help() function, and the pydoc module and script in the Python Library Reference for automated extraction and display tools.


Generally significant only to the left of code, where indentation is used to group blocks. Blank lines and spaces are otherwise ignored except as token separators and within string constants.

Name Rules

This section contains the rules for user-defined names (i.e., variables) in programs.

Name format


User-defined ...

Get Python Pocket Reference, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.