Menu
Python While Loop
While Loop
In Python, a while
loop is used to repeatedly execute a block of code as long as a certain condition is true. The break
statement is used to exit the loop prematurely based on a certain condition.
Example:
# While loop with break
counter = 0
while counter < 5:
print(f"Counter: {counter}")
counter += 1
if counter == 3:
print("Breaking the loop.")
break
In the example above, the while
loop continues to execute as long as the counter
is less than 5. Inside the loop, the current value of the counter is printed. When the counter reaches 3, the break
statement is encountered, and the loop is exited.