← Python course

Lesson 04

Repeating things

Loops — making the computer do the boring repetition.

Computers are good at one thing above all: doing the same thing over and over without complaining. That's a loop.

Loading editor…

range(5) produces the numbers 0, 1, 2, 3, 4 — five of them, starting at zero. for i in range(5): means "for each of those numbers, call it i, and run the indented block below." It runs five times, once per number.

Python counts from 0 almost everywhere. It feels strange at first, then becomes automatic.

You can loop over more than numbers — directly over a list of things:

Loading editor…

There's a second kind of loop — while — which keeps going as long as a condition stays true, instead of a fixed number of times:

Loading editor…

Be careful with while — if the condition never becomes false, it runs forever. That count = count + 1 line is what eventually stops it. Forgetting it is the most common beginner mistake (everyone does it once).

Your turn

Print the 5 times table, from 1×5 up to 10×5, using a for loop.

Loading editor…

Next lesson: lists — storing more than one thing under a single name.