同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
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
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:
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:
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏