在 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 原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/312031.html
微信掃一掃
支付寶掃一掃