gpt4 book ai didi

python - 在for循环中添加一个计数器

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:47 25 4
gpt4 key购买 nike

我的目标是打印接下来的 20 个闰年。

到目前为止没有什么特别的。

我的问题是:

how to replace the while with a for

def loop_year(year):
x = 0
while x < 20:
if year % 4 != 0 and year % 400 != 0:
year +=1
##print("%s is a common year") %(year)
elif year % 100 != 0:
year +=1
print("%s is a leap year") % (year)
x += 1


loop_year(2020)

最佳答案

如果您要问的是在遍历集合时是否有索引,这就是 enumerate 的用途。

而不是做:

index = -1
for element in collection:
index += 1
print("{element} is the {n}th element of collection", element=element, n=index)

你可以这样写:

for index, element in enumerate(collection):
print("{element} is the {n}th element of collection", element=element, n=index)

编辑

回答最初的问题,你是在问这样的事情吗?

from itertools import count

def loop_year(year):
leap_year_count = 0
for year in count(year):
if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
leap_year_count += 1
print("%s is a leap year") % (year)
if leap_year_count == 20:
break

loop_year(2020)

也就是说,我同意 ArtOfCode 的观点,即 while 循环似乎是完成这项特定工作的更好工具。

关于python - 在for循环中添加一个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36593590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com