python - 计数输出

标签 python python-3.x

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/

相关文章:

python - 查找中间有一个小写字母的大写字母

python - 如何从 csv 中读取字节对象?

python - 捕获所有 * 前面没有 < 的组

python - 对 int 文字的属性访问

python - 如何获得整数作为立方根的结果?

python - 让 Selenium 驱动程序等到元素样式属性发生变化

Python dateutil.rrule 非常慢

Django 计算组内的百分比

python - 在 pypi 包索引上查找包版本的优雅方法是什么?

python - 需要来自 __future__ 的 print() 的 Python 3.4 版本