The break statement ends the current loop and jumps to the statement immediately following the loop.
for i in range (1,11):
if i == 5:
break #terminate loop if i is 5
print(i)
print("Loop is over.")
Output:
1
2
3
4
Loop is over.
The continue statement ends the current iteration and jumps to the top of the loop and start next iteration.
for i in range (1,11):
if i % 2 == 0:
continue # skip next statement if i is even
print(i)
print("Loop is over.")
Output:
1
3
5
7
9
Loop is over.
If you need a loop that should run forever, you can write the code like this:
while True:
statement
etc.
It’s good to add a break condition, if you want to exit, rather than killing the process. Here is an example to use an infinite loop.
i = 1
while True:
print(i)
i = i + 1
if i == 6:
break
print('Loop is over.')
Output:
1
2
3
4
5
Loop is over.