Lesson

Python While Loops

10 min reading
Free Course

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 attempts never increases, while attempts < 3: loops forever until you press Ctrl+C.
  • Testing floats for exact loop exit: Writing while x != 1.0: with x += 0.1 can skip 1.0 due to binary rounding; use while x < 1.0:.
  • Using 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:.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum