How to prevent loops going into infinite mode in Python?


In python the while loop needs to be controlled by making some provision inside the body of the loop to drive the condition mentioned in the beginning to false. This is usually done by keeping count of iterations.

If the while loop condition never evaluates to False, then we will have an infinite loop, which is a loop that never stops automatically, in this case we need to interrupt externally.

count=0
while condition:
   stmt1
   stmt2
   .
   .
   count=count+1

Example

Let’s take an example and see how to prevent the while loop going into the infinity mode.

count = 0
while count < 5:
    print('Python !')
    count+=1

Output

Python !
Python !
Python !
Python !
Python !

Within the loop, we increased the condition variable “Count” value by 1 so that we can iterate through the loop 5 times.

Interupting the loops manually

If we don't mention any loop breaking statements/counter in the program then we can manually interrupt the program by pressing CTRL + C. Then it will raise a KeyboardInterrupt exception like below.

Example

The loop is executed until CTRL + C is pressed, but Python also has a break statement that we can use directly in our code to stop this type of loop.

while True:
    print('Python !')

Output

Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
Python !
.
.
.

---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-9-f36b31426ed4> in <module>
      1 while True:
----> 2     print('Python !')

Using the break statement

Loop repetition can also be controlled by using break statements to take an early exit from the iterations.

Syntax

while True:
   stmt1
   stmt2
   if expr==True: 
   break
   stmt3
   ..

Example

Let’s take the previous example to see how the break statement stops the infinity loop. In this above example, the while loop is executed only one time because the break statement stops the loop in the first iteration.

while True:
    print('Python !')
    break

Output

Python !

Example

Also we can use the Try and except method to handle the infinity loops like below example.

while True:
    try:
        print("Python!")
    except: 
        break

Output

Python!

The above program is also executed until manually interrupted by clicking CTRL + C. But it won’t raise KeyboardInterrupt exceptions like the previous example. The except block suppresses the KeyboardInterrupt exceptions by using break statements.

Updated on: 23-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements