在 Python 中,for
關鍵字提供了更全面的機制來構成循環。 for
循環用于序列類型,如列表、元組、集合、范圍等。
對序列中的每個成員元素執行for
循環的主體。因此,它不需要顯式驗證控制循環的布爾表達式(如 while
循環)。
Syntax:
for x in sequence:
statement1
statement2
...
statementN
首先,for 語句中的變量x
引用序列中 0 索引處的項目。 將執行:
符號后縮進量增加的語句塊。一個變量x
現在引用下一個項目,并重復循環的主體,直到序列結束。
以下示例演示了帶有列表對象的 for
循環。
Example:
nums = [10, 20, 30, 40, 50]
for i in nums:
print(i)
Output
10
20
30
40
50
下面演示了帶有元組對象的 for
循環。
Example: For Loop with Tuple
nums = (10, 20, 30, 40, 50)
for i in nums:
print(i)
Output
10
20
30
40
50
任何 Python 序列數據類型的對象都可以使用 for 語句進行迭代。
Example: For Loop with String
for char in 'Hello':
print (char)
Output
H
e
l
l
o
下面的for
循環使用項()方法遍歷字典。
Example: For Loop with Dictionary
numNames = { 1:'One', 2: 'Two', 3: 'Three'}
for pair in numNames.items():
print(pair)
Output
(1, 'One')
(2, 'Two')
(3, 'Three')
鍵值 paris 可以在for
循環中解包成兩個變量,分別得到鍵值。
Example: For Loop with Dictionary
numNames = { 1:'One', 2: 'Two', 3: 'Three'}
for k,v in numNames.items():
print("key = ", k , ", value =", v)
Output
key = 1, value = One
key = 2, value = Two
key = 3, value = Three
對于帶范圍()函數的循環
range
類是不可變的序列類型。范圍()返回可與for
循環一起使用的range
對象。
Example:
for i in range(5):
print(i)
Output
0
1
2
3
4
退出 for
循環
在某些情況下,可以使用break
關鍵字停止并退出 for
循環的執行,如下所示。
Example:
for i in range(1, 5):
if i > 2
break
print(i)
Output
1
2
繼續下一次迭代
使用continue
關鍵字跳過當前執行,并在某些條件下使用continue
關鍵字繼續下一次迭代,如下所示。
Example:
for i in range(1, 5):
if i > 3
continue
print(i)
Output
1
2
3
對于帶其他塊的循環
else
塊可以跟隨for
循環,該循環將在for
循環結束時執行。
Example:
for i in range(2):
print(i)
else:
print('End of for loop')
Output
0
1
End of for loop
循環嵌套
如果一個循環(for
循環或 while
循環)在其主體塊中包含另一個循環,我們說這兩個循環是嵌套的。如果外循環被設計為執行 m 次迭代,而內循環被設計為執行 n 次重復,那么內循環的主體塊將被執行 m×n 次。
Example: Nested for loop
for x in range(1,4):
for y in range(1,3):
print('x = ', x, ', y = ', y)
Output
x = 1, y = 1
x = 1, y = 2
x = 2, y = 1
x = 2, y = 2
x = 3, y = 1
x = 3, y = 2