A while loop repeats a block as long as its condition remains true.
count = 1
while count <= 5:
print(count)
count += 11 2 3 4 5
Three things keep the loop finite:
- The condition is initially true.
- The body changes a value used by the condition (
count += 1). - The condition eventually becomes false.
If a loop never changes its condition, it runs forever (or until ILoveCompiler's time limit stops it).
Accumulating a result#
total = 0
number = 1
while number <= 100:
total += number
number += 1
print(total)total is an accumulator. Initialise it before the loop and update it inside.
Reading until a sentinel#
A sentinel is a value that signals the end of input:
total = 0
while True:
text = input()
if text == "done":
break
total += int(text)
print(f"Total: {total}")while True is an intentional infinite loop. The break inside provides the exit. This pattern is readable when the stopping condition is easier to check after reading input.
while versus for#
Use while when the number of iterations is unknown and depends on a condition. Use for when iterating over a sequence or a known range.
# Known count: prefer for
for attempt in range(3):
print("Attempt", attempt + 1)
# Unknown count: while fits
remaining = 10
while remaining > 0:
print(remaining)
remaining -= 3Validating input#
text = input("Enter a positive number: ")
while not text.isdigit():
print("Please use digits only.")
text = input("Enter a positive number: ")
print("You entered", int(text))In ILoveCompiler, all input lines are supplied before the run. If the available lines run out, input() raises EOFError, which is a useful signal that the program needs more input.
Practice#
Write a loop that starts at 20 and counts down to 0, printing only even numbers. Then write a loop that repeatedly doubles a starting value of 1 until it exceeds 1000, printing each value.
