一、語法
為什么有了while循環,還需要有for循環呢?不都是循環嗎?我給大家出個問題,我給出一個列表,我們把這個列表里面的所有名字取出來。
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循環也可以按照索引取值。
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 + break
for循環調出本層循環。
# for+break
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
if name == 'jason':
break
print(name)
nick
三、for + continue
for循環調出本次循環,進入下一次循環
# for+continue
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
if name == 'jason':
continue
print(name)
nick
tank
sean
四、for循環嵌套
外層循環循環一次,內層循環循環所有的。
# 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+else
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中斷掉
六、for循環實現loading
import time
print('Loading', end='')
for i in range(6):
print(".", end='')
time.sleep(0.2)
Loading......