⊗pyPmLpNSG 157 of 208 menu

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:

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

The result of the executed code:

1 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:

for 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:

10 9 8 7 6 5 4 3 2

Practical tasks

Print to the console even numbers from 1 to 100.

Print numbers from -10 to 10 to the console.

Write the code to get the following numbers:

20 17 14 11 8 5 2
byenru