如何在Python中中断for循环?


在Python中,通常构建for循环来迭代遍历范围内的每个项目。如果需要在所有迭代完成之前提前终止循环,则可以使用`break`关键字。它通常用于循环体内的条件语句中。

使用break语句

让我们来看几个例子,看看break语句如何在for循环中工作。

示例

在这个例子中,for循环定义为迭代最多20次,但是break语句在第10次迭代(即x=10)终止了for循环。

如果我们将break语句应用于嵌套for循环的内循环,则它只会中断最内层的循环。它不会停止整个循环。

for x in range(20): 
    print (x) 
    if x==10: 
        break 
        print ("end of loop")

输出

0
1
2
3
4
5
6
7
8
9
10 

示例

在这个例子中,内循环在i = 0且j = 2迭代时停止,因此循环跳过了剩余的2次迭代(0, 3)和(0,4)。我们可以使用标志变量在特定迭代时停止整个循环。让我们看下面的例子。

for i in range(5):
    for j in range(5):
        print(i,j)
        if i == 0 and j == 2:
            print("stopping the inner loop at i = 0 and j = 2")
            break

输出

0 0
0 1
0 2
stopping the inner loop at i = 0 and j = 2
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4

示例

标志变量在(0,2)迭代时终止了嵌套循环。

flag = False
for i in range(5):
    for j in range(5):
        print(i,j)
        if i == 0 and j == 2:
            print("stopping the loops at i = 0 and j = 2")
            flag = True
            break
    if flag:
        break

输出

0 0
0 1
0 2
stopping the loops at i = 0 and j = 2

使用return语句

要中断for循环,我们可以使用`return`关键字,这里我们需要将循环放在函数中。使用`return`关键字可以直接结束函数。

示例

return关键字在(0,2)次迭代时终止了嵌套for循环。

def check():
    for i in range(5):
        for j in range(5):
            print(i,j)
            if i == 0 and j == 2:
                return "stopping the loops at i = 0 and j = 2"

print(check())   

输出

0 0
0 1
0 2
stopping the loops at i = 0 and j = 2

更新于:2023年8月23日

2K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.