前言
- 在代碼中有的時候我們需要程序不斷地重復執行某一種操作
- 例如我們需要不停的判斷某一列表中存放的數據是否大於 0,這個時候就需要使用循環控制語句
- 這里會講解 for 循環
python 有兩種循環語句,一個是 for、一個是 while
while 循環詳解
https://www.cnblogs.com/poloyy/p/15087250.html
功能和語法
for 循環變量 in 序列: 代碼塊
序列
for 語句用於遍歷序列中的元素,這里所講的序列是廣義的,可以是:
- 列表
- 元組
- 集合
- range 對象
遍歷列表
# 遍歷列表 lis = [1, 2, 3, 4] for i in lis: print(l) # 輸出結果 1 2 3 4
遍歷元組
# 遍歷元組 tup = (1, 2, 3, 4) for i in tup: print(i) # 輸出結果 1 2 3 4
遍歷集合
# 遍歷集合 se = {1, 2, 3, 4} for i in se: print(i) # 輸出結果 1 2 3 4
遍歷字典
# 遍歷字典 dic = {1: 1, 2: 2, "3": 3, "4": 4} for i in dic: print(i) # 輸出結果 1 2 3 4
遍歷 range
# 遍歷range for i in range(5): print(i) # 輸出結果 0 1 2 3 4
range() 詳解:https://www.cnblogs.com/poloyy/p/15086994.html
雙重循環
# 雙重循環 name = ['張三', "李四", "老汪"] score = [60, 70] for i in name: for j in score: print("名:", i, " 分:", j) # 輸出結果 名: 張三 分: 60 名: 張三 分: 70 名: 李四 分: 60 名: 李四 分: 70 名: 老汪 分: 60 名: 老汪 分: 70
多個變量的栗子
# 多個變量 for a, b in [("張三", "80"), ("李四", "81"), ("老汪", "82")]: print(a, b) # 輸出結果 張三 80 李四 81 老汪 82
break、continue 詳解
https://www.cnblogs.com/poloyy/p/15087598.html
結合 continue + if 的栗子
# continue + if list1 = [1, 2, 3, 4, 5, 6] sum = 0 for i in list1: # 如果是奇數,則跳出本次循環 if i % 2 != 0: continue # 偶數則加上 sum += i print(sum) # 輸出結果 12
2+4+6
結合 break + if 的栗子
# break + if list1 = [1, 2, 3, 4, 5, 6] sum = 0 for i in list1: # 如果是 4 ,則結束 for 循環 if i == 4: break # 偶數則加上 sum += i print(sum) # 輸出結果 6
1+2+3
if 詳解
https://www.cnblogs.com/poloyy/p/15087130.html
在 for 循環中使用 else 語句
語法格式
for 變量 in 序列: 代碼塊 1 else: 代碼塊 2
當 for 循環正常完成后,會自動進入到 代碼塊 2
代碼栗子一
檢測 number 是否會素數
- range(2, number) 會生成 2、3、4、5、6、7、8 的數字序列
- 判斷 factor 是否可以被 number 整除
- 如果是,則 number 不是素數
- 如果 for 循環整除結束,就會進到 else 里面,則 number 為素數
number = 9 # 2,3,4,5,6,7,8 for factor in range(2, number): print(factor) # 9 求模 2、3、4、5、6、7、8 if number % factor == 0: # factor = 3 會進到這里 is_prime = False # 結束 for 循環 break else: # 素數 is_prime = True print(is_prime) # 輸出結果 False
代碼栗子二
# else for i in range(10): print(i) if i == 4: break else: print("執行 else 代碼塊") # 輸出結果 0 1 2 3 4
重點
- 若想執行 else 里面的代碼塊,必須是觸達到循環條件且為假
- 如果在循環里面提前結束了循環(break),則不會執行 else 里面的代碼塊