如何在Python中使用break跳出多层循环

Python013

如何在Python中使用break跳出多层循环,第1张

python中的break默认只能退出当前循环,无法退出多重循环。不过想退出多重循环可以用退出标志的方式来折中实现。代码如下。

endloop1=False

while True:

    endloop2=False

    if endloop1:

        print('end loop 1')

        break

    while True:

        endloop3=False

        if endloop2:

            print('end loop 2')

            break

        i=0

        while True:

            if endloop3:

                print('end loop 3')

                break

            if i>3:

                endloop1 = True

                endloop2=True

                endloop3 = True

            i+=1

不明白可追问

python中常用的两种退出循环方式,break和continue 举个例子更直接:

1、以break方式退出循环:当某些条件成立,退出整个循环i = 1

# 例:吃5个苹果--循环:吃完第3个吃饱了,第4个和第5个不吃了(不执行--==4 或 》3)

while i <= 5:

# 条件:如果吃到第4或>3 打印吃饱了不吃了

if i == 4:

print('吃饱了,不吃了')

break

print(f'吃了第{i}个苹果')

i += 1

2、以continue方式退出循环:当条件成立,退出当前一次循环,继而执行下一次循环

# 例:吃5个苹果--循环:吃到第3个吃出一个虫子,第3个不吃了,继续吃第4和第5个

i = 1

while i <= 5:

# 条件

if i == 3:

print('吃出一个虫子,这个苹果不吃了')

# 如果使用continue,在continue之前一定要修改计数器,否则进入死循环

i += 1

continue

print('吃了第{i}个苹果')

i += 1

扩展:

while和for循环都可以配合else使用:

else下方缩进的代码含义:当循环正常结束后执行的代码

break终止循环不会执行else下方缩进的代码

continue退出循环的方式执行else下方缩进的代码

使用自定义异常可以跳出深层嵌套循环、看我做过的例子:

class FoundException(Exception): pass

try:

for row,record in enumerate(table):

for columu,field in enumerate(record):

for index,item in enumerate(field):

if item == target:

raise FoundException()

except FoundException:

print ("found at ({0},{1},{2})".format(row,column,index))

else:

print ('not found')