1. More Control Flow Tools 流程控制语句
    Besides the while statement just introduced,
    除了while语句
    Python knows the usual control flow statements known from other languages, with some twists.
    Python还拥有在其他语言里常见的控制语句,以及一些好玩的语句
    4.1. if Statements if语句
    Perhaps the most well-known statement type is the if statement.
    也许最常见的语句类型是if语句
    For example:
    例如

x = int(input("Please enter an integer: "))
Please enter an integer: 42

if x < 0:
… x = 0
… print(‘Negative changed to zero’)
… elif x == 0:
… print(‘Zero’)
… elif x == 1:
… print(‘Single’)
… else:
… print(‘More’)

More

There can be zero or more elif parts, and the else part is optional.
可以有0个或多个elif语句,并且else块是可选的
The keyword ‘elif‘ is short for ‘else if’,
关键字elif比else if短
and is useful to avoid excessive indentation.
并且可以避免过度缩进
An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.
一个if…elif…elif…序列,是对其他语言的switch or case语句的替代方案

4.2. for Statements for语句
The for statement in Python differs a bit from what you may be used to in C or Pascal.
Python的for语句与你在C或者Pascal中使用的有一点区别
Rather than always iterating over an arithmetic progression of numbers (like in Pascal),
和常见的等差数列迭代(如Pascal中)
or giving the user the ability to define both the iteration step and halting condition (as C),
或让用户能够自定义迭代步骤和停止条件(如C)不一样
Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
Python的for语句可以按照元素出现的顺序迭代任何序列(列表或字符串)
For example (no pun intended):
例如

Measure some strings:

… words = [‘cat’, ‘window’, ‘defenestrate’]

for w in words:
… print(w, len(w))

cat 3
window 6
defenestrate 12

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items),
如果要在循环内修改正在迭代的序列(例如,复制所选的项目)
it is recommended that you first make a copy.
建议首先创建原序列的拷贝
Iterating over a sequence does not implicitly make a copy.
迭代序列不会隐式地创建副本
The slice notation makes this especially convenient:
使用切片就很容易地做到

for w in words[:]: # Loop over a slice copy of the entire list.
… if len(w) > 6:
… words.insert(0, w)

words
[‘defenestrate’, ‘cat’, ‘window’, ‘defenestrate’]

4.3. The range() Function range()函数
If you do need to iterate over a sequence of numbers,
如果你确实需要遍历一个数字序列
the built-in function range() comes in handy.
内置函数range()会派上用场
It generates arithmetic progressions:
它生成算术级数

for i in range(5):
… print(i)

0
1
2
3
4

The given end point is never part of the generated sequence;
给定的终点不会包含在生成的序列中
range(10) generates 10 values,
range(10)会生成10个值
the legal indices for items of a sequence of length 10.
即长度为10的序列的项的合法索引
It is possible to let the range start at another number,
也可以让range()函数从另一个数值开始
or to specify a different increment (even negative; sometimes this is called the ‘step’):
或者可以指定一个不同的步进值(甚至是负数,有时这也被称为“步长”)

range(5, 10)
5 through 9

range(0, 10, 3)
0, 3, 6, 9

range(-10, -100, -30)
-10, -40, -70

To iterate over the indices of a sequence,
要迭代序列的索引
you can combine range() and len() as follows:
你可以将range()和len()组合如下

a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
for i in range(len(a)):
… print(i, a[i])

0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however,
然而,在大多数这类情况
it is convenient to use the enumerate() function, see Looping Techniques.
一般使用enumerate()函数,请参见循环技术
A strange thing happens if you just print a range:
如果你只打印range,会出现奇怪的结果

print(range(10))
range(0, 10)

In many ways the object returned by range() behaves as if it is a list,
在很多方面由range()返回的对象的行为就像它是一个列表
but in fact it isn’t.
但事实上它不是
It is an object which returns the successive items of the desired sequence when you iterate over it,
它是一个对象,当你遍历它时,它会返回所需的序列连续项
but it doesn’t really make the list, thus saving space.
但它并不真的生成了列表,从而节省了空间
We say such an object is iterable, that is,
我们说这样一个对象是iterable,就是说
suitable as a target for functions and constructs that expect
它适合作为一个函数和结构的目标
something from which they can obtain successive items until the supply is exhausted.
而函数期望从中获得连续的项目,直到耗尽

We have seen that the for statement is such an iterator.
我们已经看到for语句是这种迭代器
The function list() is another;
list()函数是另一个
it creates lists from iterables:
它从可迭代量创建列表

list(range(5))
[0, 1, 2, 3, 4]

Later we will see more functions that return iterables and take iterables as argument.
后面我们会看到更多返回可迭代对象和以可迭代对象作为参数的函数

4.4. break and continue Statements, and else Clauses on Loops
break和continue语句,以及循环中else子句
The break statement, like in C,
break语句和C中的类似
breaks out of the smallest enclosing for or while loop.
用于跳出最近的for或while循环
Loop statements may have an else clause;
循环语句可以有一个else子句
it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while),
当for循环迭代完整个列表或while循环条件变为假
but not when the loop is terminated by a break statement.
而非由break语句终止时,就会执行这个else语句
This is exemplified by the following loop, which searches for prime numbers:
下面 循环搜索质数的代码例示了这一点:

for n in range(2, 10):
… for x in range(2, n):
… if n % x == 0:
… print(n, ‘equals’, x, ‘*’, n//x)
… break
… else:
… # loop fell through without finding a factor
… print(n, ‘is a prime number’)

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code. Look closely:
是的,这是正确的代码,仔细看
the else clause belongs to the for loop, not the if statement.)
else子句属于for循环,不是if语句的
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements:
与在if语句中的用法相比,循环中的else子句与try语句的else子句有更多的共同点
a try statement’s else clause runs when no exception occurs,
try语句的else子句在未出现异常时运行
and a loop’s else clause runs when no break occurs.
循环的else子句在未出现break时运行
For more on the try statement and exceptions, see Handling Exceptions.
更多关于try语句和异常的内容,请参见处理异常
The continue statement, also borrowed from C,
continue语句,也是从C语言借来的
continues with the next iteration of the loop:
表示继续下一次迭代

for num in range(2, 10):
… if num % 2 == 0:
… print(“Found an even number”, num)
… continue
… print(“Found a number”, num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

4.5. pass Statements pass语句
The pass statement does nothing.
pass语句什么也不做
It can be used when a statement is required syntactically but the program requires no action.
当语法上需要语句但程序不需要动作时,可以使用它
For example:
例如

while True:
… pass # Busy-wait for keyboard interrupt (Ctrl+C)

This is commonly used for creating minimal classes:
这通常用于创建最小的类

class MyEmptyClass:
… pass

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code,
另一个使用pass的地方是编写新代码时作为函数体或控制体的占位符
allowing you to keep thinking at a more abstract level.
这让你在更抽象层次上思考
The pass is silently ignored:
pass语句将被默默地忽略

def initlog(*args):
… pass # Remember to implement this!

4.6. Defining Functions 定义函数
We can create a function that writes the Fibonacci series to an arbitrary boundary:
我们可以创建一个函数,将斐波那契数列写入任意边界:

def fib(n): # write Fibonacci series up to n
… “”“Print a Fibonacci series up to n.”""
… a, b = 0, 1
… while a < n:
… print(a, end=’ ')
… a, b = b, a+b
… print()

Now call the function we just defined:

… fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
The keyword def introduces a function definition.
关键字def引入函数的定义
It must be followed by the function name and the parenthesized list of formal parameters.
其后必须跟有函数名和以括号标明的形式参数列表
The statements that form the body of the function start at the next line, and must be indented.
组成函数体的语句从下一行开始,且必须缩进
The first statement of the function body can optionally be a string literal;
函数体的第一行可以是一个可选的字符串文本
this string literal is the function’s documentation string, or docstring.
此字符串是该函数的文档字符串,或成为docstring
(More about docstrings can be found in the section Documentation Strings.)
更多关于docstrings的内容可以在文档字符串一节中找到
There are tools which use docstrings to automatically produce online or printed documentation,
有工具使用docstrings自动生成在线的或可打印的文档
or to let the user interactively browse through code;
或者让用户在代码中交互浏览
it’s good practice to include docstrings in code that you write,
在你编写的代码中包含docstrings是很好的做法
so make a habit of it.
所以让它成为习惯吧
The execution of a function introduces a new symbol table used for the local variables of the function.
执行一个函数会引入一个用于函数的局部变量的新符号表
More precisely,
更确切地说
all variable assignments in a function store the value in the local symbol table;
函数中的所有的赋值都是将值存储在局部符号表
whereas variable references first look in the local symbol table,
而变量引用首先查找局部符号表
then in the local symbol tables of enclosing functions,
然后是上层函数的局部符号表
then in the global symbol table,
然后是全局符号表
and finally in the table of built-in names.
最后是内置名字表
Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement),
因此,在函数内部无法给一个全局变量直接赋值(除非在一个global语句中命名)
although they may be referenced.
虽然可以引用它们
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called;
当函数被调用时,函数调用的实际参数被引入到被调用函数的局部(本地)符号表中
thus, arguments are passed using call by value
因此,参数传递通过传值调用
(where the value is always an object reference, not the value of the object).
这里的值始终是对象的引用,不是对象的值
[1] When a function calls another function, a new local symbol table is created for that call.
一个函数调用另一个函数时,会为本次调用创建一个新的局部符号表
A function definition introduces the function name in the current symbol table.
函数定义会在当前符号表内引入函数名
The value of the function name has a type that is recognized by the interpreter as a user-defined function.
函数名对应的值的类型是解释器可识别的用户自定义函数
This value can be assigned to another name which can then also be used as a function.
此值可以分配给另一个名称,然后该名称也可作为函数
This serves as a general renaming mechanism:
这是通用的重命名机制

fib
<function fib at 10042ed0>

f = fib
f(100)
0 1 1 2 3 5 8 13 21 34 55 89

Coming from other languages,
如果你使用过其他语言
you might object that fib is not a function but a procedure since it doesn’t return a value.
你可能会反对说:fib不是一个函数,而是一个过程(子程序),因为它并不返回任何值
In fact, 事实上
even functions without a return statement do return a value,
没有return语句的函数也返回一个值
albeit a rather boring one.
尽管是一个很无聊的值
This value is called None (it’s a built-in name).
此值被称为None(它是一个内置的名称)
Writing the value None is normally suppressed by the interpreter if it would be the only value written.
如果None只是唯一的输出,解释器通常不会打印出来
You can see it if you really want to using print():
如果你真的想看到这个值,可以使用print语句

fib(0)
print(fib(0))
None

It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
写一个函数返回斐波那契数列的列表,而不是打印出来,非常简单

def fib2(n): # return Fibonacci series up to n
… “”“Return a list containing the Fibonacci series up to n.”""
… result = []
… a, b = 0, 1
… while a < n:
… result.append(a) # see below
… a, b = b, a+b
… return result

f100 = fib2(100) # call it
f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

This example, as usual, demonstrates some new Python features:
此示例中,像往常一样,演示了一些新的Python功能
The return statement returns with a value from a function.
return语句可以从函数中携带着返回值返回
return without an expression argument returns None.
return语句不携带任何表达式参数时返回None
Falling off the end of a function also returns None.
如果一直执行到整个函数结束还没有碰到return语句,也返回None
The statement result.append(a) calls a method of the list object result.
语句result.append(a)调用了列表result的一个方法
A method is a function that ‘belongs’ to an object and is named obj.methodname,
方法是属于一个对象且名字叫做obj.methodname的函数
where obj is some object (this may be an expression),
其中obj是某个对象(可能是个表达式)
and methodname is the name of a method that is defined by the object’s type.
methodname是由该对象类型定义的方法的名称
Different types define different methods.
不同类型定义了不同的方法
Methods of different types may have the same name without causing ambiguity.
不同类型的方法可以具有相同的名称而不引起歧义
(It is possible to define your own object types and methods, using classes, see Classes),The method append() shown in the example is defined for list objects;
可以使用classes定义你自己的对象类型和方法,参见classes
示例中显示的append()方法是给列表对象定义的
it adds a new element at the end of the list.
它添加一个新的元素到列表的末尾
In this example it is equivalent to result = result + [a], but more efficient.
在这个示例中,它等同于result = result + [a],但是它更高效
4.7. More on Defining Functions 更多关于定义函数
It is also possible to define functions with a variable number of arguments.
可以定义具有可变数目的参数的函数
There are three forms, which can be combined.
有三种函数形式,可以结合使用
4.7.1. Default Argument Values 默认函数值
The most useful form is to specify a default value for one or more arguments.
最有用的形式是指定一个或多个参数的默认值
This creates a function that can be called with fewer arguments than it is defined to allow.
这种方法创建的函数被调用时,可以带有比定义的要少的参数
For example:
例如
def ask_ok(prompt, retries=4, reminder=‘Please try again!’):
while True:
ok = input(prompt)
if ok in (‘y’, ‘ye’, ‘yes’):
return True
if ok in (‘n’, ‘no’, ‘nop’, ‘nope’):
return False
retries = retries - 1
if retries < 0:
raise ValueError(‘invalid user response’)
print(reminder)
This function can be called in several ways:
这个函数可以通过几种方式调用
giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)
只提供必须的参数
giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)
提供可选参数中的一个
or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)
或者提供所有参数
This example also introduces the in keyword.
上面示例中的in关键字
This tests whether or not a sequence contains a certain value.
它测试一个序列是否包含特定的值
The default values are evaluated at the point of function definition in the defining scope,
默认值在函数定义的时刻,在定义的作用域中计算
so that
因此
i = 5

def f(arg=i):
print(arg)

i = 6
f()
will print 5.

Important warning:
重要的警告
The default value is evaluated only once.
默认值只初始化一次
This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.
当默认值是一个可变对象(如列表,字典或大多数类的实例)时,默认值会不同

For example,
例如
the following function accumulates the arguments passed to it on subsequent calls:
下面的函数在后续调用过程中会累积传给它的参数

def f(a, L=[]):
L.append(a)
return L

print(f(1))
print(f(2))
print(f(3))
This will print
这将会打印
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls,
如果你不想默认值在随后的调用中共享
you can write the function like this instead:
可以像这样编写函数
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4.7.2. Keyword Arguments 关键字参数
Functions can also be called using keyword arguments of the form kwarg=value.
函数还可以用kwarg=value形式的关键字参数调用
For instance, the following function:
例如,下面的函数
def parrot(voltage, state=‘a stiff’, action=‘voom’, type=‘Norwegian Blue’):
print("-- This parrot wouldn’t", action, end=’ ')
print(“if you put”, voltage, “volts through it.”)
print("-- Lovely plumage, the", type)
print("-- It’s", state, “!”)
accepts one required argument (voltage) and three optional arguments (state, action, and type).
接受一个必需的参数(voltage)和三个可选参数(state,action,and type)
This function can be called in any of the following ways:
可以用下列任意一种方式调用这个函数
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action=‘VOOOOOM’) # 2 keyword arguments
parrot(action=‘VOOOOOM’, voltage=1000000) # 2 keyword arguments
parrot(‘a million’, ‘bereft of life’, ‘jump’) # 3 positional arguments
parrot(‘a thousand’, state=‘pushing up the daisies’) # 1 positional, 1 keyword
but all the following calls would be invalid:

parrot() # required argument missing
parrot(voltage=5.0, ‘dead’) # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor=‘John Cleese’) # unknown keyword argument
In a function call,
在函数调用中
keyword arguments must follow positional arguments.
关键字参数必须写在位置参数之后
All the keyword arguments passed must match one of the arguments accepted by the function
传递的所有关键字参数必须匹配函数接受的参数中的一个
(e.g. actor is not a valid argument for the parrot function),
例如,actor不是parrot函数的合法参数
and their order is not important.
它们的顺序并不重要
This also includes non-optional arguments
这同样适用于非可选的参数
(e.g. parrot(voltage=1000) is valid too).
例如,parrot(voltage=1000)也是合法的
No argument may receive a value more than once.
任何参数都不可以多次赋值
Here’s an example that fails due to this restriction:
下面的示例由于这种限制将失败

def function(a):
… pass

function(0, a=0)
Traceback (most recent call last):
File “”, line 1, in ?
TypeError: function() got multiple values for keyword argument ‘a’

When a final formal parameter of the form name is present,
如果在最后存在一个
name形式的形式参数
it receives a dictionary (see Mapping Types — dict)
它将接受一个字典(参见映射类型-字典)
containing all keyword arguments except for those corresponding to a formal parameter.
这个字典包含除形式参数之外的所有关键字参数
This may be combined with a formal parameter of the form name (described in the next subsection)
它可以与
name形式的形式参数组合(在下一节讲述)
which receives a tuple containing the positional arguments beyond the formal parameter list.
这种形式接收一个元组,这个元组包含除形式参数之外的所有位置参数
(*name must occur before name.)
(*name必须出现在
name之前)
For example, if we define a function like this:
例如,如果我们定义这样的函数
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, “?”)
print("-- I’m sorry, we’re all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, “:”, keywords[kw])
It could be called like this:
它可以这样被调用
cheeseshop(“Limburger”, “It’s very runny, sir.”,
“It’s really very, VERY runny, sir.”,
shopkeeper=“Michael Palin”,
client=“John Cleese”,
sketch=“Cheese Shop Sketch”)
and of course it would print:
并且当然它会打印
– Do you have any Limburger ?
– I’m sorry, we’re all out of Limburger
It’s very runny, sir.


client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
Note that the list of keyword argument names is created by sorting the result of the keywords dictionary’s keys() method before printing its contents;
注意,在打印关键字参数内容之前,它的名称列表是通过排序字典的key()方法得到的关键字创建的
if this is not done, the order in which the arguments are printed is undefined.
如果不这样做,打印出来的参数顺序将是未定义的

4.7.3. Arbitrary Argument Lists 任意参数的列表
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments.
最后,最不常用的场景是指明某个函数可以被可变个数的参数调用
These arguments will be wrapped up in a tuple (see Tuples and Sequences).
这些参数将被封装在一个元组中(参见元组和序列)
Before the variable number of arguments,
在可变数量的参数之前
zero or more normal arguments may occur.
可能出现零个或多个正常参数
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))

Normally, these variadic arguments will be last in the list of formal parameters,
通常,这些可变的参数将位于形式参数列表的最后面
because they scoop up all remaining input arguments that are passed to the function.
因为它们将剩下的传递给函数的所有输入参数都包含进去
Any formal parameters which occur after the args parameter are ‘keyword-only’ arguments,
出现在
args之后的任何形式参数都是非关键字不可的参数
meaning that they can only be used as keywords rather than positional arguments.
意味着它们只能作用于关键字参数而不能是位置参数

def concat(*args, sep="/"):
… return sep.join(args)

concat(“earth”, “mars”, “venus”)
‘earth/mars/venus’

concat(“earth”, “mars”, “venus”, sep=".")
‘earth.mars.venus’

4.7.4. Unpacking Argument Lists 解包参数列表

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments.
当传递的参数已经是一个列表或元组时,情况与之前相反,你要拆分这些参数,因为函数调用要求独立的位置参数
For instance, the built-in range() function expects separate start and stop arguments.
例如,内建的range()函数期待单独的start和stop参数
If they are not available separately,
如果它们不能单独地获得
write the function call with the -operator to unpack
可以编写带有
操作的函数调用
the arguments out of a list or tuple:
来从一个列表或元组分拆出参数

list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]

args = [3, 6]
list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion,
同样的风格
dictionaries can deliver keyword arguments with the -operator:
字典可以通过
操作传递关键字参数

def parrot(voltage, state=‘a stiff’, action=‘voom’):
… print("-- This parrot wouldn’t", action, end=’ ‘)
… print(“if you put”, voltage, “volts through it.”, end=’ ')
… print(“E’s”, state, “!”)

d = {“voltage”: “four million”, “state”: “bleedin’ demised”, “action”: “VOOM”}
parrot(**d)

– This parrot wouldn’t VOOM if you put four million volts through it. E’s bleedin’ demised !

4.7.5. Lambda Expressions Lambda表达式
Small anonymous functions can be created with the lambda keyword.
可以使用lambda关键字创建小的匿名函数
This function returns the sum of its two arguments:
此函数会返回两个参数的总和
lambda a, b: a+b. Lambda functions can be used wherever function objects are required.
lambda函数可以用于任何需要函数对象的地方
They are syntactically restricted to a single expression.
在语法上它们被局限于只能有一个单独的表达式
Semantically, they are just syntactic sugar for a normal function definition.
在语义上,它们只是普通函数定义的语法糖
Like nested function definitions,
像嵌套的函数定义
lambda functions can reference variables from the containing scope:
lambda函数可以从包含它的作用域中引用变量

def make_incrementor(n):
… return lambda x: x + n

f = make_incrementor(42)
f(0)
42

f(1)
43

The above example uses a lambda expression to return a function.
上面的示例使用lambda表达式返回一个函数
Another use is to pass a small function as an argument:
另一种用法是将一个小函数作为参数传递

pairs = [(1, ‘one’), (2, ‘two’), (3, ‘three’), (4, ‘four’)]
pairs.sort(key=lambda pair: pair[1])
pairs
[(4, ‘four’), (1, ‘one’), (3, ‘three’), (2, ‘two’)]

4.7.6. Documentation Strings 文档字符串
Here are some conventions about the content and formatting of documentation strings.
下面是一些关于文档字符串内容和格式的惯例
The first line should always be a short,
第一行永远应该是对象用途的简短
concise summary of the object’s purpose.
精确的总述
For brevity,
为了简单起见
it should not explicitly state the object’s name or type,
不应该明确的陈述对象的名字或类型
since these are available by other means
因为这些信息可以从别的途径了解到
(except if the name happens to be a verb describing a function’s operation).
(除非这个名字碰巧就是描述这个函数操作的动词)
This line should begin with a capital letter and end with a period.
这一行应该以大写字母开头,并以句号结尾
If there are more lines in the documentation string,
如果在文档字符串中有更多的行
the second line should be blank,
第二行应该是空白
visually separating the summary from the rest of the description.
在视觉上把摘要与剩余的描述分离开来
The following lines should be one or more paragraphs describing the object’s calling conventions,
以下各行应该是一段或多段描述对象的调用约定
its side effects, etc.
其副作用等
The Python parser does not strip indentation from multi-line string literals in Python,
Python解释器不会从多行的文档字符串中去除缩进
so tools that process documentation have to strip indentation if desired.
所以必要的时候处理文档字符串的工具应当自己清楚缩进
This is done using the following convention.
使用以下约定即可
The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string.
使用以下约定即可,第一行之后的第一个非空行字符串确定整个文档字符串的缩进的量
(We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.)
我们不用第一行是因为它通常紧靠着字符串起始的引号,其缩进格式不明晰
Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string.
所有行起始的等于缩进量的空格都将被过滤掉
Lines that are indented less should not occur,
不应该存在缩进更少的行
but if they occur all their leading whitespace should be stripped.
但如果确实存在,应去除所有其前导空白
Equivalence of whitespace should be tested after expansion of tabs
应该在展开制表符之后再去测试留白的长度
(to 8 spaces, normally).
(展开后通常为8个空格)
Here is an example of a multi-line docstring:
这里是一个多行文档字符串的示例

def my_function():
… “”“Do nothing, but document it.

… No, really, it doesn’t do anything.
… “””
… pass

print(my_function.doc)
Do nothing, but document it.
No, really, it doesn’t do anything.

4.7.7. Function Annotations 函数注释
Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 484 for more information).
函数注释是关于用户定义的函数使用的类型的元数据信息,它们是完全可选的(更多信息参见PEP 484)
Annotations are stored in the annotations attribute of the function as a dictionary
注释以字典形式存储在函数的__annotations__属性中
and have no effect on any other part of the function.
对函数其他任何部分没有任何影响
Parameter annotations are defined by a colon after the parameter name,
参数注解的定义是参数名后面跟着一个冒号
followed by an expression evaluating to the value of the annotation.
然后紧跟着一个用于计算注解的表达式
Return annotations are defined by a literal ->,
返回值注解的定义是一个->
followed by an expression,
然后紧跟着一个表达式
between the parameter list and the colon denoting the end of the def statement.
他们位于参数列表和表示def语句结束的冒号之间
The following example has a positional argument,
下面的示例包含一个位置参数
a keyword argument, and the return value annotated:
一个关键字参数,和被注解的返回值

def f(ham: str, eggs: str = ‘eggs’) -> str:
… print(“Annotations:”, f.annotations)
… print(“Arguments:”, ham, eggs)
… return ham + ’ and ’ + eggs

f(‘spam’)
Annotations: {‘ham’: <class ‘str’>, ‘return’: <class ‘str’>, ‘eggs’: <class ‘str’>}
Arguments: spam eggs
‘spam and eggs’

4.8. Intermezzo: Coding Style 插曲:代码风格
Now that you are about to write longer, more complex pieces of Python,
若要编写更长更复杂的Python代码
it is a good time to talk about coding style.
是时候谈一谈编码风格了
Most languages can be written
大部分语言都可以有多种写法
(or more concise, formatted) in different styles;
(比如更简洁,更格式化)
some are more readable than others.
有些写法可以更易读
Making it easy for others to read your code is always a good idea,
让你的代码更具有可读性
and adopting a nice coding style helps tremendously for that.
而良好的编码风格对此有很大的帮助
For Python,
对于Python
PEP 8 has emerged as the style guide that most projects adhere to;
PEP8已经成为多数项目遵循的代码风格指南
it promotes a very readable and eye-pleasing coding style.
它推动了一种非常易于阅读且赏心悦目的编码风格
Every Python developer should read it at some point;
每个Python开发者都应该找个时间读一下
here are the most important points extracted for you:
以下是从中提取出来的最重要的一些点:
Use 4-space indentation, and no tabs.
使用4个空格的缩进,不要使用制表符
4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read).
4个空格是小缩进(允许更深的嵌套)和大缩进(易于阅读)之间很好的折中
Tabs introduce confusion, and are best left out.
制表符会引起混乱,最好弃用
Wrap lines so that they don’t exceed 79 characters.
折行以确保其不会超过79个字符
This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
这有助于小显示器用户阅读,也可以让大显示器能并排显示几个代码文件
Use blank lines to separate functions and classes,
使用空行分隔函数和类
and larger blocks of code inside functions.
以及函数内的大块代码
When possible, put comments on a line of their own.
如果可能,注释单独成行
Use docstrings.
使用文档字符串
Use spaces around operators and after commas,
在操作符两边和逗号之后加空格
but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).
但不要直接在左括号和右括号前加:
Name your classes and functions consistently;
类和函数的命名风格要一致
the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods.
传统上使用CameCase(驼峰风格)命名类而用lower_case_with_underscores(小写字符加下划线)命名函数和方法
Always use self as the name for the first method argument
方法的第一个参数名称应为self
(see A First Look at Classes for more on classes and methods).
查看初识类以获得更多有关类和方法的规则
Don’t use fancy encodings if your code is meant to be used in international environments.
如果您的代码要在国际环境中使用,不要使用花哨的编码
Python’s default, UTF-8, or even plain ASCII work best in any case.
Python默认的UTF-8或者ASCII在任何时候都是最好的选择
Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.
同样,只要存在哪怕一丁点可能性有使用另一种不同语言的人会来阅读或维护你的代码,就不要在标识符中使用非ASCII字符

Footnotes
脚注
[1] Actually, call by object reference would be a better description,
事实上,按对象引用传递可能是更恰当的说法
since if a mutable object is passed,
因为如果传递了一个可变对象
the caller will see any changes the callee makes to it
调用函数将看到任何被调用函数对该可变对象作出的改变
(items inserted into a list).
(比如添加到列表中的元素)

004_More Control Flow Tools_流程控制语句相关推荐

  1. java控制语句练习题_[Java初探实例篇02]__流程控制语句知识相关的实例练习

    本例就流程控制语句的应用方面,通过三个练习题来深入学习和巩固下学习的流程控制语句方面的知识,设计到,if条件判断语句,switch多分支语句,for循环语句及其嵌套多层使用,while循环语句. 练习 ...

  2. CMU15-213学习笔记(六)Exceptional Control Flow

    CMU15-213学习笔记(六)Exceptional Control Flow 程序的正常执行顺序有两种: 按顺序取下一条指令执行 通过CALL/RET/Jcc/JMP等指令跳转到转移目标地址处执行 ...

  3. 【Sql Server】Database-sql语言的流程控制语句

    流程控制语句 If  else语句 If (表.列) {语句|语句块begin,,,end} Else {语句|语句块begin,,,end }   If else 语句嵌套 If Begin If ...

  4. 深度学习编译器Data Flow和Control Flow

    深度学习编译器Data Flow和Control Flow 本文介绍了一下深度学习框架的Data Flow和Control Flow,基于TensorFlow解释了TensorFlow是如何在静态图中 ...

  5. PHP流程控制语句例题,第四堂、php流程控制语句

    php流程控制语句 条件控制语句和循环控制语句是两种基本的语法结构.它们都是用来控制程序执行流程的,也是构成程序的主要语法基础. 程序的3种控制结构 条件控制语句 循环控制语句 跳转语句 包含语句 1 ...

  6. 《C#精彩实例教程》小组阅读08 -- C#流程控制语句

    本微信图文详细介绍了C#的流程控制语句.

  7. Java编程基础04——流程控制语句

    1.顺序结构语句(了解) A:什么是流程控制语句 流程控制语句:可以控制程序的执行流程. B:流程控制语句的分类 顺序结构 选择结构 循环结构 C:执行流程: 从上往下,依次执行. D:案例演示 输出 ...

  8. pup 流程控制语句(下)

    pup 流程控制语句(下) 一:do--while 二:for语句 三:break和continue do...while 循环控制语句有两种结构,一种只有while-..部分.另一种do-.whil ...

  9. Python3 流程控制语句

    Python3 流程控制语句 python3 的流程控制语句包括: if 条件语句 while循环语句 for 循环语句 range函数 break continue pass 一.if语句 if语句 ...

  10. PL/SQL流程控制语句

    介绍PL/SQL的流程控制语句, 包括如下三类: l 控制语句: IF 语句 l 循环语句: LOOP语句, EXIT语句 l 顺序语句: GOTO语句, NULL语句 1 条件语句 IF <布 ...

最新文章

  1. 关于出现org.hibernate.TransientObjectException: The given object has a null identifier: 错误的解决方法
  2. golang 反射 reflect包 struct相互填充
  3. iGrimace IG 各版本区别
  4. 云合影程序_活动回顾丨阿里云ACE同城会开发者云workshop圆满落幕
  5. propertychange方法
  6. ASP.NET Core Web API下事件驱动型架构的实现(二):事件处理器中对象生命周期的管理
  7. java正则表达式及api_Java API 之 正则表达式
  8. 蓝桥杯 BASIC-19 基础练习 完美的代价
  9. 平时如何管理你的项目?
  10. JVM调优之:垃圾收集器
  11. 大学英语综合教程三 Unit 3 课文内容英译中 中英翻译
  12. java-se-包装类
  13. 今天是我的生日,也是我的离职日!
  14. 神经网络(4)---神经网络是如何帮助我们学习复杂的nonlinear hypotheses
  15. (c语言)通俗易懂的冒泡代码思路
  16. Matlab系列之变量
  17. 151个容易混淆拼错的英文单词
  18. WEB前端 网页设计 简介
  19. 12.11 Daily Scrum
  20. 电阻参数_电阻主要特性参数

热门文章

  1. 华为od与中软外包哪个更好_华为外包,不是OD,OD也烂,呆了8个月。今天离职再见,…...
  2. 2015最新移动App设计尺寸视觉规范【图文版】(转)
  3. 借助 Lucene.Net 构建站内搜索引擎(上)
  4. 2022年fw保研经验(东南大学网安、湖南大学计科学硕、中科院沈阳自动化所,最终东南网安)
  5. 京瓷TCL太阳能在日本福井县建设共计3.4MW光伏电站
  6. python与图像处理书籍_数字图像处理与Python实现
  7. HTML页面基本结构浅谈
  8. 洛谷 P1069 细胞分裂
  9. matlab工具箱计算最小生成树_数学建模【图与网络模型(图的基本概念与数据结构、最短路-最小生成树-网络最大流问题、Matlab图论工具箱、渡河问题、钢管的订购与运输)】...
  10. php计算众数,C++算法代码——众数