Basic While Loop Syntax
The while loop in Python repeatedly executes a block of code as long as a specified condition evaluates to true. This construct is ideal for scenarios where the number of iterations is not predetermined.
counter = 0
while counter < 5:
print(f"Current iteration: {counter}")
counter += 1
print("Loop completed!")The condition is evaluated before each iteration. If the condition is truthy (non-zero, non-empty, or not None), the loop body executes. When the condition becomes falsy, the loop terminates.
Controlling Loop Execution with Break and Continue
Python provides two essential control statements for modifying loop behavior:
- break: Immediately terminates the loop and transfers execution to the statement following the loop.
- continue: Skips the remaining code in the current iteration and proceeds to the next iteration.
Example demonstrating both keywords:
num = 0
while num < 20:
num += 1
if num % 2 != 0:
continue # Skip odd numbers
print(f"Even number: {num}")
# Using break with an infinite loop condition
value = 0
while True: # Always true condition
print(f"Processing value: {value}")
value += 1
if value >= 5:
break # Exit when value reaches 5Infinite Loops
An infinite loop occurs when the loop condition never becomes false. While sometimes intentional (e.g., server applications), unintentional infinite loops can cause programs to hang.
status = True
iteration = 0
while status:
iteration += 1
print(f"Running iteration #{iteration}")
# Without a break or status change, this runs indefinitely
if iteration >= 3:
status = False # Properly exit the loopWhile-Else Construct
Python supports an optional else clause with while loops. The else block executes when the loop condition becomes false, but not if the loop is terminated by a break statement.
threshold = 0
while threshold < 4:
print(f"{threshold} is below threshold")
threshold += 1
else:
print(f"{threshold} has reached or exceeded the threshold")Single-Line While Loops
Similar to conditional statements, if the loop body consists of a single statement, it can be written on the same line as the while keyword:
active = True
while active: active = False # Executes once, then terminates