Keywords Within Loops
tags: #python/documentation/python_loops
The Break Keyword
The break statement is used to exit a loop prematurely, before its normal termination. When encountered, the break statement immediately terminates the innermost loop in which it appears.
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
The break keyword must be indented relative to the body of the loop, and de-indented when returning to the body of the loop.
This ends the loop in its entirety and jumps out of the loop to the statement immediately following the loop. This is often used in conjunction with conditional statements.
The Continue Keyword
The continue statement is used to skip the rest of the code inside a loop for the current iteration and move on to the next iteration. In other words, the continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration without needing to finish the body of the loop for the current iteration.
for i in range(5):
if i == 2:
continue # Skip the rest of the loop body when i is 2
print(i)