Break and Continue Statements in Python
In previous lessons, we learned how loops help us repeat tasks efficiently. Today, we will learn about Break and Continue, two important statements used to control loop execution.
These statements give programmers more control over loops.
What is the Break Statement?
The "break" statement immediately stops a loop.
When Python encounters "break", the loop terminates and execution continues after the loop.
Example of Break
for number in range(1, 6):
if number == 4:
break
print(number)
Output
1
2
3
The loop stops when the value becomes 4.
Using Break in While Loops
Example
count = 1
while True:
print(count)
if count == 5:
break
count += 1
Output
1
2
3
4
5
What is the Continue Statement?
The "continue" statement skips the current iteration and moves to the next iteration.
Example of Continue
for number in range(1, 6):
if number == 3:
continue
print(number)
Output
1
2
4
5
The value 3 is skipped.
Difference Between Break and Continue
Statement| Function
break| Stops the loop completely
continue| Skips current iteration
Example Using Both
for number in range(1, 10):
if number == 3:
continue
if number == 8:
break
print(number)
Output
1
2
4
5
6
7
Real-World Applications
Break and Continue are useful for:
- Searching data
- Validation systems
- Menu-driven programs
- User input handling
- Game development
Conclusion
The "break" and "continue" statements provide additional control over loops. They help developers write cleaner, more efficient, and flexible programs.
Understanding these statements is important because they are widely used in real-world Python applications.
Top comments (0)