You can break 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
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
Do comment if you have any doubts or suggestions on this Python while loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.