Python exit while loop | Example code

Use the break statement to exit while loop in Python. A “break” is only allowed in a loop (while or for), and it causes the loop to end but the rest of the program continues.

  • break: is used to exit a loop
  • sys.exit(): is used to terminate the running program.

Python exit while loop example

Simple example code.

n = 0

while n < 5:
    n += 1
    if n == 2:
        break

    print(n)

print('Loop ended.')

Output:

Python exit while loop

Another example code

Use of break statement inside the loop

for val in "string":
    if val == "i":
        break
    print(val)

print("The end")

Output:

s
t
r
The end

Do comment if you have any doubts and suggestions on this Python while loop.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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