4. More Control Flow Tools

Besides the while statement just introduced, Python knows the usual control flow statements known from other languages, with some twists.

除了刚刚介绍的while语句之外,Python还知道其他语言中常见的控制流语句,只是有些修改。

4.1. if Statements

Perhaps the most well-known statement type is the if statement. For example:

也许最有名的语句类型就是if语句了。例如:

>>>

>>> 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. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or casestatements found in other languages.

If语句之后可以是空,也可以选择性添加更多的elif部分,和else部分。关键字elif是else if的缩写,用于避免行的过度缩进。If ... elif ... elif ...序列是其他语言中发现的switch或者cases语句的替代。

4.2. for Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as 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. For example (no pun intended):

Python中的for语句与C或者Pascal语言的有些微不同。不是总迭代数字的等差数列(如Pascal),或者让用户能够定义迭代步骤和停止条件(比如C语言),python的for语句依据序列出现的顺序,迭代序列的任何部分(一个列表或者一串字符)。比如(没有双关语意)

译者说,一般C语言使用for的格式,for(i=0;i<10;i++),即从0开始到9,每次增加1。C语言都是对数字的迭代,迭代边界和步骤可以自己定义。而此处看到python可以对数列迭代,类似shell。

>>>

>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']>>> for w in words:...     print(w, len(w))...cat 3window 6defenestrate 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:

如果您需要修改循环内遍历的序列(例如复制选定的项),建议您首先进行复制。遍历序列并不会隐式地复制。切片符号使复制特别方便:

译者说,切片即words[:]从列表第一个到最后一个。words.insert(0, w)在words列表第0个位置插入字符串w。

>>>

>>> 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']


With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

使用for w in words:,这个例子可以通过不断插入defenestrate 来创建一个无限长的列表。

4.3. The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:

如果你需要迭代数字序列,内置函数range()很方便。它产生等差序列:

>>>

>>> for in range(5):

...     print(i)

...01234

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

给定结束点永远都不是产生的序列的一部分(译者说,就是5-10,,10不包含在内);range(10)产生10个值,合法序列的长度为10.可以使用其他的数值作为序列起始位,或者不同的步长(甚至负数;有时这就做步长。“步长”是数学概念,等差数列里面的。好好回忆,高中知识^_^)

range(5, 10)#指定从5开始,默认步长为1

   5, 6, 7, 8, 9

range(0, 10, 3)#指定从0开始,步长为3

   0, 3, 6, 9

range(-10, -100, -30)#指定从-10开始,步长为-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 Mary1

 had2 a3

 little4 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:

如果你仅仅打印序列,会产生意想不到的事:

>>>

>>> print(range(10))

range(0, 10)



In many ways the object returned by range() behaves as if it is a list, 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.

在许多方面,range()返回的对象的行为就好像它是一个列表,但实际上它不是。当您遍历序列时,它会返回所需序列的后续项,但是它并没有真正创建列表,因此节省了空间。

We say such an object is iterable, that is, 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. The function list() is another; it creates lists from iterables:

我们说这样一个对象是可迭代的,也就是说,它适合作为函数和构造的目标,这些函数和构造期望从某个对象获得连续的项,直到供应耗尽为止。我们已经看到for语句就是这样一个迭代器。函数list()是另一个;它通过迭代器创建列表:

>>>

>>> 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

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Break语句,类似C语言中的break,用于for或者while循环中断。

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a breakstatement. This is exemplified by the following loop, which searches for prime numbers:

循环语句可以有一个else子句;它是在循环耗尽列表(with for)或条件变为false (with while)时执行的,但不是在循环被breaks语句终止时执行。

>>>

>>> for in range(2, 10):

...     for 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 number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 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: a try statement’s else clause runs when no exception occurs, and a loop’s elseclause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.

当使用一个循环时,在if语句中,try语句中的else语句比else语句使用的更多:当没有异常发生时执行try语句的else语句,且一个循环的else语句在没有break发生时执行。想看更多try语句和异常,请看处理异常。

The continue statement, also borrowed from C, continues with the next iteration of the loop:

Continue语句,也是从C语言借用的,表示在循环中继续下一个迭代:

>>>

>>> 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 2Found a number 3Found an even number 4Found a number 5Found an even number 6Found a number 7Found an even number 8Found a number 9

你可能感兴趣的:(4. More Control Flow Tools)