Skip to content

Python exit for loop early

  • by

If you want to exit a loop early in Python you can use break , just like in Java. It is used in conjunction with conditional statements (if-elif-else) to terminate the loop early if some condition is met.

Python exit for loop early

Simple example code.

for i in range(5):
    if i == 3:
        break
    print(i)
print('Exit for loop')

Output:

Python exit for loop early

If you want to start the next iteration of the loop early you use continue, again just as you would in Java.

for i in range(5):
    if i == 3:
        continue
    print(i)
print('Finished')

Python exit out of two loops

done = False
for x in xs:
    for y in ys:
        if bad:
            done = True
            break

    if done:
        break

Do comment if you have any doubts or suggestions on this Python 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 *