How To Stop A While Loop In Python

Control flow in a program is essential – it determines how & when the statements will run. In Python, the while loop is commonly used to iterate over a block of code as long as a test expression (condition) is true.

But once you start a while loop, you might often need to gracefully exit or stop it when a certain condition arises. This tutorial shall delve deep into how to control a while loop in Python, focusing primarily on how to stop it according to your requirements.

1. The Basic Concept of a While Loop

In Python, a while loop continues to execute a block of indented code as long as a condition is true. Here’s a common structure of a while loop:

The condition above can be any expression that is either true or false. When the condition is evaluated to be true, the code block under while is executed. This loop continues until the condition becomes false.

2. The break Statement

The break statement is the most straightforward way to stop a while loop. When activated, it immediately terminates the loop, even if the while condition is true. Here’s how it works:

In the code above, the loop will stop when the new_condition is met.

3. The continue Statement

Another essential command in control flow is the continue statement. Instead of ending the loop altogether, it ends the current iteration and starts the next one. Here’s how it functions:

If the different_condition is met, the while loop will skip the rest of the loop and start the next iteration.

Here’s the full example code:

Output:

1
2
3
4
6
7
8
9
10
11

In the above example, the number 5 is not printed due to the continue statement. When the count reaches 5, it returns to the beginning of the loop, skipping the print statement.

Conclusion

Controlling flow in a Python program, especially when dealing with while loops, is a fundamental concept that every developer should understand. Through the use of the break and continue statements, you can effectively control your loops, enabling them to exit or skip iterations according to the conditions you set. With a firm grasp of these concepts, you can write cleaner and more efficient Python code.