Python While Loops
Python While Loops: Condition-Driven Repetition
A Python while loop runs a block of code repeatedly as long as its condition evaluates to True. Unlike for loops that iterate over a known sequence, while loops shine when you do not know upfront how many attempts are needed.
Common real-world uses include polling an API until a job completes, reading chunks from a stream, or prompting a user until valid input arrives.
Controlling Loop Flow with break and continue
Use break to exit the loop immediately, and continue to skip the rest of the current pass and re-check the while condition.
attempts = 0
max_attempts = 3
connected = False
while attempts < max_attempts:
attempts += 1
if attempts == 2:
print("Attempt 2 timed out, retrying...")
continue
if attempts == 3:
connected = True
break
print(f"Connected={connected} after {attempts} attempts")
The Optional while ... else Clause
Python allows an else: block after a while loop. That else: runs only if the loop ended normally because its condition became False, not when stopped by break.
Common Mistakes to Avoid
- Forgetting to update the loop variable: If
attemptsnever increases,while attempts < 3:loops forever until you pressCtrl+C. - Testing floats for exact loop exit: Writing
while x != 1.0:withx += 0.1can skip1.0due to binary rounding; usewhile x < 1.0:. - Using
whilewhereforis simpler: Iterating through a list with an index counter inwhileis slower and bug-prone compared tofor item in items:.
Frequently Asked Questions
How do I stop an infinite loop in the terminal?
Press Ctrl+C in your terminal to send a KeyboardInterrupt and stop the running Python script.
When is while True: good practice?
while True: paired with a clear if done: break condition works well for input validation loops and event polling where the exit check happens mid-loop.
Does continue skip incrementing my counter?
Yes, if the increment sits below continue. Always update your loop counter before any continue statement.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.