Counting with range()

Loops, lesson 3 of 5

🔁 Loops, lesson 3 of 5

Counting with range()

Loop a set number of times and count up, down or in steps.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

To repeat something a fixed number of times, loop over range(). range(5) produces 0, 1, 2, 3, 4: it starts at 0 and stops before 5.

Example

Five laps

Change it to range(1, 6) so the laps are numbered 1 to 5.

range takes up to three numbers:

  • range(stop): 0 up to stop - 1
  • range(start, stop): start up to stop - 1
  • range(start, stop, step): jump by step each time (a negative step counts down)

Peek at the numbers with list(range(...)).

Example

Peek inside range

Try range(10, 0, -1). Why doesn't 0 appear?

Example

Times table

Change n to practise another table.

Quiz

What does this print?

Example

Temperature table

The step of 20 gives 0, 20, … 100. Try a step of 10.

Quiz

What does this print?

Exercise

Add up the evens

Use a for loop with range to add up every even number from 2 to 100 inclusive (2 + 4 + … + 100). Store the result in total.