A break statement in Python exits out of a loop. This statement is used under your loop statement, usually after a conditional if statement. It will terminate the loop that contains it, and control of the program flows to the statement immediately after the body of the loop.
break statement in a nested loopIf the break statement is inside a break statement will terminate the innermost loop.
break
The following code will help you understand how to use a break statement to exit a loop.
num = 0for num in range(6):if num == 3:break # exit out of loop hereprint('The value of num is ' + str(num))print('Exited loop')
In this program, we iterate through the integer num which has been initialized to 0. We check if num is equal to 3, upon which we break from the loop. Hence, all num values from num equal to ‘0’ to num equal to ‘2’ get printed. After that, the loop terminates.