當咱們寫while循環的時候,不給判斷條件的時候,while循環是不會自動結束的,他是無限次循環的,咱們要是想要while結束循環的須要給判斷也就是說須要咱們本身判斷它。拿咱們就會想其餘的方法來解決這些問題,這時候咱們就學到了for循環,for循環的循環次數受限於容器類型的長度,而while循環的循環次數須要本身控制。python
好比:字典也有取多個值的需求,字典可能有while循環沒法使用了,這個時候能夠使用咱們的for循環。學習
# while 循環 name_list = ['nick', 'jason', 'tank', 'sean'] n = 0 while n < 4: # while n < len(name_list): print(name_list[n]) n += 1 # for循環,去字典的key info = {'name': 'nick', 'age': 19} for item in info: # 取出info的keys print(item) # for循環,去字典的item name_list = ['nick', 'jason', 'tank', 'sean'] for item in name_list: print(item)
for循環也能夠按照索引取值。code
# 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])
for循環的循環次數也是顧頭不顧尾的。對象
for i in range(1, 10): # range顧頭不顧尾 print(i) # 1,2,3,4,5,6,7,8,9
while: 1. 會進入死循環(不可控),儘可能少使用while循環 2. 世間萬物均可以做爲循環的對象 for: 1. 不會進入死循環(可控),之後儘可能使用for循環 2. 只對容器類數據類型+字符串循環(可迭代對象)
咱們學while循環的時候,學習了使用break來結束本層循環,continue來結束本次循環;那咱們學習for循環也有break和continue。索引
for循環調出本層循環。字符串
# for+break name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': break print(name)
for循環調出本次循環,進入下一次循環it
# for+continue name_list = ['nick', 'jason', 'tank', 'sean'] for name in name_list: if name == 'jason': continue print(name)
for循環裏的else 和 while裏的else的使用方法式樣的,都是在沒有break的時候觸發else內部代碼塊。for循環
# 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中斷掉
實現加載的時候,咱們用到了python裏面的time庫,和time庫裏面的sleep方法。class
import time print('Loading', end='') for i in range(6): print(".", end='') time.sleep(0.2) # Loading......