A while loop executes code repeatedly as long as its target boolean condition remains True. while loops are ideal when the number of required iterations is unknown before loop entry.
flowchart TD
A["Loop Entry"] --> B{"Condition Evaluates True?"}
B -- "Yes" --> C["Execute Loop Body"]
C --> D{"Break Encountered?"}
D -- "Yes" --> E["Exit Loop Immediately"]
D -- "No" --> B
B -- "No" --> F["Execute while...else Block (If no break occurred)"]
F --> G["Resume Execution"]
E --> G
break: Terminate the loop immediately.continue: Skip the rest of the current iteration and re-evaluate condition.else: Executes once when the loop condition turns False (skipped if exited via break).import time
def retry_connection(max_attempts: int = 3) -> bool:
"""Simulate exponential backoff connection retries using a while loop."""
attempt = 1
connected = False
while attempt <= max_attempts:
print(f"Connection attempt {attempt} of {max_attempts}...")
# Simulated connection condition (succeeds on attempt 3)
if attempt == 3:
connected = True
print("Successfully established database connection!")
break
attempt += 1
time.sleep(0.1)
else:
# Executes only if loop finishes naturally without 'break'
print("Failed to connect after maximum attempts.")
return connected
if __name__ == "__main__":
retry_connection(max_attempts=4)
while True with Explicit Break: For event loops or interactive interfaces, use while True: combined with explicit if exit_condition: break.while...else Semantic: Remember that the else block runs only when the condition evaluates to False, NOT when the loop is terminated by break.Write a while loop that calculates the factorial of a given integer $N$ ($N! = N imes (N-1) imes \dots imes 1$) and prints the result.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With