In Python, the range() function is used to generate a sequence of numbers. It can be used in a for loop to iterate over a sequence of numbers.

The general syntax of the range() function is as follows:

range(start, stop, step)
  • start (optional): The starting number of the sequence. Default is 0.
  • stop (required): The number that the sequence stops before.
  • step (optional): The difference between each number in the sequence. Default is 1.

Here are a few examples of using range() in a for loop:

Example 1: Iterate from 0 to 4 (exclusive) with a step of 1

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

Output:

0
1
2
3
4

Example 2: Iterate from 1 to 10 (exclusive) with a step of 2

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

Output:

1
3
5
7
9

Example 3: Iterate from 10 to 1 (exclusive) with a step of -1

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

Output:

10
9
8
7
6
5
4
3
2

Note that the stop parameter is exclusive, meaning that the loop will not include the number specified as stop

python3 for range

原文地址: https://www.cveoy.top/t/topic/h8FN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录