while Loops

The Course
January 6, 2026
4 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.

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.

secret = 42
guesses = 0

# Your code here
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.