Statements and Syntax
This section describes the rules for syntax and variable names.
Syntax Rules
Here are the basic rules for writing Python programs:
- Control flow
Statements execute one after another, unless control-flow statements are used (
if
,while
,for
,raise
, calls, etc.).- Blocks
A block is delimited by indenting all of its statements 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.
- Statements
A statement ends at the end of a line, but may 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 separated with a semicolon (;
).- Comments
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 constant, it is stored in the object’s
_ _doc_ _
attribute. See thepydoc
module and script in the Python Library Reference for automated extraction and display tools.- Whitespace
Generally significant only to the left of code, where indentation is used to group blocks. Blank lines and space 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
- Structure
User-defined names start with a letter ...
Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.