How to break a for loop in Python?

Server Side ProgrammingProgrammingPython

Normally the for loop is constructed to iterate over a block for each item in a range. If a premature termination of loop is sought before all iterations are completed, break keyword is used. It is invariably used in a conditional statement inside the body of loop

for x in range(20):
     print (x)
     if x==10: break
print ("end of loop")

In this case even though range is upto 20, loop will terminate at x=10

Published on 19-Feb-2018 23:37:23