How to use ‘range’ in Python.

In Python, the range() function is used to generate a sequence of integers. It has three different ways of being used.

  1. range(stop): Generates a sequence of integers from 0 to stop-1.
for i in range(5):
    print(i)
# 输出:0 1 2 3 4
  1. Create a sequence of integers from the starting point to one less than the stopping point.
for i in range(1, 6):
    print(i)
# 输出:1 2 3 4 5
  1. range(start, stop, step): Create a sequence of integers from start to stop-1, with a step size of step.
for i in range(1, 10, 2):
    print(i)
# 输出:1 3 5 7 9

It is important to note that the range() function returns an iterable object that can be used in loops for traversal, or can be converted into a list using the list() function.

bannerAds