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.
break and continueUse 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")
while ... else ClausePython 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.
attempts never increases, while attempts < 3: loops forever until you press Ctrl+C.while x != 1.0: with x += 0.1 can skip 1.0 due to binary rounding; use while x < 1.0:.while where for is simpler: Iterating through a list with an index counter in while is slower and bug-prone compared to for item in items:.Press Ctrl+C in your terminal to send a KeyboardInterrupt and stop the running Python script.
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.
continue skip incrementing my counter?Yes, if the increment sits below continue. Always update your loop counter before any continue statement.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.