Python Basics · Lesson 8 of 12

While Loops

A for loop is for when you know what to loop over. A while loop is for when you only know when to stop. It repeats as long as its condition is true:

countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Lift off!")

Before each round, Python checks the condition. When it becomes false, the loop ends and the program continues below it.

Loops that never end

Something inside the loop must eventually make the condition false. Leave out countdown -= 1 above, and the loop runs forever. If that happens here, the editor stops your program after a few seconds and tells you.

A typical use

while suits problems where the number of rounds depends on the data:

savings = 100
years = 0
while savings < 200:
    savings = savings * 1.07   # 7 percent interest
    years += 1
print(years)   # 11

How many years until the money doubles? You do not know in advance, which is exactly when to reach for while.

break

break leaves a loop immediately, even if the condition is still true:

n = 1
while True:
    if n * n > 50:
        break
    n += 1
print(n)   # 8, the first number whose square is over 50

while True on its own would run forever. With a break inside, it means "keep going until I say stop".

Your Task

  1. A water tank holds 500 liters, and 60 liters are used each day.
  2. Write a while loop that keeps going as long as there are at least 60 liters left. In each round, subtract 60 from tank and add 1 to days.
  3. After the loop, print days, then print tank (the liters left over).
  • The code uses a while loop
  • days ends up as 8
  • tank ends up as 20
  • The number of days and the liters left are printed, in that order