Example of Python method for jumping out of multiple loops

  • 2021-07-09 08:35:55
  • OfStack

Method 1: Customize exceptions


# -*- coding:utf-8 -*-
 
"""
 Functions: python Out of the loop 
"""
#  Method 1 : Custom exceptions 
 
 
class Getoutofloop(Exception):
  pass
try:
  for i in range(5):
    for j in range(5):
      if i == j == 2:
        raise Getoutofloop()
      else:
        print i, '----', j
except Getoutofloop:
  pass

Method 2: Encapsulate the loop as a function, return


# -*- coding:utf-8 -*-
 
"""
 Functions: python Out of the loop 
"""
#  Method 2 Encapsulated as a function, return
 
 
def test():
  for i in range(5):
    for j in range(5):
      if i == j == 2:
        return
      else:
        print i, '----', j
 
test()

Method 3: Use the for... else... statement


# -*- coding:utf-8 -*-
 
"""
 Functions: python Out of the loop 
"""
#  Method 2 : for...else... Usage for jumping out of the specified loop layer 
 
for i in range(5):
  for j in range(5):
    for k in range(5):
      if i == j == k == 3:
        break
      else:  
        print i, '----', j, '----', k
    else:    # else1
      continue
    break    # break1
  else:      # else2
    continue
  break      # break2

Method 3 explains:
(1) break can jump out of a 1-cycle (the current and remaining times of the cycle are no longer executed), but it cannot jump out of other external cycles of the cycle.

For example, after the innermost third loop break, the program returns to the second loop and continues to execute the next second loop, and then the third loop will execute again.

(2) continue is to skip a certain 1-loop, but the remaining number of times of the loop will continue to be executed.

(3) for... else: In which the statements in the else block will not be executed until the for loop has been completely executed, and if the for loop is break, the else block will not be executed.

(4) In method 3, when the third cycle satisfies i = = j = = k = = 3, if the third cycle is break, the parallel else1 will be skipped and break1 will be executed, resulting in the second cycle

else2 is skipped and break2 is executed, resulting in the first loop being terminated.

Finally, jump out of the whole cycle.

for... else plus break example:


# -*- coding:utf-8 -*-
 
"""
 Functions: for...else Statement 
"""
 
for i in range(5):
  print i
else:
  print u" Complete loop execution 1 Times. "
 
for j in range(6):
  for k in range(6):
    print j, k
    if j == 3:
      print u" The internal heavy cycle is about to be break"
      break
  else:
    print u" Complete execution of internal heavy cycle 1 Times. "
else:
  print u" Complete execution of external heavy cycle 1 Times. "

Related articles: