深度阅读

how to use range in python

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

The range() function in Python generates an immutable sequence of integers. It can be used in a for loop to perform a repetitive task a certain number of times, or to create a list of numbers with a specific pattern. Here are a few examples:

  1. To generate a sequence of integers from 0 to n-1:
for i in range(n):
    print(i)
  1. To generate a sequence of integers from start to end-1:
for i in range(start, end):
    print(i)
  1. To generate a sequence of integers from start to end-1 with a specific step size:
for i in range(start, end, step):
    print(i)

Here’s an example of how to create a list of even numbers between 4 and 12 using the range() function:

even_numbers = list(range(4, 13, 2))
print(even_numbers)

This will output [4, 6, 8, 10, 12], which is the list of even numbers between 4 and 12 with a step size of 2.

相关标签

博客作者

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