Python’s Statements

Table 10-1 summarizes Python’s statement set. 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 3.0 statements

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Statement

Role

Example

Assignment

Creating references

a, *b = 'good', 'bad', 'ugly'

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

Sequence 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.0+)

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 (2.6+)

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

del

Deleting references

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

Table 10-1 reflects the statement forms in Python 3.0—units of code that each have a specific syntax and purpose. Here are a few fine points about its content:

 

 
  • Assignment statements come in a variety of syntax flavors, described in Chapter 11: basic, sequence, augmented, and more.
  • print is technically neither a reserved word nor a statement in 3.0, but a built-in function call; because it will nearly always be run as an expression statement, though (that is, on a line by itself), it’s generally thought of as a statement type. We’ll study print operations in Chapter 11 the next chapter.
  • yield is actually an expression instead of a statement too, as of 2.5; like print, it’s typically used in a line by itself and so is included in this table, but scripts occasionally assign or otherwise use its result, as we’ll see in Chapter 20. As an expression, yield is also a reserved word, unlike print.

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

 

 
  • In 2.6, nonlocal is not available; as we’ll see in Chapter 17, there are alternative ways to achieve this statement’s writeable state-retention effect.
  • In 2.6, print is a statement instead of a built-in function call, with specific syntax covered in Chapter 11.
  • In 2.6, the 3.0 exec code execution built-in function is a statement, with specific syntax; since it supports enclosing parentheses, though, you can generally use its 3.0 call form in 2.6 code.
  • In 2.5, the try/except and try/finally statements were merged: the two were formerly separate statements, but we can now say both except and finally in the same try statement.
  • In 2.5, with/as is an optional extension, and it is not available unless you explicitly turn it on by running the statement from __future__ import with_statement (see Chapter 33).