Week 5 · Session 3
Doing something more than once without writing it more than once.
The CRITICAL branch flashes the light three times.
led.on(), time.sleep(0.1), led.off(), time.sleep(0.1), and then the same four lines again, and againfor Loopfor flash in range(3): means: run the indented block below, three timesfor line, the same rule as ifrange(3) is three iterationsThis is the CRITICAL branch as a loop, with print standing in for the light.
3 to 10 and run it againprint("Warning over.") at the bottom with no indentation, and see how many times it printsrange Doesrange(3) makes the loop go through 0, then 1, then 2. It stops before 3range(1, 4) starts at 1 and goes through 1, 2, 3. The stop value is not includedfor holds the current value. Use it inside the block, or ignore it and just count tripsWrite down what this prints before you press Run.
range(1, 4) to range(4) and predict again before runningif Inside a LoopThe question is asked once per trip, about the value the loop handed over.
flash % 3 == 0 is True for 3, 6 and 9: the remainder is what picks out every third one1 is what makes "every third" line up with the remainder0 before the loop, plus one inside the if, ends up holding how many trips took that branchRun it. Which flash numbers are held long, and why those?
range(1, 8) to range(7) and run again. Which flashes are long now, and why did that move?long = 0 before the loop and long = long + 1 inside the if, then print it after the loopRead it before you run it. Count the lines it will print.
for runs all the way through on every trip of the outer oneshort and three long. Check your count against the outputfor and run againwhile: Repeat Until Something ChangesFor when you do not know the count in advance.
while charge < 40: checks the condition before every trip and stops the first time it is FalseFalse, or the loop never endscharge to 50 and see how many trips happenfor ... in range(n) when you know how many times: flash three timeswhile when you stop on a condition, not a count: keep charging until the battery is readyif inside a loop decides each trip on its own. A loop inside a loop repeats a repetition