Python Arena
Step 3 of 5

Counting with range

Often you want to repeat something a given number of times, or go through numbers in order. The function range gives the numbers, and for goes through them. With one argument, range(n) gives the numbers from 0 to n - 1:

for i in range(4):
    print(i)
Output
0
1
2
3

That's 4 numbers, starting from 0: range(4) stops just before 4. So for i in range(4): repeats its block 4 times, which is often all you need.

Start, end and step

With two arguments, range(start, end) starts from start instead of 0. The end is still left out:

for number in range(1, 6):
    print(number, "squared is", number * number)
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

To go up to 5, the end must be 6. Forgetting that is the most common range mistake: the loop stops one number too early.

A third argument is the step, how much the number changes each time:

for year in range(2000, 2025, 8):
    print(year)
Output
2000
2008
2016
2024

The step can also be negative, which counts down. Then the start is the greater number, and the end (left out again) is the smaller one:

for i in range(5, 0, -1):
    print(i)
print("Liftoff!")
Output
5
4
3
2
1
Liftoff!

Compare this with the while loop that would do the same: a counter, a condition and a -= 1. With range, all three are in one line.

The variable of the loop can be used like any other variable. Here a function uses it to build a line of numbers:

def number_line(n: int) -> str:
    line = ""
    for i in range(1, n + 1):
        line += str(i) + " "
    return line


print(number_line(5))
Output
1 2 3 4 5

Your task

Challenge 1 of 3

Fill in the blanks so the loop prints the even numbers from 2 to 10:

2
4
6
8
10

Challenge 2

Write a program that asks for a whole number and counts down from it to 1, one number per line, and then prints Liftoff!. Use for and range:

Count down from: 3
3
2
1
Liftoff!

Challenge 3

Write the function sum_of_squares(n: int) -> int, which returns the sum 1 · 1 + 2 · 2 + ... + n · n. For example, sum_of_squares(3) returns 14, because 1 + 4 + 9 is 14.