一、while循環
1、while 循環,隻要條件為真,我們就可以執行一組語句。
2、while 循環需要預先設定索引變量,并且需要編寫代碼執行索引變量+1。如下:我們需要定義一個變量 i,初始值設定為 1。
i = 1
while i < 7:
print(i)
i += 1
3、break 語句
如果使用 break 語句,即使 while 條件為真,我們也可以停止循環:
i = 0
while i < 7:
i += 1
if i == 3:
break
print(i)
輸出:
1
2
3
4、continue 語句
如果使用 continue 語句,我們可以停止循環中的目前疊代,并繼續下一個
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)
輸出:
1
2
4
5
6
7
二、for循環
1、for 循環用于疊代序列(即清單,元組,字典,集合或字元串)。通過使用 for 循環,我們可以為序列(即清單,元組,字典,集合或字元串)中的每個項目等執行一組語句。
2、for 循環不需要預先設定索引變量,索引變量自動+1。如下:
for x in "banana":
print(x)
3、for循環一般和range() 函數結合使用
range() 函數預設從 0 開始,并遞增 1(預設1,可以通過添加第三個參數來指定增量值,非必填),并以指定的數字結束。
4、for嵌套循環
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
5、pass 語句
for 語句不能為空,如果因為某種原因寫了無内容的 for 語句,可使用 pass 語句來避免錯誤
for x in [0, 1, 2]:
pass
6、break 語句
通過使用 break 語句,我們可以在循環周遊所有之前停止循環
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
輸出:
apple
7、continue 語句
通過使用 continue 語句,我們可以停止循環的目前疊代,并繼續下一個
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
輸出:
apple
cherry