在 Python 中从 1 开始一个 for 循环
Vaibhhav Khetarpal
2023年1月30日
Python
Python Loop
-
在 Python 中使用简单的用户定义函数的索引 1 处启动
for循环 -
在 Python 中使用嵌套的
for循环的索引 1 处启动for循环 -
在 Python 中使用
n+1代替range()函数中的n的索引 1 处启动for循环
与任何其他编程语言类似,for 循环的起始索引默认为 0。但是,可以操作迭代语句的范围,并且可以将循环的起始索引更改为 1。
本教程将介绍如何在 Python 中的索引 1 处启动 for 循环。
在 Python 中使用简单的用户定义函数的索引 1 处启动 for 循环
我们可以很容易地自己创建一个函数来实现这个方法。然后可以在 for 循环中使用创建的函数而不是 range() 函数。
以下代码使用一个简单的用户定义函数在 Python 中的索引 1 处启动 for 循环。
def nums(first_number, last_number, step=1):
return range(first_number, last_number + 1, step)
for i in nums(1, 5):
print(i)
上面的代码提供了以下输出:
1
2
3
4
5
在 Python 中使用嵌套的 for 循环的索引 1 处启动 for 循环
在 Python 中的索引 1 处启动 for 循环的另一种方法是使用 for 循环两次。这与 range() 函数一起使用。
以下代码使用嵌套的 for 循环在 Python 中的索引 1 处启动 for 循环。
for x in (n + 1 for n in range(5)):
print(x)
上面的代码提供了以下输出:
1
2
3
4
5
在 Python 中使用 n+1 代替 range() 函数中的 n 的索引 1 处启动 for 循环
该方法可以通过分别使用 start 值作为 1 和停止值作为 n+1 而不是默认值 0 和 n 来实现。
以下代码使用 n+1 代替 range() 函数中的 n,以在 Python 中的索引 1 处启动 for 循环。
n = 5
for x in range(1, n + 1):
print(x)
上面的代码提供了以下输出:
1
2
3
4
5
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
LinkedIn