Beginner friendly ยท 6 minute read
Loops in three steps
Computers are wonderfully patient. Ask one to do something a thousand times and it will not sigh once. In this post we look at loops, the tool that makes this possible, and we build each idea with blocks while Python writes itself next to them.
1 Repeat n times
The simplest loop just says do this a few times. Below, a single print block
sits inside a repeat block, so the greeting is printed three times. The Python on the
right uses range(3), which counts off three rounds. The underscore is the
usual Python name for a counter we never look at.
Try it: change the 3 to a 10, or drag a second print block from the row of blocks into the loop and watch the Python grow a line. Then press Run to see what the program prints now.
2 Count with a variable
Often we want to know which round we are in. A counting loop gives each round
a number and keeps it in a variable, here called i. Printing
i inside the loop shows the numbers 1 to 5.
Notice the + 1 in the Python version: range stops just
before its second number, so counting up to 5 means asking for a range that ends at 6.
The blocks hide this detail; the text shows it.
3 Repeat while a condition holds
Sometimes we do not know in advance how many rounds we need. A while loop keeps going
as long as a question is answered with yes. Here i starts at 90 and
goes up by one in every round. The loop stops once i is no longer
below 100, so the output ends at 99.
Can you make it count in steps of 2, or stop at 95? Change the blocks, guess the output, then press Run. Careful: a loop whose condition never becomes false would run forever, which is the classic loop mistake. This page stops such a loop after a thousand rounds and tells you so.
Where to go next
These three shapes cover most loops you will ever write. Every editor on this page is the same small web component, placed between paragraphs like an image. The same tag works in a blog, a wiki or a course page: pick the blocks with an attribute and the editor does the rest.