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.).- Blocks
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.
- 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
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 thehelp()function, and thepydocmodule 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 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
- Structure
User-defined ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access