while Loops

The Course
•
January 6, 2026
•
5 min read

A while loop repeats a block for as long as its condition stays true. It is the loop to reach for when you do not know in advance how many repetitions you need.

Counting down Python
count = 3

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

print("Lift off")

Trace it once by hand: check 3 > 0 → print, decrement → check 2 > 0 → … → check 0 > 0 → false, so the loop ends and the last line runs.

Every while loop needs an exit

If nothing inside the loop can make the condition false, the loop never ends. Forget the count -= 1 above and the program prints 3 forever. In this playground that is harmless — press Stop, which kills the runtime and restarts it. In a terminal it is Ctrl-C.

Accumulating a result

The classic while shape is: set something up, loop until done, use the result.

Summing until a limit Python
total = 0
n = 1

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

print(f"Adding 1..{n - 1} first exceeds 100 at {total}")

Validating input

This is where while earns its place in everyday code: keep asking until the answer makes sense.

Ask until valid Python
answer = ""

while not answer.isdigit():
    answer = input("Enter a positive whole number: ")
    if not answer.isdigit():
        print("  That is not a positive whole number.")

print(f"Thank you: {int(answer)}")

Three answers are pre-filled for this one — maybe, -4, then 7 — so you can watch it reject two and accept the third.

break and continue

break leaves the loop immediately. continue skips the rest of this pass and goes back to the condition.

Leaving early, skipping ahead Python
n = 0
while True:                 # deliberately endless...
    n += 1
    if n % 2 == 0:
        continue            # skip even numbers
    if n > 9:
        break               # ...until this fires
    print(n)

print("Done at", n)

while True: with a break inside is a normal, readable Python idiom for “loop until something happens”. It is not a code smell, as long as the break is easy to find.

The loop else clause

Python loops can take an else, which runs only if the loop finished without hitting a break. It is unusual, and perfect for search loops.

Search, and report failure once Python
target = 7
n = 1

while n <= 5:
    if n == target:
        print("Found it")
        break
    n += 1
else:
    print(f"{target} was not in range")

Without else you would need a found = False flag and an if not found: afterwards. The else says the same thing in one word.

Before you write your own

Predict. You save $30 a week towards $100. What does this print? Trace it by hand, one pass at a time, before you run it.

What will this print? Python
savings = 0
weeks = 0

while savings < 100:
    savings += 30
    weeks += 1

print(weeks, savings)
Check your prediction
4 120

After three weeks you have 90, which is still under 100, so the loop runs once more. The condition is only checked at the top of each pass — so the loop can overshoot, and here it ends at 120, not 100.

Fix. A countdown should print 5, 4, 3, 2, 1 and then Go!. One number is missing.

Off by one Python
count = 5
while count > 1:
    print(count)
    count -= 1
print("Go!")
Check your fix
count = 5
while count > 0:
    print(count)
    count -= 1
print("Go!")
5
4
3
2
1
Go!

When count is 1, 1 > 1 is false, so the loop stopped before printing it. Missing the first or last item by one is the most common loop bug there is; trace the final pass by hand whenever a loop’s edge matters.

Exercise

Guess the number

The secret is 42. Keep asking for a guess until it is correct, saying “higher” or “lower” each time, then report how many guesses it took.

The pre-filled answers are 50, 25, 42, so your program should say Lower, then Higher, then that it took 3 guesses.

secret = 42
guesses = 0

# Your code here
Hint 1: the idea

You don’t know how many guesses it will take, so this is a while loop. And the test that ends it — “was that guess right?” — can only happen after you’ve read a guess. That’s the while True: with a break shape from above.

Hint 2: a first step

Inside while True:, read one guess with int(input("Guess: ")) and add 1 to guesses. Then you need three branches: correct (print and break), too low, and too high.

Show one solution
secret = 42
guesses = 0

while True:
    guess = int(input("Guess: "))
    guesses += 1

    if guess == secret:
        print(f"Correct in {guesses} guesses")
        break
    elif guess < secret:
        print("  Higher")
    else:
        print("  Lower")

while True plus break fits this problem better than a condition at the top, because the test that ends the loop only makes sense after reading a guess.

What you learned

  • while condition: repeats until the condition goes false.
  • Something in the body must move towards the exit, or the loop never ends.
  • break exits now; continue skips to the next pass.
  • while True: with a break is the idiom for “until something happens”.
  • A loop’s else runs when no break fired.
Last updated on January 6, 2026

Was this article helpful?

Your response is saved on this device.