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

x=0
while x<5:
   x=x+1
   print (x)

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

while True:
   stmt1
   stmt2
   if expr==True: break
   stmt3
   ..
raja
Published on 20-Feb-2018 00:05:20
Advertisements