A while loop iterates over a block of statements until the specified condition evaluates to False.
At some point, we always want the loop to end. Otherwise, it will run indefinitely, and a programmer never desires that.
So, how do we do that?
There are multiple ways to terminate while loops in Python.
So, let’s get started and understand each one of them.
How to Exit While Loops Using the Control Condition
How to Exit While Loops in Python with the “Break” Statement
How to Stop While Loops in Python with the “Return” statement
How to End While Loops in Python by Raising an Exception
Conclusion
How to Exit While Loops Using the Control Condition
The first way is to specify a condition in the while statement that always evaluates to False at some point during the loop’s execution time. Let’s take an example to understand this.
i = 0 while i < 5: print("Iteration no:", i) i += 1 #increment i by 1
Output
Iteration no: 0 Iteration no: 1 Iteration no: 2 Iteration no: 3 Iteration no: 4
In the above example, the while loop will run if the variable i is less than 5. Initially, i is equal to 0. Therefore, the condition gets evaluated to True.
In the while block, we increment i by 1 in every iteration. So, the loop will run 5 times, i.e., for i = 0, 1, 2, 3, and 4. When the value of i becomes 5, the condition evaluates to False, and the loop gets terminated.
If the condition specified in the while statement never allows the loop to terminate, i.e., it is always True, then the loop will run infinitely.
While True: print(“Hello World”)
The above code will run forever. As already mentioned, we want to avoid that. Therefore, we need to force the while loop to terminate prematurely. There are three ways to do that.
How to Exit While Loops in Python with the “Break” Statement
The break statement stops the execution of a while loop. Let’s take an example to see how it works.
result = 0 print("Enter -1 to end") while True: value = int(input("Insert a number: ")) if value == -1: break else: result += value print("The sum of the values entered:", result)
Output
Enter -1 to end Insert a number: 12 Insert a number: 8 Insert a number: 6 Insert a number: -1 The sum of the values entered: 26
The above example takes values from the user and adds them to the result variable. The user can enter any number of values. When the user enters -1, the loop stops using the break keyword, and we display the final result.
One thing to keep in mind is that when you have nested loops, the break keyword will only terminate the loop in which it is written. Consider the code below to understand this concept.
i=0 while True: j=0 while True: if j==5: break else: print("Inner Loop Iteration:", j) j += 1 i += 1
Output
Here, we have a nested loop, and the break statement is inside the inner loop. Notice that when j is equal to 5, the inner loop breaks, but we never get out of the outer loop. Therefore, it will run indefinitely.
How to Stop While Loops in Python with the “Return” statement
Another way to end a while loop is to use a return statement. You can only use this if the while loop is inside a function.
Furthermore, it will not only terminate the loop but will also exit from a function. So, we need to ensure that the statements after the while loop are not necessary to run when the loop breaks.
Consider the following example.
def test(): result = 0 print("Enter -1 to end") while True: value = int(input("Insert a number: ")) if value == -1: return result else: result += value res = test() print("The sum of the values entered:", res)
Output
Enter -1 to end Insert a number: 10 Insert a number: 20 Insert a number: 30 Insert a number: 40 Insert a number: -1 The sum of the values entered: 100
This is the same example as above, except we use the return statement instead of the break statement.
How to End While Loops in Python by Raising an Exception
One last way to get out of a while loop is to raise an exception that is not handled inside it.
See the code below:
#find the first number which is divisible by 2 and 3 starting from 1 i=1 try: while True: if (i%2==0 and i%3==0): raise Exception("End Loop") i += 1 except Exception as e: print(e) print("The first number which is divisible by 2 and 3 is: ", i)
Output
End Loop The first number which is divisible by 2 and 3 is: 6
In the above example, when a number i is divisible by 2 and 3, we raise an exception that gets handled outside the loop. The control gets out of the loop, and it terminates.
Conclusion
In this article, we have learned 4 different ways to exit while loops in Python:
- How to Exit a While Loop in Python with the Control Condition
- How to Exit a While Loop in Python with the Break Statement
- How to Exit a While Loop in Python with the Return Statement
- How to Exit a While Loop in Python by Raising an Exception.
Read the article about how to loop back to the beginning of a program in Python next.
Hey guys! It’s me, Marcel, aka Maschi. On MaschiTuts, it’s all about tutorials! No matter the topic of the article, the goal always remains the same: Providing you guys with the most in-depth and helpful tutorials!