Code

While the Oil Lasts

A for loop is great when you know how many times to repeat. A while loop repeats as long as a condition is true, handy when you don't know in advance how many rounds you need.

steps = 0
while steps < 3:
    print("Step", steps)
    steps += 1
print("Done!")

Before each round Python checks steps < 3. When it becomes False, the loop stops and the program carries on below it.

Beware the endless loop

If nothing inside the loop ever makes the condition False, it runs forever! Always change something the condition depends on (here, steps += 1).

Pip tip: If your program seems stuck, you probably forgot to update the variable in your while condition.

Assignment

A lantern starts with 20 units of oil and burns 3 units each night. It can only burn a night if it has at least 3 units left.

  1. Write a while loop that keeps going while oil is at least 3.
  2. Each round, subtract 3 from oil and add 1 to nights.
  3. Leave the final print as it is. It should show Burned for 6 nights, 2 oil left.