How to break out of multiple loops?

后端 未结 30 3264
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  孤街浪徒
    2020-11-21 06:12

    Solutions in 2 Ways

    With an example: Are these two matrices equal/same?
    matrix1 and matrix2 are same size, n, 2 dimentional matrices.

    First Solution, without a function

    same_matrices = True
    inner_loop_broken_once = False
    n = len(matrix1)
    
    for i in range(n):
        for j in range(n):
    
            if matrix1[i][j] != matrix2[i][j]:
                same_matrices = False
                inner_loop_broken_once = True
                break
    
        if inner_loop_broken_once:
            break
    

    Second Solution, with a function
    This is the final solution for my case

    def are_two_matrices_the_same (matrix1, matrix2):
        n = len(matrix1)
        for i in range(n):
            for j in range(n):
                if matrix1[i][j] != matrix2[i][j]:
                    return False
        return True
    

    Have a nice day!

提交回复
热议问题