Home >Backend Development >Python Tutorial >Python's range() function: generate a sequence of numbers
Python's range() function: generates a sequence of numbers, specific code examples are required
Python is a powerful programming language with many built-in functions for Writing programs is very helpful. One of them is the range() function, which is used to generate a sequence of numbers. This article will introduce the usage of the range() function in detail and illustrate it through specific code examples.
The basic syntax of the range() function is as follows:
range(start, stop, step)
Among them, start represents the starting value (default is 0), stop represents the end value ( not included in the range), step represents the step size in the sequence (default is 1). This means that the sequence of numbers generated by the range() function starts from start, with step as the step size, until stop (exclusive).
The following are several examples of using the range() function:
Generate a sequence of numbers from 0 to 9:
for i in range(10): print(i)
Output results:
0 1 2 3 4 5 6 7 8 9
Generate a sequence of numbers from 2 to 10 with a step of 2:
for i in range(2, 11, 2): print(i)
Output result:
2 4 6 8 10
Generate a decreasing sequence of numbers, from 10 to 1, with a step size of -1:
for i in range(10, 0, -1): print(i)
Output result:
10 9 8 7 6 5 4 3 2 1
Except use range() in the loop function, which can also be used to create a list of numerical sequences. You can use the list() function to convert the return value of range() to a list, as follows:
Convert the return value of range() to a list:
numbers = list(range(5)) print(numbers)
Output result:
[0, 1, 2, 3, 4]
Convert the return value of range() into a list, and specify the starting value and step size:
numbers = list(range(2, 11, 2)) print(numbers)
Output result:
[2, 4, 6, 8, 10]
As shown in the above code example, the range() function can generate a sequence very flexibly, and the start value, end value and step size can be specified as needed. The range() function is often used in a loop to traverse numbers within a certain range, and can also be used to create a list of number sequences.
Although this article only briefly introduces the range() function and gives some code examples, its application has a wide range of possibilities. By using the range() function properly, we can write Python programs more efficiently.
To summarize, the range() function is a very practical and commonly used function in Python. It can be used to generate a sequence of numbers, making it easy to loop through or create a list. For beginners, mastering the usage of the range() function is an important basic knowledge point. I hope the introduction in this article can help readers better understand and use the range() function.
The above is the detailed content of Python's range() function: generate a sequence of numbers. For more information, please follow other related articles on the PHP Chinese website!