循環(huán)語句可以讓我們執(zhí)行語句聲明或組多次。下圖說明了一個循環(huán)語句 -
| 循環(huán)類型 | 描述 |
|---|---|
| 當指定的條件為TRUE重復(fù)執(zhí)行語句或組。它在執(zhí)行循環(huán)體之前測試條件。 | |
|
執(zhí)行一系列語句多次和縮寫代碼管理循環(huán)變量
|
|
|
可以使用一個或多個環(huán)在另一個 while 或者 for 或循環(huán)內(nèi)
|
循環(huán)控制語句改變其正常的順序執(zhí)行。當執(zhí)行離開了循環(huán)范圍,在該范圍內(nèi)創(chuàng)建的所有自動對象被銷毀。
|
控制語句
|
描述 |
|---|---|
|
終止循環(huán)語句并立刻轉(zhuǎn)移執(zhí)行循環(huán)后面的語句
|
|
|
跳過循環(huán)體的其余部分,并立即重申之前重新測試循環(huán)條件狀態(tài)
|
|
|
在Python中的pass語句的使用時,需要在一份聲明中使用,但又不希望執(zhí)行任何命令或代碼
|
迭代器是一個對象,它允許程序員遍歷集合的所有元素,而不管其具體的實現(xiàn)。在Python迭代器對象實現(xiàn)了兩個方法: iter() 和 next()
list=[1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr//bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
當一個生成器函數(shù)被調(diào)用,它返回一個生成器對象甚至不需要開始執(zhí)行該函數(shù)。 當 next()方法被調(diào)用的第一次,函數(shù)開始執(zhí)行,直到達到其返回值產(chǎn)生yield語句。yield跟蹤并記住最后一次執(zhí)行。第二 next()函數(shù)從上一個值繼續(xù)調(diào)用。
# Following example defines a generator which generates an iterator for all the Fibonacci numbers.
!usr//bin/python3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()