TExcelTAD
Home › Python › Python While Loops

Python While Loops

A while loop repeats a block as long as a condition stays true. Use it when you don't know in advance how many repetitions you need — "keep going until the data runs out", "retry until it succeeds".

Basic while

python · try it yourself
count = 1
while count <= 5:
    print("Count is", count)
    count += 1
print("Done")
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Done

Every while loop needs three things: a variable that's set up before the loop, a condition that tests it, and something inside the loop that changes it. Forget the last part and the condition never becomes false — an infinite loop.

Tip: If you accidentally start an infinite loop in a playground, ExcelTAD stops it after a timeout. In a terminal, press Ctrl+C.

A loop that doesn't know its length

Here is a typical "until" problem: how many years until savings double at 7% interest?

python · try it yourself
balance = 1000.0
years = 0
while balance < 2000:
    balance *= 1.07
    years += 1
print(f"{years} years, final balance {balance:.2f}")
11 years, final balance 2104.85

break — leave the loop early

break exits the loop immediately, skipping the rest of the body and the remaining iterations:

python · try it yourself
numbers = [4, 9, 15, 22, 7]
i = 0
while i < len(numbers):
    if numbers[i] > 10:
        print("First number above 10:", numbers[i])
        break
    i += 1
First number above 10: 15

A common pattern is while True: with a break inside, for loops whose exit condition is easiest to check in the middle:

python · try it yourself
commands = ["start", "status", "stop", "never reached"]
position = 0
while True:
    cmd = commands[position]
    position += 1
    if cmd == "stop":
        print("Stopping.")
        break
    print("Running command:", cmd)
Running command: start
Running command: status
Stopping.

continue — skip to the next iteration

continue jumps straight back to the condition check, skipping the rest of the current pass:

python · try it yourself
n = 0
while n < 10:
    n += 1
    if n % 3 != 0:
        continue
    print(n, "is divisible by 3")
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3

Notice that n += 1 comes before continue. If it came after, continue would skip it and the loop would never end.

while … else

A loop may have an else block. It runs when the loop ends normally (the condition became false), but not when it was left with break. This is handy for searches:

python · try it yourself
def find_divisor(n):
    d = 2
    while d * d <= n:
        if n % d == 0:
            print(n, "is divisible by", d)
            break
        d += 1
    else:
        print(n, "is prime")

find_divisor(91)
find_divisor(97)
91 is divisible by 7
97 is prime

Loop control summary

Statement Effect
break Exit the loop now; else is skipped
continue Skip to the next condition check
else: Runs if the loop finished without break
pass Does nothing (placeholder)

Note: When you are going through the items of a list, string or range, a for loop (next lesson) is simpler and safer than managing an index with while.

Test yourself

When does the else block of a while loop run?

  1. Always
  2. Only when the loop body never ran
  3. When the loop ends without hitting break
  4. Only after a continue

What happens if the variable in the condition is never changed inside the loop?

  1. The loop runs once
  2. Python raises an error
  3. The loop may run forever
  4. The loop is skipped