Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
breakstatement
communitycreator

How to break out of a loop in Python

Rameen Farrukh

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 loop

If the break statement is inside a nested loopa loop inside of another loop, the break statement will terminate the innermost loop.

Syntax

break 
Flow chart to break out of a loop

Code

The following code will help you understand how to use a break statement to exit a loop.

num = 0

for num in range(6):
    if num == 3:
        break    # exit out of loop here

    print('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.

RELATED TAGS

python
breakstatement
communitycreator
RELATED COURSES

View all Courses

Keep Exploring