Break statement is used to terminate the nearest enclosing loop skipping all the code inside the loop after it.
If a loop is terminated by break, control is transferred outside the loop. We can achieve it with the help of ‘break’ keyword.
Consider a following block of code :
for i in range(1,11):
print(i,end=' ')
Above code will print the integers from 1 to 10. But, what if we want to terminate the program once our counter reaches to 5, we’ll do this with the help of break statement.
for i in range(1,11):
if i == 5:
break
print(i,end=' ')
Now, above code will print “1 2 3 4” as output. This is due to the reason that program control will come out of the loop as soon as our counter reaches to 5.
Break has a great utility when we only want to execute some statements of the program based on a particular condition.
