How to Stop an Infinite Loop in Python?
Programming can be fun to do until you see the code covered in red or the compiler say SyntaxError. What’s more frustrating is to see the code run but infinitely, as is the case for infinite loop in Python.
An infinite loop is an ever-going sequence of iterations that continue to run endlessly unless provided with external interference.
The execution of a block of code that goes on forever is called an iteration. A loop, in general, is a programming structure where iterations are implemented.
Recurring iterations can cause unwanted delays and lagging and may interrupt the performance of the system.
In computer programming, iterations are classified into two categories: definite and indefinite iterations.
In an indefinite iteration, it is not specified explicitly as to how many times the loop will execute.
Instead, the loop repeats itself continuously unless a particular condition is met that is specified in the loop body. Conversely, in a definite iteration, the recurrence of the loop is pre-defined explicitly before the loop starts.
Now that we have covered the basics to understand loop and iterations, it’s important to know how loop statements – particularly infinite loops – are constructed in Python before delving into details about how to stop them from recurring.
How to Stop an Infinite Loop in Python
The while Loop
A while loop repeatedly iterates over a block of code as long as the specified condition stays True. A primitive while loop format is as follows:
while <condition>: <statement>
The <statement> in the above code – called the loop body – will execute forever until the <condition> holds no more. The controlling <condition> usually consists of at least one variable that is initialized at the start and may be modified within the loop body.
Fact: Unlike most programming languages, indentation is of significant importance in Python because the statements that match the indentation level of the preceding condition(s) are considered part of the same block.
Before execution, the while loop tests if the initializing condition is true and then proceeds to run the statement to infinity if it does not meet any terminating conditions. Let’s consider an example with a loop terminating condition:
n = -1 while n < 0: n += 1 print(‘Infinite Loop’)
Infinite Loop (Loop Ends)
- In the above example, modification has been made as an increment of +1 in the value of n.
- The code starts with n defined as an integer value of -1.
- The while loop executes and the initial condition is met because -1 < 0 (true).
- In the 3rd line, first, the value of n adds up to zero (-1 + 1 = 0) then the print command is executed.
Here, the loop only prints the outcome Infinite Loop once because, in the next run, the condition becomes False (i.e. 0 ≠ 0). Therefore, the loop terminates.
Consider another example but this time without a terminating condition:
n = -1 while n < 0: print(‘Infinite Loop’)
Infinite Loop Infinite Loop Infinite Loop …….. (Forever)
Here’s what is happening:
- The code starts with a variable defined as n with an initial value of -1.
- while loop executes and checks the initial condition if n < 1 – which certainly is true.
- The print command prints the expression within the parenthesis and the loop restarts.
- Again, the while loop starts and checks the condition which still holds true because it finds no increment or decrement command inside the body. Hence, n always remains -1 and the loop goes on forever.
- The outcome will always be the same: Infinite Loop.
The Infinite Loop
Until now we have seen while loops with and without a terminating condition. But what if we want to break a loop that – theoretically – never ends. The answer lies within the question: break.
Before we get to specific pre-defined commands from the Python library, suppose a scenario with a block of code that goes on endlessly with a condition that is literally ‘True’, as in the example below:
while True: print(‘Infinite Loop’)
Infinite Loop Infinite Loop Infinite Loop … … … … Infinite Loop KeyboardInterrupt Traceback (most recent call last): File “<pyshell#2>”, line 3, in <module> Print(‘Infinite Loop’)
The above infinite loop was terminated manually by pressing Ctrl + C from the keyboard to provide an external interruption for the program – a direct way to terminate the whole loop which would go on forever.
The remaining output lines after Ctrl + C have been eliminated by a returning command as KeyboardInterrupt.
As clear from the example that an infinite loop is initiated by a never-failing condition that always remains true.
Perhaps one might think that why this condition would ever appear while writing a program, but in practical scenarios, this is found more than often.
As an example, one may want to write code for a business that sells its services twenty-four hours a day and seven days a week – without interruption to be precise.
In that case, the user might appear anytime for a service, hence the system has to be operating endlessly. By endlessly means either the system is either turned off or the loop is terminated manually.
There are two pre-defined commands in Python that may be used to terminate an infinite loop iteration prematurely: break and continue.
Without a say, it is easy to relate the break command because it is pretty much self-explanatory.
Apparently, the continue command might seem a bit confusing relative to the context being discussed, but that’s really not the case. We shall see how in the succeeding paragraphs.
The Break and Continue Commands
The while loop comes with the feature that it treats each iteration as a whole. Meaning that the entire body of statements gets executed after it completes its one loop-run.
But for cases when termination is required between some ongoing loop, that is where break and continue commands play their role. This can be understood from the figure below:
Figure: Break and Continue commands in Python
- As evident from the figure, the break command terminates the entire loop and the program jumps to the last statement at the end of the program.
- The continue command, on the other hand, only terminates the ongoing loop and the program returns to the initial condition statement where the controlling expression is checked again whether or not to execute the loop further.
Consider the following example codes of break and continue commands used to terminate an infinite loop in Python:
Example Codes for Break Command
x = 5 while x > 0: x -= 1 if x == 2: break print(x) print(‘End of Loop’)
4 3 End of Loop
Then, before printing the x values, it subtracts 1 each time from the original value. When x becomes exactly equal to 2, it breaks the loop from the 5th line without printing the value and jumps to the 7th line to print End of Loop. The above example presents a while loop with a break command that terminates the loop. First of all, the loop tests whether the value of variable x is greater than zero, which is in this case.
The program will restart from this point and will continue with the same output.
Fact: It should be noted that although break commands are used to terminate an infinite loop, it is more appropriate to apply terminations based on pre-defined conditions inside the loop body rather than outside or atop the loops.
Here is a variant of an infinite loop that exits the iteration with the break command using a built-in .pop() function:
x = [‘a’, ‘b’, ‘c’] while True: if not x: break print(x.pop(-1))
c b a
In this example, the while loop is always True but the terminating condition inside the loop won’t let it go endlessly.
The function .pop() successively removes elements from x and prints them consecutively until x gets empty. This is a very good example in the sense that the loop remains true throughout, but the function variables a, b, and c are popped-up due to which it breaks.
It is also possible to include multiple break statements in a single loop. Such a condition will imply that there exist multiple causes to end the ongoing loop, where if one fails, the other is tested, and so on, as in the following case:
while True: if <condition1>: # First loop termination condition break …… if <condition2>: # Second loop termination condition break …... if <condition1>: # Third loop termination condition break
Example Code for Continue Command
As stated above, the continue command is used to terminate a loop to restart it all the way from the beginning by re-calculating the condition to decide further continuance. Let’s take the same example that we used for the break program and replace it continue command, as follows: Example Code for Continue Command
x = 5 while x > 0: x -= 1 if x == 2: continue print(x) print(‘End of Loop’)
4 3 1 0 End of Loop
The above example presents a while loop with a continue command that terminates and restarts the loop at x equals 2.
It first checks whether the value of variable x is greater than zero, which is in this case. Then, before printing the x values, it subtracts 1 each time from the original value.
When x reaches the exact value of 2, it breaks the loop from the 5th line without printing the value and goes back to the 2nd line to print values other than 2 until End of Loop. The program will restart from this point and will continue with the same output.
Caveat: Common Errors in Loops
In Python programming, it is possible for a while loop to contain another while loop inside it – called as nested loops.
This can a bit tricky to handle with break and continue statements. A caveat that needs attention is if the break or continue statements are found within a nested loop, they only apply to the nearest preceding while loop instead of the whole nest.
An example can illustrate this concept:
while <condition1>: <statement> <statement> while <condition2>: <statement> <statement> break # Applies to while <condition2> loop break # Applies to while <condition1> loop
As clear in the above example for nested while loops that the first break statement applies only within while <condition2> loop, whereas the second break statement applies only within while <condition1> loop.
Another caveat for a while loop may be when they are written in one line rather than in multiple lines. It might generate SyntaxError: invalid syntax in the output screen. Although this works, it only works for simple statements. Combining two compound statements into one line can cause an error. Moreover, writing many statements at one line may also increase the complexity of the structure.
For example, you can write a code like this:
x = 3 while x > 0: x -= 1; print(x)
2 1 0
But you cannot write like this with an if/else statement combined at one line:
while x > 0: x -= 1; if True: print(x)
So far we discussed some important pre-requisite definitions and concepts like loops, iterations, and their types.
We also went through examples of while loops and infinite loop in Python programming. We learned how the break and continue statements can be used to break an infinite loop that goes on endlessly.
Lastly, we pondered over some caveats and common causes of errors that arise in nested loops with example codes to avoid them.
Hence, with the help of in-depth examples and thorough explanations, we learned how to stop an infinite loop in Python.
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!