在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)