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