3.3 for循环

3.3 for循环

while循环条件写不好容易进入死循环,更建议写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循环可以遍历列表、字典、range、字符串、元组、集合。

for i in 可迭代对象:
  代码块

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':
        break
    print(i)

3.3.2 for + continue

e=['a','b','c','d','e','f']

#如过遇到变量值为'e',跳过,继续打印其他元素
for i in e:
    if i=='e':
        continue
    print(i)

a
b
c
d
f

3.3.3for+else

for循环没有被break的时候,执行else里面代码

e=['a','b','c','d','e','f']

for i in e:
    if i=='e':
        continue
    print(i)
else:
    print('for循环外')

a
b
c
d
f
for循环外

e=['a','b','c','d','e','f']

for i in e:
    if i=='e':
        break
    print(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 (1,i+1):
        print(f'{i}*{j}={i*j}',end=' ')
        

​

1*1=1

21=2 22=4

31=3 32=6 3*3=9

41=4 42=8 43=12 44=16

51=5 52=10 53=15 54=20 5*5=25

61=6 62=12 63=18 64=24 65=30 66=36

71=7 72=14 73=21 74=28 75=35 76=42 7*7=49

81=8 82=16 83=24 84=32 85=40 86=48 87=56 88=64

91=9 92=18 93=27 94=36 95=45 96=54 97=63 98=72 9*9=81

打印loading......

#打印默认end='\n',默认换行

import time
print('loading',end='')
for i in range(6):
    time.sleep(1) #执行一次停留1s
    print('.',end='')

loading......

posted @ 2025-08-03 20:40  bokebanla  阅读(21)  评论(0)    收藏  举报