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 case statements found in other languages.

可以有0个或多个elif部分,else部分也是可选的。关键字elif是 else if的简称,它能很有效的避免过多的缩排。if...elif...elif 可以使其他语言的switch...case语句。(Python没有switch语句)。

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语言中,for语句总是以某个数的等差数列迭代,在C语言中,用户可以定义循环条件和步差。在Python中,for语句是依次遍历序列的每一个元素。例如:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

 如果你想在迭代的同时修改序列(例如复制某个元素),建议你先复制序列。因为迭代一个序列并不会隐式的复制序列。下面的切片操作非常方便用来复制序列:

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

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

如果你需要变量一个数字序列,那么内置的函数rang()排的上用场。它会产生一个数列。

>>> 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, 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’):

range()函数也是遵守前闭后开原则;range(10)产生10个值(0到9),可以指定数值序列起始值,或指定不同的步差(步差可以是负数)

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()函数会更方便一些,见Looping Techniques

A strange thing happens if you just print a range:

如果你用print()函数直接打印rang()函数,会看到一个奇怪的现象:

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

我们可能觉得rang()应该是返回一个类似于列表的对象,但其实不是的。当你迭代它的时候,它返回的是所期望序列的连续的元素,但它不是一个列表,这是为了节约空间。

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:

我们称这样的对象叫做:可迭代的iterable,我们其实已经看到 for语句也是一个iterator。函数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 smallest enclosing for or while loop.

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 break statement. This is exemplified by the following loop, which searches for prime numbers:

和C语言程序一样,break语句用来跳出最近的for或while循环。

循环语句可以有一个else子句;当循环跳出循环条件之后就执行else语句。但是如果是通过break跳出循环的,则不执行else语句。看下面的例子,搜寻质数:

>>> 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: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.

else子句另一个应用最普遍的地方是和try语句一起使用:当没有异常发生的时候,则会使用到try语句的else子句。更多try语句和异常,请查阅异常处理。

4.5. pass Statements

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

pass语句作用:不做任何事情。它通常在当某个语句需要包含一条语句,但又不需要做任何事情的时候使用。例如:

>>> 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, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

另一个使用pass的地方是:当你写新代码时,给函数或条件体作为一个占位符,这样允许你保持该函数可运行或更抽象。pass语句直接被忽略:

>>> def initlog(*args):
...     pass   # Remember to implement this!
...
原文地址:https://www.cnblogs.com/lijie-vs/p/4337649.html