深度阅读

How to break out of a loop in Python?

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

To break out of a loop in Python, you can use the break keyword. When the break keyword is encountered within a loop, it immediately exits the loop and continues execution of the code following the loop.

Here’s an example:

for i in range(10):
    if i == 5:
        break
    print(i)

In this example, the loop will iterate through the numbers 0 to 9. When i equals 5, the break keyword is encountered and the loop immediately exits. The output of the above code will be:

0
1
2
3
4

Note that break can be used with both for and while loops in Python. Additionally, you can use the break keyword with nested loops to break out of both the current loop and any outer loops.

相关标签

博客作者

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