DEV Community

Cover image for Break and Continue Statements in Python – 18
augustineowino357-design
augustineowino357-design

Posted on • Edited on

Break and Continue Statements in Python – 18

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
4
5
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
4
5
6
7
Enter fullscreen mode Exit fullscreen mode

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.

Python #PythonForBeginners #CodingJourney #LearnPython #Programming

Top comments (0)