How to Exit a While Loop with a Break Statement in Python



Python


In this article, we show how to exit a while loop with a break statement in Python.

So a while loop should be created so that a condition is reached that allows the while loop to terminate. This may be when the loop reaches a certain number, etc.

If the while loop does not have a condition that allows it to break, this forms what is called an infinite loop.

An infinite loop is a loop that goes on forever with no end.

Normally in programs, infinite loops are not what the programmer desires. The programmer normally wants to create loops that have an end.

If the while loop isn't designed to end with a certain condition by itself, we can force an exit with a break statement.

This break statement makes a while loop terminate. The loop then ends and the program continues with whatever code is left in the program after the while loop.

Before we look at how to exit a while loop with a break statement in Python, let's first look at an example of an infinite loop.

One such example of an infinite loop in Python is shown below.



Any program that contains the statement, while True:, without any break statements is an infinite loop. This is because by nature, while True always evalues to True. Since the while statement is true, it keeps executing.

The program goes from 1 upwards to infinity and doesn't break or exit the while loop.

Another infinite loop example is shown below.



Similarly like the last code, this code, too, is an infinite loop and doesn't break.

So how can we force the while loop to exit when a certain condition is met?

And this can simply be done using the break keyword.

The below code breaks when x is equal to 25.



So now we have a while loop with the statement, while(True), which by nature creates an infinite loop.

However, since we place a break statement in the while loop, it isn't infinite and the program exits the while loop when the count reaches 25.

break is a reserved keyword in Python. If typing it in a Python IDLE, you will see that it turns orange, indicating that it is a special reserved word in Python.

So this is how you can exit a while loop in Python using a break statement.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...