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 we do that? There are multiple ways through which we can terminate the loop. So, let’s get started and understand each one of them.
1. 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
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.
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)
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
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.
Another way to end a while loop is to use a return statement. Note that 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 make sure 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)
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.
4. Raising an Exception
One last way to get out of a while loop is to raise an exception that is not handled inside it. Let’s see.
#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)
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.
In this article, we have learned 4 different ways to exit while loops in Python code. From the “Control Condition” to “break and “return”. The last way we had a closer look at was by “raising an exception”.
Hey guys! It’s me, Marcel, aka Maschi. I earn a full-time income online and on MaschiTuts I gladly share with you guys how I stay on top of the game! I run several highly profitable blogs & websites and love to speak about these project whenever I get a chance to do so. I do this full-time and wholeheartedly. In fact, the moment I stopped working an 8-to-5 job and finally got into online business as a digital entrepreneur, is problably one of the best decisions I ever took in my life. And I would like to make sure that YOU can get on this path as well! Don’t let anyone tell you that this can’t be done. Sky’s the limit, really…as long as you BELIEVE in it! And it all starts right here..at Maschituts!