时间:2022-12-06 01:27
在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)