Statements and Syntax

Syntax Rules

Rules for writing Python programs.

Control flow

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

Blocks

Blocks are delimited by indenting all their statements the same amount with spaces or tabs. A tab counts for enough spaces to move the column to a multiple of 8.

Statements

Statements end at the end of a line but may continue over multiple lines if the prior line ends with a \, or an open ( ), [ ], or {} pair, or an open triple-quoted string. Separate statements with a semicolon (;) if more than one on a line.

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’s stored in the object’s __doc__ attribute.

Name Rules

Rules for user-defined names in programs.

Format

User-defined names start with a letter or ‘_’, followed by any number of letters, digits, or ‘_’s.

Reserved words

User-defined names cannot be the same as any Python reserved word (listed in Table 1-11).

Case sensitivity

User-defined names and reserved words are always case- sensitive: SPAM and spam are different.

Unused tokens

Python does not use characters @, $, or ?, though they may appear in string constants.

Creation

User-defined names are created when assigned, but must exist when referenced.

Table 1-11. Reserved Words

and

assert

break

class

continue

def

del

elif

else

except

exec

finally

for

from

global

if

import

in

is

Get Python Pocket Reference 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.