🔁 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.
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(...)).
Which numbers does range() give?
range(5): start defaults to 0 and it stops before 5: 0, 1, 2, 3, 4. That's 5 numbers.
Peek inside range
Try range(10, 0, -1). Why doesn't 0 appear?
Times table
Change n to practise another table.
What does this print?
Temperature table
The step of 20 gives 0, 20, … 100. Try a step of 10.
What does this print?
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.