Lesson 6 of 12
Learn loops with flowchart blocks: Repeat a set number of times, Count with a number each lap, and Repeat While until something changes. Run every one.
About 7 minutes · 4 parts, each with a program to try
Part 1 of 4
Repeat runs the blocks on its body arrow again and again, then carries on down its exit arrow.
Use it when you know how many times: say it 3 times.
3 timesRepeat →
"Hip hip hooray!"back to the top for the next lap
Hip hip hooray!Hip hip hooray!Hip hip hooray!for _ in range(3): print("Hip hip hooray!")Part 2 of 4
Count is a repeat with a number that goes up each time, like i from 1 to 5.
In code this is a for loop.
i from 1 to 5Repeat →
"Lap " + iback to the top for the next lap
Lap 1Lap 2Lap 3Lap 4Lap 5for i in range(1, 6): print("Lap " + str(i))Part 3 of 4
Repeat While keeps going for as long as its condition is true. Use it when you don't know how many times.
Something inside must change the value it checks, or it never stops.
savings = 0weeks = 0savings < 100Repeat →
savings to savings + 30weeks to weeks + 1back to the top for the next lap
"After " + weeks + " weeks you have " + savingsAfter 4 weeks you have 120savings = 0weeks = 0while savings < 100: savings = savings + 30 weeks = weeks + 1print("After " + str(weeks) + " weeks you have " + str(savings))Part 4 of 4
Start a total at 0, and add to it each lap. This is one of the most useful patterns in programming.
total = 0i from 1 to 10Repeat →
total to total + iback to the top for the next lap
"1 + 2 + ... + 10 = " + total1 + 2 + ... + 10 = 55total = 0for i in range(1, 11): total = total + iprint("1 + 2 + ... + 10 = " + str(total))Quick check