How to Use “break” in Python

In this tutorial, we will discuss the usage of the “break” keyword in Python. The Python break statement is a loop control statement that terminates the loop statement, irrespective of whether the loop has completed all its iterations or not. It can be used in while and for loops.

Step 1: Using break in a while loop

Let’s start by using the break statement in a while loop. The break statement will terminate the loop as soon as it encounters a specific condition.

In the code above, the while loop will break as soon as i is equal to 5, and thus, the numbers from 1 to 5 will be printed.

Step 2: Using break in a for loop

The break statement can also be used in for loops. The following example demonstrates this:

In the code above, the for loop breaks when i equals 5, so the numbers from 1 to 4 are printed.

Step 3: Using break in nested loops

The break statement also works in nested loops. When a break statement is encountered in the inner loop, it terminates only the inner loop, not the entire loop structure. Here is an example:

In the code above, the inner loop breaks when j reaches 3. However, the outer loop continues to run until i reaches 5.

Conclusion

Recognizing when and how to use the break statement in Python optimizes both your coding process and program flow control. It’s a powerful tool that allows loops to become more flexible to specific conditions. Knowing this, keep practicing with different Python loops and mastering the conditions for the break statement.