indusai.co

While loops

A while loop repeats a block as long as its condition stays true. Use it when you do not know in advance how many times you need to repeat.

Basic while loop

python
count = 1
while count <= 5:
    print(count)
    count += 1
print("Done")

Every while loop has three parts: something set up before it, a condition checked at the top of each pass, and something inside the block that eventually makes the condition false. Forget the third part and the loop never ends.

break

break leaves the loop immediately.

python
n = 0
while True:
    n += 1
    if n * n > 50:
        break
print("First square above 50 is", n * n)

while True with a break inside is the standard pattern for "keep going until something happens".

continue

continue skips the rest of the current pass and jumps back to the condition.

python
i = 0
while i < 10:
    i += 1
    if i % 3 != 0:
        continue
    print(i, "is divisible by 3")

else on a loop

The else block runs when the loop finishes without hitting break. It is rarely used, but handy for search loops.

python
numbers = [2, 4, 6, 8]
i = 0
while i < len(numbers):
    if numbers[i] % 2 == 1:
        print("Found an odd number")
        break
    i += 1
else:
    print("All numbers are even")

A common pattern: repeat until valid input

python
while True:
    answer = input("Type yes or no: ")
    if answer in ("yes", "no"):
        break
    print("Please try again")
print("You said", answer)

Countdown

python
n = 5
while n > 0:
    print(n)
    n -= 1
print("Lift off")

Avoiding infinite loops

If a program seems to hang, you probably have a loop whose condition never becomes false. Press Ctrl+C in a terminal to stop it. Check that the variable in the condition is actually changing inside the loop.

Practice

  1. Print the powers of 2 that are less than 1000.
  2. Use a while loop to find the sum of the digits of 98765.
  3. Simulate a bank balance of 1000 that loses 12 percent each year. How many years until it drops below 500?