Perhaps the most well-known statement type is the if statement. For example:html
if語句多是最多見的控制流語句了,例如:python
>>> 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.app
能夠有0個或多個elif部分,else部分也是可選的。關鍵字elif是 else if的簡稱,它能頗有效的避免過多的縮排。if...elif...elif 可使其餘語言的switch...case語句。(Python沒有switch語句)。函數
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):oop
在Python中,for語句和你使用的C或Pascal語言有點不一樣,在Pascal語言中,for語句老是以某個數的等差數列迭代,在C語言中,用戶能夠定義循環條件和步差。在Python中,for語句是依次遍歷序列的每個元素。例如:ui
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
若是你想在迭代的同時修改序列(例如複製某個元素),建議你先複製序列。由於迭代一個序列並不會隱式的複製序列。下面的切片操做很是方便用來複制序列:this
>>> 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']
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:spa
若是你須要變量一個數字序列,那麼內置的函數rang()排的上用場。它會產生一個數列。code
>>> 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’):htm
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.
下面,咱們會看到更多函數返回 一個迭代對象或將迭代對象做爲參數。
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語句和異常,請查閱異常處理。
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! ...