对永远重复的循环的第一个实例执行操作



现在我有一个脚本,它意味着永远循环。但是,我想在第一圈做一些不同的事情,如下所示:

import math
for i in range(0,math.inf):
if i == 0:
print("I'm gonna start the first lap")
print('this is one lap')
"I'm gonna start the first lap"
'this is a lap'
'this is a lap'

请注意,此代码不起作用,因为 math.inf 是浮点数,而不是整数。这篇文章说,在Python中,没有办法将无穷大表示为整数。

在这种情况下,使用while True:可能是有意义的,但是有没有办法让函数为第一次(或第 x 次(重复打印不同的东西?

print("I'm gonna start the first lap")
while True:
print('this is one lap')

把它放在循环之前。

如果您希望在保留计数器的同时使用无限for循环,则可以使用itertools.count

from itertools import count
for i in count():
if i == 0:
print("I'm gonna start the first lap")
print('This is one lap')
# break

显而易见的方法是将第一次迭代放在循环之前:

print("I'm gonna start the first lap")
while True:
print('this is one lap')

但是,此示例未指定问题的其余部分。

只需计算圈数并将当前圈数与所需圈数进行比较即可。对于第 x 次重复:

counter = 0
while True:
if counter == xth:
print("This is the xth lap")
print('this is one lap')
counter += 1

最新更新