
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
whilecondition.
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.
- Write a
whileloop that keeps going whileoilis at least3. - Each round, subtract
3fromoiland add1tonights. - Leave the final
printas it is. It should showBurned for 6 nights, 2 oil left.
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.
- Write a
whileloop that keeps going whileoilis at least3. - Each round, subtract
3fromoiland add1tonights. - Leave the final
printas it is. It should showBurned for 6 nights, 2 oil left.
Press Run to try your code, then Check to test it.