A snail on a wall
A snail climbs a wall. Each day it climbs 4 cm, and each night it slips back 1 cm. The wall is 10 cm tall. On which day does it reach the top?
Notice a trick. On the third day the snail climbs from 6 up to 10 and reaches the top. It doesn't wait for night to slip back. So the check "have I arrived?" has to happen right after the climb, before the slip.
- day
- 1
- position
- 4
Day 1: the snail climbs 4 and reaches height 4. That's not the top yet.
Break out of the loop
The word break leaves the loop on the spot. Any lines after it in that pass are skipped, and the computer carries on after the loop.
That's just what the snail needs. Make a loop that goes on until you say stop. Each pass is one day: count the day, climb, and then if you've reached the top, break. If not, slip back and carry on. The loop is written as while true, which means keep going until a break happens.
while True:
days = days + 1
position = position + up
if position >= height:
break
position = position - down