All lessons

Loops

8 min · Python

Repeat work without writing it out a hundred times.

A loop repeats code. A for loop with range(n) runs the indented block n times, counting from 0 up to n - 1.

Run this to print the numbers 0, 1, 2:

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: 0 1 2

Loop over a list

A for loop can also walk through the items of a list, handing you one at a time.

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: apple banana cherry

Build up an answer

Loops shine when you accumulate a result: start a variable before the loop, then update it each time around.

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: 60

Your turn

Use a loop to print every number from 1 to 5, one per line.

Your turn

Loading editor...

Ln 1, Col 1Spaces: 4