標籤:
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 3window 6defenestrate 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)...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’):
range()函數也是遵守前閉後開原則;range(10)產生10個值(0到9),可以指定數值序列起始值,或指定不同的步差(步差可以是負數)
range(5, 10) 5 through 9range(0, 10, 3) 0, 3, 6, 9range(-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 Mary1 had2 a3 little4 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 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 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!...
Python更多控制流程工具(一)