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. 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
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python "while" Loops (Indefinite Iteration) (Tutorial)
- Python Keywords: An Introduction (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- Python "for" Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python "while" Loops (Quiz)
- Exploring Keywords in Python (Course)