🔁 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 tostop - 1range(start, stop):startup tostop - 1range(start, stop, step): jump bystepeach 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?
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1, 0]
[4, 3, 2, 1, 0]
[]
Example
Temperature table
The step of 20 gives 0, 20, … 100. Try a step of 10.
Quiz
What does this print?
2 5 8 11
2 5 8
3 6 9
2 5 8 11 14
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.