break statement

break statement

Syntactically, break can only appear in the nested code of a for or while loop.

It will terminate the nearest outer loop, and if the loop has an optional else clause, it will also skip that clause.

If a for loop is terminated by a break, the control variable of the loop will retain its current value.

When break transfers the control flow to a try statement with a finally clause, the finally clause will be executed first and then the loop will actually leave.

for i in range(6):
    for j in range(6):
        if i**2 == j:
            print(f'i={i},j={j}')
print(f'i={i},j={j}')            
i=0,j=0
i=1,j=1
i=2,j=4
i=5,j=5
for i in range(6):
    for j in range(6):
        if i**2 == j:
            print(f'i={i},j={j}')
        break
print(f'i={i},j={j}')  
i=0,j=0
i=5,j=0
for i in range(6):
    for j in range(6):
        if i**2 == j:
            print(f'i={i},j={j}')
        break # 控制内层循环
    else: # 不会执行
        print(f'i={i},j={j}')  
i=0,j=0
for i in range(6):
    for j in range(6):
        if i**2 == j:
            print(f'i={i},j={j}')
        break
else: # 属于外层循环,会执行
    print(f'i={i},j={j}')  
i=0,j=0
i=5,j=0
for i in range(5):
    try:
        print(f'3/i={3/i}')
    except ZeroDivisionError as e:
        print(e)
    finally:
        print(f'i={i}')
division by zero
i=0
3/i=3.0
i=1
3/i=1.5
i=2
3/i=1.0
i=3
3/i=0.75
i=4
# 引发异常直接跳过 break
# 无异常则继续执行完 finally 才终止循环
for i in range(5):
    try:
        print(f'3/i={3/i}')
        break
    except ZeroDivisionError as e:
        print(e)
    finally:
        print(f'i={i}')
division by zero
i=0
3/i=3.0
i=1

Guess you like

Origin blog.csdn.net/weixin_46757087/article/details/112403103