如何确定一年是否是闰年?

Ant*_*ony 43 python python-2.7

我正在尝试制作一个简单的计算器,以确定某一年是否是闰年.

根据定义,闰年可被4整除,但不能被100整除,除非它可以被400整除.

这是我的代码:

def leapyr(n):
    if n%4==0 and n%100!=0:
        if n%400==0:
            print n, " is a leap year."
    elif n%4!=0:
        print n, " is not a leap year."
print leapyr(1900)
Run Code Online (Sandbox Code Playgroud)

当我在Python IDLE中尝试这个时,模块返回None.我很确定我应该得到1900 is a leap year.

小智 142

import calendar
print calendar.isleap(1900)
Run Code Online (Sandbox Code Playgroud)

Python在库模块"calendar"中已经提供了这个功能.


Eug*_*ash 43

作为单线:

def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Run Code Online (Sandbox Code Playgroud)

它类似于Mark的答案,但在第一次测试时短路(注意括号).

正如P. Ortiz在评论中所注意到的那样,标准库的calendar.isleap功能具有相同的实现.

  • +1,无论语言是什么,这都是规范的方式.比照 [calandar.py](https://hg.python.org/cpython/file/3.4/Lib/calendar.py#l97) (4认同)
  • @lifebalance`is`运算符比较对象'*identity*.要比较数字,你应该使用`==`. (4认同)

Sam*_*ann 14

你在n上测试了三个不同的东西:

n % 4
n % 100
n % 400
Run Code Online (Sandbox Code Playgroud)

对于1900年:

1900 % 4 == 0
1900 % 100 == 0
1900 % 400 == 300
Run Code Online (Sandbox Code Playgroud)

所以1900不进入if子句,因为1900 % 100 != 0False

但是1900年也else因为1900 % 4 != 0也没有进入条款False

这意味着执行到达函数的末尾并且没有看到return语句,因此返回None.

这个函数的重写应该有效,并且应该返回FalseTrue适当地传递给它的年份数.(请注意,与其他答案一样,您必须返回一些内容而不是打印它.)

def leapyr(n):
    if n % 400 == 0:
        return True
    if n % 100 == 0:
        return False
    if n % 4 == 0:
        return True
    else:
        return False
print leapyr(1900)
Run Code Online (Sandbox Code Playgroud)

(来自维基百科的算法)

  • +1用于识别逻辑错误.但是,OP的代码不包含`return`语句.修复您在此处指出的错误无济于事. (3认同)

Mar*_*som 9

整个公式可以包含在一个表达式中:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"
Run Code Online (Sandbox Code Playgroud)