python中如何跳出多层循环

1、定义标记变量;利用变量值的变化退出循环

 

# 第一种嵌套形式
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)

# 第二种嵌套形式
flag = True
while flag:
    for i in range(10):
        print(x)
        flag = False
        break

 2、使用函数配合return关键字 实现跳出循环(在函数内部只要执行完return语句 则直接退出函数)

def test():
    while True:
        for x in range(10):
            print(x)
            return


test()

 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)

 

while True:
    for x in range(4):
        print(x)
        if x == 2:
            break
    else:
        print("未执行")
        continue
    break