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:
>>> 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. As a result, 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
breakin the innermost loop
Related Resources
Tutorial
How to Exit Loops Early With the Python break Keyword
In this tutorial, you'll explore various ways to use Python's break statement to exit a loop early. Through practical examples, such as a student test score analysis tool and a number-guessing game, you'll see how the break statement can improve the efficiency and effectiveness of your code.
For additional information on related topics, take a look at the following resources:
- Break Out of Loops With Python's break Keyword (Course)
- Python for Loops: The Pythonic Way (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- How to Exit Loops Early With the Python break Keyword (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)