Generating Numbers with Steps Using For in Python

To output numbers at a certain step, you need to pass a third parameter to the range function.

Example

Let's print numbers from 1 to 9 with a step of 2:

pythonfor num in range(1, 10, 2):
  print(num)

The result of the executed code:

python1
3
5
7
9

Example

If you set the step with a negative number, the numbers will be output in reverse order. Let's swap the values ​​in the first and second parameters of the function for clarity:

pythonfor num in range(10, 1, -1):
  print(num)

After running the code, the numbers output will be from 10 to 2, since the number in the second parameter is not included in the range:

python10
9
8
7
6
5
4
3
2

Practical tasks

Задание 1

Print to the console even numbers from 1 to 100.

Задание 2

Print numbers from -10 to 10 to the console.

Задание 3

Write the code to get the following numbers:

python20
17
14
11
8
5
2