for
And compare the while loop for loop using an iterator iteration value
Why have a while loop, loop also need to have for it? Not all circulating it? I'll give you a question, I give a list of all the names we put this list inside taken out.
name_list = ['nash', 'langyigang', 'fujiachen', 'jinyi']
n = 0
while n < 4:
# while n < len(name_list):
print(name_list[n])
n += 1
# nash
# langyigang
# fujiachen
# jinyi
Dictionary also needs to take multiple values, the dictionary may be unable to use a while loop, this time we can use for loop.
Dictionary take key Liezi:
info = {'name': 'nash', 'age': 19}
for item in info:
# 取出info的keys
print(item)
# 输出结果
# name
# age
name_list = ['nash', 'langyigang', 'fujiachen', 'jinyi']
for item in name_list:
print(item)
#输出结果
# nash
# langyigang
# fujiachen
# jinyi
The number of cycles for loop is limited by the length of the container type, and the number of while loop requires its own control. The for loop can also be in accordance with the value of the index.
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 = ['nash', 'langyigang', 'fujiachen', 'jinyi']
# for i in range(5): # 5是数的
for i in range(len(name_list)):
print(i, name_list[i])
# 输出结果
# 0 nash
# 1 langyigang
# 2 fujiachen
# 3 jinyi
for + break
layer recursive call for the present cycle.
# for+break
name_list = ['nash', 'langyigang', 'fujiachen', 'jinyi']
for name in name_list:
if name == 'langyigang':
break
print(name)
# 输出结果
# nash
for + continue
recursive call for the current cycle, the next cycle into the
# for+continue
name_list = ['nash', 'langyigang', 'fujiachen', 'jinyi']
for name in name_list:
if name == 'langyigang':
continue
print(name)
# 输出结果
# nash
# fujiachen
# jinyi
nested for loop
A loop outer loop, the inner loop cycle all.
# 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+else
name_list = ['nash', 'langyigang', 'fujiachen', 'jinyi']
for name in name_list:
print(name)
else:
print('for循环没有被break中断掉')
# nash
# langyigang
# fujiachen
# jinyi
# for循环没有break中断掉
for realization of loading cycle
Sho Case
import time
print('Loading', end='')
for i in range(6):
print(".", end='')
time.sleep(0.2)
# Loading......