Features of the for
loop
How to change the step in the sequence of values and not start from scratch? The
range()
function, by default, builds a sequence in which each next number is 1 greater than the previous one. You can use the
range
function in another entry.
The general form of the function entry is as follows:
range([start], stop[, step])
start
: start number of the sequence.
stop
: generates numbers up to but not including the given number.
step
: the difference between each number in the sequence (step)
You have to remember!
- All parameters must be integers:
- Each of the parameters can be either positive or negative.
range()
(and Python in general) is based on index 0. This means that the index list starts at 0, not 1. The last integer generated by the function range()
depends on stop
but will not include it. For example, range(0, 5)
generates the integers 0, 1, 2, 3, 4, not including 5.
Example 1
for i in range (10, 0, -1):
print(i*i)
The program displays the squares of natural numbers from 10 to 1 in descending order
- 10: The first number in the sequence.
- 0: end number of the sequence (not including this number).
- -1: step
Example 2
for i in range (0, 101, 5):
print(i)
The program displays all numbers from 0 to 100 in increments of 5
- 0: The first number in the sequence.
- 101: end number of the sequence (not including this number).
- 5: step