python Jump Out of Double Layer for Cycle Solution

  • 2021-06-29 11:31:59
  • OfStack

1. Description of the problem

In traversing a 2-dimensional array, we often use a double-layer for loop.At some point, we don't need to traverse the entire 2-dimensional array.The for loop should be terminated when the condition is met.However, break directly in the inner loop does not terminate the outer loop.

2. Solutions

Resolve using for... else... syntax.


for i in range(5):
  for j in range(5):
    print(i, j)
    if i == 3 and j == 3:
      break
  else:
    continue
  break

Statements in else are executed when the loop normally ends (else will not execute if break is executed by the loop).Note: continue in else of for j acts on for i, not for j.


Related articles: