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.')
Another example code
Use of break statement inside the loop
for val in "string": if val == "i": break print(val) print("The end")
s t r The end
Do comment if you have any doubts and suggestions on this Python while loop.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.