Chapters
Python114 chapters

Control flowChapter 45 of 114

While Loops

Repeat while a condition holds, and make sure it eventually stops.

The form

A while loop repeats as long as its condition is true:

Python
count = 0

while count < 3:
    print(count)
    count += 1

print("done")

Output

0
1
2
done

The condition is checked before each pass, so a loop whose condition starts false never runs at all:

Python
while False:
    print("never printed")

print("skipped it")

Output

skipped it

Something has to change

Every while loop needs something in the body that eventually makes the condition false. Forget it and the program hangs:

Python
count = 0
while count < 3:
    print(count)   # count never changes, so this never stops

while versus for

Use for when you know what you are iterating over. Use while when you do not know how many passes it will take:

Python
balance = 100
years = 0

while balance < 150:
    balance *= 1.1
    years += 1

print(years, round(balance, 2))

Output

5 161.05

You could not write that as a for loop without working out the answer first.

The deliberate infinite loop

while True with a break is a normal and readable pattern when the exit condition sits in the middle of the body:

Python
values = [3, 7, -1, 9]
index = 0

while True:
    if index >= len(values):
        break
    if values[index] < 0:
        print("found a negative at", index)
        break
    index += 1

Output

found a negative at 2

break and continue

break leaves the loop immediately. continue skips to the next condition check:

Python
n = 0
while n < 6:
    n += 1
    if n % 2 == 0:
        continue
    if n > 4:
        break
    print(n)

Output

1
3

while...else

The else runs only when the loop ended because the condition went false — not when a break stopped it:

Python
n = 0
while n < 3:
    n += 1
else:
    print("ended naturally")

n = 0
while n < 3:
    n += 1
    break
else:
    print("not printed")

print("done")

Output

ended naturally
done

It is rarely used, and worth recognising when you meet it.

A guarded input loop

The shape you will write most often in real programs:

Python
attempts = ["abc", "-5", "42"]

for typed in attempts:
    if not typed.lstrip("-").isdigit():
        print(typed, "is not a number")
        continue
    value = int(typed)
    if value < 0:
        print(typed, "is negative")
        continue
    print("accepted", value)
    break

Output

abc is not a number
-5 is negative
accepted 42

Test yourself

2 questions

What is the most common cause of an infinite while loop?

Show the answer

Nothing in the body changes the variable in the condition — Every while loop needs something that moves it towards the condition becoming false.

When does a while...else clause run?

Show the answer

Only when the loop ended because the condition went false — A break skips the else entirely. The same rule applies to for...else.

Next chapter

For Loops

Walk a sequence, count with range, and loop over dictionaries.