Skip to content
Happy Programming Guide
Start learning
Python

Python While Loops Explained

A while loop repeats for as long as a condition stays true. How to write one, when to use it instead of a for loop, and how to avoid the infinite loop that catches everyone once.

A while loop repeats a block of code for as long as a condition stays true. You use it when you do not know in advance how many times you need to repeat.

Python
count = 3

while count > 0:
    print(count)
    count -= 1

print("Go")

That prints 3, 2, 1, Go. Each pass checks the condition first, and stops the moment it is false.

How it actually runs#

Reading a while loop is easier if you say the steps out loud:

  1. Check the condition.
  2. If it is false, skip the whole block and carry on with the rest of the program.
  3. If it is true, run the indented block.
  4. Go back to step 1.

Note that the check happens before the first pass. If the condition is false to begin with, the body never runs at all:

Python
count = 0

while count > 0:
    print("This never prints")

while or for?#

Ask yourself one question: can I say how many times before the loop starts?

Situation Use
Every item in a list for
Exactly ten times for with range
Until the user types “quit” while
Until the input is valid while
Until a total passes a target while

If you can answer the question, use a for loop. If the stopping point depends on something that happens inside the loop, use while.

The infinite loop#

Everyone writes one. The cause is always the same: nothing inside the loop moves the condition towards being false.

Python
count = 5

while count > 0:
    print(count)        # count never changes — this runs forever

The fix is a line that changes the thing being tested:

Python
count = 5

while count > 0:
    print(count)
    count -= 1          # now it ends

Pattern 1: keep asking until the input is valid#

This is the most useful thing while loops do, and it is why they exist in most beginner programs.

Python
while True:
    raw = input("Enter a number between 1 and 10: ")

    if not raw.isdigit():
        print("That is not a whole number.")
        continue

    number = int(raw)

    if number < 1 or number > 10:
        print("Out of range.")
        continue

    break        # everything passed — leave the loop

print("Thank you:", number)

while True loops forever on purpose, and break is the only way out. That is a normal, readable pattern — not a mistake — as long as there is a reachable break.

Pattern 2: a menu that runs until the user quits#

Python
running = True

while running:
    print("\n1) Add   2) List   q) Quit")
    choice = input("Choice: ").strip().lower()

    if choice == "1":
        print("Adding...")
    elif choice == "2":
        print("Listing...")
    elif choice == "q":
        running = False
    else:
        print("Unknown choice.")

print("Goodbye.")

Using a running flag rather than break makes the exit condition visible at the top, which reads well once a menu grows.

break, continue and else#

Python
n = 0

while n < 10:
    n += 1

    if n == 3:
        continue        # skip the rest of this pass
    if n == 6:
        break           # leave the loop entirely

    print(n)            # 1 2 4 5

Python also lets a while loop have an else, which runs only if the loop finished without hitting break:

Python
attempts = 3

while attempts > 0:
    password = input("Password: ")
    if password == "letmein":
        print("Welcome")
        break
    attempts -= 1
else:
    print("Locked out.")

It is a neat way to say “what to do if we ran out rather than succeeded”.

Counting and accumulating#

Python
total = 0
number = 1

while number <= 100:
    total += number
    number += 1

print(total)    # 5050

A for loop over range(1, 101) does the same job more clearly here — which is the point. Reach for while when the count is genuinely unknown, not to avoid learning range.

Waiting on something else#

A loop that spins as fast as the processor allows will pin a CPU core for no reason. If you are waiting for time to pass, sleep:

Python
import time

seconds = 5

while seconds > 0:
    print(seconds)
    time.sleep(1)
    seconds -= 1

print("Done")

Questions people ask#

Is while True bad practice?

No, as long as there is a break that can actually be reached. It is often clearer than inventing a flag variable, and it is the standard shape for input validation.

What is the difference between break and return?

break leaves the loop and carries on with the rest of the function. return leaves the whole function immediately. Inside a function, return is often the tidier way to exit a search loop.

Can I loop over a list with while?

You can, using an index, but you should not — for item in items is shorter and cannot go out of range. See Python lists explained.

Does Python have a do-while loop?

No. The usual equivalent is while True with the condition checked at the bottom and a break, which is exactly the validation pattern above.

My loop runs one time too many

Check < against <=, and check whether you update the counter before or after the work. Print the counter on every pass and the off-by-one becomes obvious immediately.

Where to go next#

Next lessonPython try / except explained

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *