How to prevent loops going into infinite mode in Python?

PythonServer Side ProgrammingProgramming

Loops formed with for statement in Python traverse one item at a time in a collection. Hence there is less likelihood of for loop becoming infinite.

The while loop however 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

while x<5:
   print (x)

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

while True:
   if expr==True: break
Published on 20-Feb-2018 00:05:20