Topic 14 of 58
while Loops
Overview
A while loop repeatedly executes a block of code as long as a given boolean condition remains True. It is the perfect tool for situations where you do not know in advance how many times the loop needs to run—such as reading data from a network socket, waiting for a server to respond, or running a continuous game loop.
Syntax
python
battery_level = 100
while battery_level > 0:
print(f"Device running. Battery at {battery_level}%")
# CRITICAL: We must update the condition variable,
# otherwise the loop runs infinitely!
battery_level -= 20
print("Battery empty. Shutting down.")Common Pitfalls
- Creating infinite loops by forgetting to update the condition variable inside the loop block.
- Using a
whileloop with a counter when aforloop withrange()is more idiomatic and readable.
Interview Questions
Q:
What does the
else clause do when attached to a while loop?A:
The else block executes precisely when the while condition naturally evaluates to False. Crucially, if the loop is terminated abruptly by a break statement, the else block is entirely skipped.
Real-World Example
Polling an external API continuously until it returns a successful status, with a safety timeout.
example
python
import time
status = "Processing"
attempts = 0
while status != "Complete" and attempts < 5:
print(f"Attempt {attempts + 1}: Checking status...")
# status = check_api_endpoint() (Mocked function)
attempts += 1
time.sleep(1) # Wait 1 second before polling again
if status != "Complete":
print("Operation timed out.")Check Your Knowledge
Test your understanding of while Loops with these quick questions.