深度阅读

How to use the range function in a loop in Python?

作者
作者
2023年08月22日
更新时间
8.14 分钟
阅读时间
0
阅读量

To use the range() function in a loop in Python, you can simply use the for loop syntax and specify the range() function as the list of values to iterate over. Here’s an example:

for i in range(5):
    print(i)

This will loop through the values 0, 1, 2, 3, and 4, and print each of them on a separate line.

You can also specify a starting value for the range, as well as a range increment. For example:

for i in range(1, 10, 2):
    print(i)

This will loop through the values 1, 3, 5, 7, and 9, and print each of them on a separate line.

Note that the range function returns a range object in Python 3, which is an iterable sequence of numbers. If you want to get a list of the values, you can use the list() function to convert the range object to a list.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。