Usage of the for Loop

Learn how to use the for loop in a Python program.

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 from 0 to 9.
  • range(10, 20): It generates numbers from 10 to 19.
  • range(10, 20, 2): It generates numbers from 10 to 19 in increments of 2.
  • range(20, 10, -3): It generates numbers from 20 to 9 in decrements of 3.

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 1200+ tech skills courses.