gpt4 book ai didi

python - 计数输出

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:10 24 4
gpt4 key购买 nike

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/

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