Skip to content

Python break while loop

  • by

You can break a while loop using a break statement in Python. The While loop executes a set of statements in a loop based on a condition and breaks the loop when this while condition evaluates to false.

while condition :
    #statement(s)
    if break_condition :
        break

Python break while loop

Simple example code print numbers from 1 to 100. But, when we shall break the loop after the number 3 is printed to the console.

i = 1
while i <= 100:
    print(i)
    if i == 3:
        print('Break While loop')
        break
    i += 1

Output:

Python break while loop

Breaking Infinite While Loop

i = 1
while True :
    print(i)
    if i == 8 :
        break
    i += 1

Breaking Nested While Loop

i = 1
while i < 6 :
    j = 1
    while j < 8 :
        print(i, end=" ")
        if j == 3 :
            break
        j += 1
    print()
    i += 1

In Python, you can use the break statement to exit a while loop prematurely. The break statement is typically used when a certain condition is met, and you want to immediately terminate the loop.

Comment if you have any doubts or suggestions on this Python while 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