Skip to content

Python exit for loop | Example code

  • by

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

Example exit for loop in Python

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

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

Do comment if you have any doubts and 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.