9.for循环

for 循环

为什么有了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循环。

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中断掉
原文地址:https://www.cnblogs.com/yellowcloud/p/10839447.html