3.3 for循环
e=['a','b','c','d','e','f']
# 0 1 2 3 4 5
#打印类似于循环
index=0
while index<6: #如果元素变多,则索引不可数print(e[index])index+=1
运行结果如下:
a
b
c
d
e
f
for循环可以遍历列表、字典
语法:
for i in 列表or字典: //用变量i去遍历列表元素
代码块
e=['a','b','c','d','e','f']for i in e:print(i)
运行结果如下:
a
b
c
d
e
f
3.3.1 for+break
e=['a','b','c','d','e','f']#如过遇到变量值为'e',结束循环
for i in e:if i=='e':breakprint(i)
3.3.2 for + continue
e=['a','b','c','d','e','f']#如过遇到变量值为'e',跳过,继续打印其他元素
for i in e:if i=='e':continueprint(i)
运行结果如下:
a
b
c
d
f
3.3.3 for+else
for循环没有被break的时候,执行else里面代码
e=['a','b','c','d','e','f']for i in e:if i=='e':continueprint(i)
else:print('for循环外')
运行结果如下:
a
b
c
d
f
for循环外
e=['a','b','c','d','e','f']for i in e:if i=='e':breakprint(i)
else:print('for循环外')
a
b
c
d
3.3.4 for循环嵌套
#range()
#list(range(n)),元素为整数0到n-1的列表
list(range(3))
[0, 1, 2]
- 打印九九乘法表
for i in range(1,10):print('\n')for j in range (i,10):print(f'{i}*{j}={i*j}',end=' ')
运行结果如下:
11=1 12=2 13=3 14=4 15=5 16=6 17=7 18=8 19=9
22=4 23=6 24=8 25=10 26=12 27=14 28=16 2*9=18
3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 6*6=36 6*7=42 6*8=48 6*9=54 7*7=49 7*8=56 7*9=63 8*8=64 8*9=72 9*9=81
- 打印loading......
#打印loading......
#打印默认end='\n',默认换行import time
print('loading',end='')
for i in range(6):time.sleep(1) #执行一次停留1sprint('.',end='')
运行结果如下:
loading......
