Solve the problem of how break goes out of the outer layer of Python inner layer for cycle

  • 2021-07-01 07:43:49
  • OfStack

I stumbled across the usage of for … else …, which enables break to jump out of the nested for loop


In [31]: for i in range(1,5):
  ...:   for j in range(5,10):
  ...:     print(i,j)
  ...:     if j==6:
  ...:       break
  ...:   else:
  ...:     continue
  ...:   break
  
1 5
1 6

The running logic of for … else … is that when the for loop is executed normally, it will run its else statement, and if break is in the middle, it will not execute the contents of else

The above code realizes the memory for cycle break jumps out of the outer layer for cycle, when the inner layer for cycle is executed normally, continue in else will be executed, then the outer layer break statement will be skipped to realize the outer layer cycle, when the inner layer break statement appears, else statement ignores, jumps out of the inner layer cycle, sequentially executes the outer layer break statement, jumps out of the outer layer cycle


Related articles: