for循環可以遍歷任何序列的項目,比如字符串、列表、元組、字典、集合等序列類型,逐個獲取序列中的各個元素。
while循環會一直執行它下面的代碼片段,直到它對應的布爾表達式為False時才會停下來。具體來講,while循環所作的和if語句類似,也是去檢查一個布爾表達式的真假,不一樣的是它下面的代碼片段不是只被執行一次,而是執行完后再調回到while所在的位置,如此重復進行,直到while表達式為False為止。
for循環
1.for循環第一種情況
for x in range(0, 10): print(x) # 結果為0,1,2,3,4,5,6,7,8,9 # 從0開始到9結束
2.for循環第二種情況
for x in range(0, 10, 2): print(x) # 結果為0,2,4,6,8 # 從0開始到9結束,依次加2
3.for循環第三種情況
a = ["1", 2, 123, "dasf"] for x in a: print(x) # 結果為"1", 2, 123, "dasf"
while循環
1.while循環第一種情況
x = 1 while True: print(x) # 結果為1,1,1,1,1……無限
# 因為一直是True所以循環不會停止會一直循環下去
2.while循環第二種情況
count = 0 while count < 5: print(count) count = count + 1 # 結果為 0,1,2,3,4 # 因為count等於4已經是小於5的整數了,所以循環停止。
---break 退出循環
---continue 跳過本次循環開始下次循環
示例如下 # continue 和 break 用法 i = 1 while i < 10: i += 1 if i%2 == 1: # 非雙數時跳過輸出 continue print(i) # 輸出雙數2、4、6、8、10 i = 1 while 1: i += 1 if i > 10: # 當i大於10時跳出循環 break
while循環中使用else
示例如下 # while循環中使用else示例 count = 0 while count < 5: print(count, " is less than 5") count = count + 1 else: print(count, " is not less than 5") # 結果為: 0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5