def leap_years(start, end):
if start < 1500 or start > 2100:
return
if end < 1500 or end > 2100:
return
i = 0
for i in range(start, end + 1):
if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0):
print(i)
print(leap_years(1998, 2008))
我想输出 3 而不是 2000,2004,2008
最佳答案
您需要添加一个计数器:
def leap_years(start, end):
if start < 1500 or start > 2100:
return 0
if end < 1500 or end > 2100:
return 0
i, count = 0, 0
for i in range(start, end + 1):
if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0):
count += 1
return count
print(leap_years(1998, 2008))
输出
3
在上面的代码中,计数器 是变量count
,每次满足闰年条件时,它都会递增1
。请注意,现在函数 leap_years
返回闰年数。
关于python - 计数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233238/