Skip to main content
 首页 » 编程设计

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

2025年05月04日9dyllove98

我的目标是打印接下来的 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 循环似乎是完成这项特定工作的更好工具。