A while loop in Python repeatedly executes a block of code as long as a specified condition is True. The loop will stop when the condition becomes False.
loop’s body is executed repeatedly while the test at the top is true; if the test is false to begin with, the body never runs.
Syntax:
while condition:
# Code to execute repeatedly
Example 1: Basic while loop
count = 0
while count < 4:
print(count)
count = counter + 1 # Increment the counter
Output:
0 1 2 3In this example, the loop continues until count is no longer less than 4.
Example 2: while loop with break
You can use the break statement to exit the loop early.
i = 0
while i < 5:
print(i)
if i == 3:
break # Exit the loop when i is 3
i += 1
Output:
0 1 2Example 3: while loop with else
Similar to a for loop, you can use an else clause with a while loop. The else the block will run if the loop completes without encountering a break.
i = 0
while i < 3:
print(i)
i += 1
else:
print("Loop finished!")
Output:
01
2
Example 4: Infinite loop
A while loop can become an infinite loop if the condition never becomes False.
while True:
print("This is an infinite loop!")
break # Use a break to avoid an actual infinite loop
Without the break, this would print endlessly. Infinite loops are commonly used when waiting for specific conditions to occur.