How To End A Loop In Python

When working with Python, loops are essential for processing data and executing repetitive tasks. But sometimes, there may be a need to stop the loop before it finishes all the given iterations. In this tutorial, we will discuss how to end a loop in Python using the break and continue statements. We will also cover how to use these statements in both the for and while loops.

1. Using break statement

The break statement is used to stop the loop completely and move to the next block of code after the loop. It is important to know the difference between break and normal loop completion. When using the break, the loop ends before all the iterations are finished, whereas a normal loop completion happens when all the iterations are complete.

Let’s take a look at an example using the break statement in a for loop:

Output:

1
2
3
4

In the example above, the break statement stops the loop when the number is equal to 5. Thus, the loop is not executed for all the numbers from 1 to 10 as defined by the range() function.

Here’s another example using the break statement in a while loop:

Output:

1
2
3
4

The output is the same as the previous example, but the only difference is that we used a while loop instead of a for loop.

2. Using the continue statement

The continue statement is used to skip the current iteration of the loop and proceed to the next iteration. Unlike the break statement, continue does not stop the loop completely; it continues to execute the loop from the next iteration.

Let’s take a look at an example using the continue statement in a for loop:

Output:

1
2
3
4
6
7
8
9
10

In this example, the loop is executed for all the numbers from 1 to 10 except for 5, as the continue statement skips the current iteration when the number is equal to 5.

Let’s see another example using the continue statement in a while loop:

Output:

1
2
3
4
6
7
8
9
10

The output is the same as the previous example, but the only difference is that we used a while loop instead of a for loop.

Conclusion

In this tutorial, we discussed two ways to end a loop in Python, using the break and continue statements. Remember that the break statement is used to exit the loop completely and move to the next block of code, while the continue statement is used to skip the current iteration of the loop and continue to the next iteration. Both statements can be used in both for and while loop structures.