Skip to content

Python exit for loop | Example code

  • by

Use the break keyword with the if statement to exit for loop in Python. The break statement provides an opportunity to exit out of a loop when the condition is triggered.

Here’s an example of how you can use break to exit a for loop:

for item in iterable:
    # some code here
    if condition:
        break  # exit the loop

    # more code here

Example exit for loop in Python

A simple example code uses a break statement after a conditional if statement in for loop. If the number is evaluated as equivalent to 2, then the loop breaks.

The break statement is used to terminate the current loop and resume execution at the next statement outside the loop.

number = 0

for number in range(10):
    if number == 2:
        break    # break here

    print('Number is ' + str(number))

print('Out of loop')

Output:

Python exit for loop

Other Examples

Python exit loop iteration.

alphabet = ['a', 'b', 'c', 'd']

for letter in alphabet:
    if letter == 'b':
        break
        # terminates current loop
    print(letter)

Output: a

Note: break only exits the innermost loop it is contained in. If you have nested loops and want to exit an outer loop from an inner loop, you can use labeled loops and the break statement with a label. Here’s an example:

for i in range(5):
    for j in range(5):
        if i == 2 and j == 3:
            break  # exit the inner loop

    if i == 2 and j == 3:
        break  # exit the outer loop

In this example, if the condition i == 2 and j == 3 is true, the inner loop will be exited with break, and then the outer loop will also be exited with break.

Do comment if you have any doubts or suggestions on this Python for loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading