break

In Python, the break keyword exits a loop prematurely. When you use break inside a loop, Python immediately terminates the loop and continues executing the code that follows the loop. This keyword is particularly useful when you want to stop a loop based on a certain condition.

Python break Keyword Examples

Here’s a quick example of how you might use the break keyword in a loop:

Python
>>> for number in range(10):
...     if number == 5:
...         break
...     print(number)
...
0
1
2
3
4

In this example, the loop attempts to iterate over numbers from 0 to 9. When the loop variable, number, reaches 5, the break statement executes, causing the loop to terminate immediately. Therefore, the loop only processes the numbers from 0 to 4.

Python break Keyword Use Cases

  • Exiting a loop when a condition is met, preventing unnecessary iterations
  • Breaking out of nested loops by placing break in the innermost loop

Tutorial

Python "for" Loops (Definite Iteration)

In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader