Skip to content

Python exit while loop | Example code

  • by

Use the break statement to exit while looping 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.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