爲何有了while循環,還須要有for循環呢?不都是循環嗎?我給你們出個問題,我給出一個列表,咱們把這個列表裏面的全部名字取出來。code
name_list = ['nick', 'jason', 'tank', 'sean'] n = 0 while n < 4: # while n < len(name_list): print(name_list[n]) n += 1
nick jason tank sean
字典也有取多個值的需求,字典可能有while循環沒法使用了,這個時候能夠使用咱們的for循環。索引
info = {'name': 'nick', 'age': 19} for item in info: # 取出info的keys print(item)
name age
name_list = ['nick', 'jason', 'tank', 'sean'] for item in name_list: print(item)
nick jason tank sean
for循環的循環次數受限於容器類型的長度,而while循環的循環次數須要本身控制。for循環也能夠按照索引取值。it
print(list(range(1, 10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(1, 10): # range顧頭不顧尾 print(i)
1 2 3 4 5 6 7 8 9
# for循環按照索引取值 name_list = ['nick', 'jason', 'tank', 'sean'] # for i in range(5): # 5是數的 for i in range(len(name_list)): print(i, name_list[i])
0 nick 1 jason 2 tank 3 sean
for循環調出本層循環。for循環
# for+break name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': break print(name)
nick
for循環調出本次循環,進入下一次循環class
# for+continue name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': continue print(name)
nick tank sean
外層循環循環一次,內層循環循環全部的。import
# for循環嵌套 for i in range(3): print(f'-----:{i}') for j in range(2): print(f'*****:{j}')
-----:0 *****:0 *****:1 -----:1 *****:0 *****:1 -----:2 *****:0 *****:1
for循環沒有break的時候觸發else內部代碼塊。容器
# for+else name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: print(name) else: print('for循環沒有被break中斷掉')
nick jason tank sean for循環沒有break中斷掉
import time print('Loading', end='') for i in range(6): print(".", end='') time.sleep(0.2)
Loading......