Loops
8 min · Python
Repeat work without writing it out a hundred times.
Enemy 1 of 5
A loop repeats a block of code without you having to write it out by hand over and over. If you ever find yourself copy-pasting the same line with only a small change each time, that's usually a sign a loop belongs there instead.
A for loop with range(n) runs the indented block n times, with a counter variable (here, i) counting from 0 up to — but not including — n. So range(3) produces 0, 1, 2: three values, starting at zero, just like list indexes did in the previous lesson. That off-by-one detail (range(3) stops before 3, not at 3) is worth internalizing now, since it explains a lot of "why is my loop running one time too few/many" bugs later.
Run this to print the numbers 0, 1, 2:
Loading editor...