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: The Pythonic Way

In this tutorial, you'll learn all about the Python for loop. You'll learn how to use this loop to iterate over built-in data types, such as lists, tuples, strings, and dictionaries. You'll also explore some Pythonic looping techniques and much more.

intermediate best-practices 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