深度阅读

How to Break out of multiple loops in Python

作者
作者
2023年08月22日
更新时间
10.52 分钟
阅读时间
0
阅读量

There are several ways to break out of multiple nested loops in Python:

  1. Add a flag variable and set it when you want to break out of all loops:
done = False
for i in range(10):
for j in range(5):
    if i+j == 12:
        done = True
        break
if done:
    break
  1. Use the return statement to exit from a function that contains the loops:
def my_function():
for i in range(10):
    for j in range(5):
        if i+j == 12:
            return
  1. Raise an exception and catch it outside the loops:
class BreakIt(Exception):
    pass

try:
    for i in range(10):
        for j in range(5):
            if i+j == 12:
                raise BreakIt
except BreakIt:
    pass
  1. Use the itertools.product() function to avoid nested loops:
import itertools
for i, j in itertools.product(range(10), range(5)):
if i+j == 12:
    break

Note that breaking out of nested loops may not be the best solution for your problem, so you should carefully consider if it is the right choice for your specific use case.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。