Python’s Statements

Table 10-1 summarizes Python’s statement set. Each statement in Python has its own specific purpose and its own specific syntax—the rules that define its structure—though, as we’ll see, many share common syntax patterns, and some statements’ roles overlap. Table 10-1 also gives examples of each statement, when coded according to its syntax rules. In your programs, these units of code can perform actions, repeat tasks, make choices, build larger program structures, and so on.

This part of the book deals with entries in the table from the top through break and continue. You’ve informally been introduced to a few of the statements in Table 10-1 already; this part of the book will fill in details that were skipped earlier, introduce the rest of Python’s procedural statement set, and cover the overall syntax model. Statements lower in Table 10-1 that have to do with larger program units—functions, classes, modules, and exceptions—lead to larger programming ideas, so they will each have a section of their own. More focused statements (like del, which deletes various components) are covered elsewhere in the book, or in Python’s standard manuals.

Table 10-1. Python statements

Statement

Role

Example

Assignment

Creating references

a, b = 'good', 'bad'

Calls and other expressions

Running functions

log.write("spam, ham")

print calls

Printing objects

print('The Killer', joke)

if/elif/else

Selecting actions

if "python" in text:
    print(text)

for/else

Iteration

for x in mylist:
    print(x)

while/else

General loops

while X > Y:
    print('hello')

pass

Empty placeholder

while True:
    pass

break

Loop exit

while True:
    if exittest(): break

continue

Loop continue

while True:
    if skiptest(): continue

def

Functions and methods

def f(a, b, c=1, *d):
    print(a+b+c+d[0])

return

Functions results

def f(a, b, c=1, *d):
    return a+b+c+d[0]

yield

Generator functions

def gen(n):
    for i in n: yield i*2

global

Namespaces

x = 'old'
def function():
    global x, y; x = 'new'

nonlocal

Namespaces (3.X)

def outer():
    x = 'old'
    def function():
        nonlocal x; x = 'new'

import

Module access

import sys

from

Attribute access

from sys import stdin

class

Building objects

class Subclass(Superclass):
    staticData = []
    def method(self): pass

try/except/ finally

Catching exceptions

try:
    action()
except:
    print('action error')

raise

Triggering exceptions

raise EndSearch(location)

assert

Debugging checks

assert X > Y, 'X too small'

with/as

Context managers (3.X, 2.6+)

with open('data') as myfile:
    process(myfile)

del

Deleting references

del data[k]
del data[i:j]
del obj.attr
del variable

Technically, Table 10-1 reflects Python 3.X’s statements. Though sufficient as a quick preview and reference, it’s not quite complete as is. Here are a few fine points about its content:

Most of this table applies to Python 2.X, too, except where it doesn’t—if you are using Python 2.X, here are a few notes for your Python, too: