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

2*1=2 2*2=4 

3*1=3 3*2=6 3*3=9 

4*1=4 4*2=8 4*3=12 4*4=16 

5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 

6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 

7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 

8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 

9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=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  阅读(9)  评论(0)    收藏  举报