How do you use the range function in Python?

The range() function in Python is used to generate a sequence of integers, commonly used in for loops.

There are three ways to use the range() function.

  1. generate a sequence of numbers up to a specified point
  2. Cease-1
  3. cease
for i in range(5):
    print(i)
# 输出:0 1 2 3 4
  1. Generate a sequence of numbers starting from a specified start value and ending before a specified stop value.
  2. begin
  3. cease-1
  4. Cease.
for i in range(2, 6):
    print(i)
# 输出:2 3 4 5
  1. Determine a sequence of numbers using a specified starting point, ending point, and interval distance.
  2. commence
  3. Cease-1
  4. cease
  5. step
for i in range(1, 10, 2):
    print(i)
# 输出:1 3 5 7 9

It’s important to note that the range() function returns an iterable object, not an actual list. If you need to obtain a list, you can use the list() function to convert the iterable object into a list.

nums = list(range(1, 4))
print(nums)
# 输出:[1, 2, 3]

Additionally, the parameters for the range() function can be any integer data type, including negative numbers. For example, range(5, -5, -2) will generate a decreasing sequence of integers, from 5 to -4 (excluding -5) with a decrease of 2 each time.

bannerAds