Usage of the for Loop
Learn how to use the for loop in a Python program.
We'll cover the following
The for
loop can be used in these two situations:
- Repeating a set of statements a finite number of times.
- Iterating through a string, list, tuple, set, or dictionary.
First usage of the for
loop
To repeat a set of statements a finite number of times, a built-in range()
function is used.
The range()
function generates a sequence of integers. For example:
range(10)
: It generates numbers from0
to9
.range(10, 20)
: It generates numbers from10
to19
.range(10, 20, 2)
: It generates numbers from10
to19
in increments of2
.range(20, 10, -3)
: It generates numbers from20
to9
in decrements of3
.
Note: The
range()
function cannot generate a sequence of floats.
Generally, range(start, stop, step)
produces a sequence of integers from start
(inclusive) to stop
(exclusive) by step
.
The list of numbers generated using range()
can be iterated using the for
loop.
Get hands-on with 1400+ tech skills courses.