在python中退出循环的方法
1.使用return语句退出循环
def test():
while True:
for x in range(10):
print(x)
return
test()
2.利用变量值的变化退出循环
a = [[1, 2, 3], [5, 5, 6], [7, 8, 9]]
# init_i = 0
# init_j = 0
flag = True
for i in range(3):
for j in range(3):
# print(i, j)
if a[i][j] == 5:
flag = False
init_i = i
init_j = j
break
if not flag:
break
print(init_i, init_j)
print(i, j)
3.利用else continue 和外层的break跳出循环
a = [[1, 2, 3], [5, 5, 6], [7, 8, 9]]
init_i = 0
init_j = 0
flag = True
for i in range(3):
for j in range(3):
# print(i, j)
if a[i][j] == 5:
flag = False
init_i = i
init_j = j
break
else:
continue
break
# if not flag:
# break
print(init_i, init_j)
print(i, j)
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: python中canvas怎么使用