日期有效期和闰年检查员

时间:2016-05-22 20:13:40

标签: python python-2.7 if-statement math

我一直在努力寻找缩短或修改此代码的方法,以提高效率并降低复杂性。任何帮助?

我是这个网站的新手,所以我希望得到一个好的回应:D!

a=int(input('Enter the date:'))
b=int(input('Enter the month:'))
c=int(input('Enter the year:'))
if b<=12 and a<=31 and b>0 and a>0:
    if b==2:
       if a>29:
           k=0
       elif a<=29:
           k=1
    elif b==1 or b==3 or b==5 or b==7 or b==8 or b==10 or b==12:
        if b>31:
            k=0
        else:
            k=1
    else:
        if b>30:
            k=0
        else:
            k=1
else:
    k=0

if k==0:
    print 'Invalid Date'

elif k==1:
    if (c%4)==0:
        if (c%100)==0:
            if (c%400)==0:
                t=1
            else:
                t=0
        else:
            t=1

    if t==1:
        print 'It is a leap year and has a valid date'
    elif t==0 :
        if a==29 and b==2:
            print 'It isn\'t a valid date neither a leap year'
        else:
            print 'It is a valid date and a leap year'

3 个答案:

答案 0 :(得分:2)

使用内置模块 -

import datetime
import calendar


def validate_date(year, month, date):
    """Returns True if valid date else False"""
    try:
        datetime.datetime(year, month, date)
        return True
    except ValueError:
        return False

使用calender.isleap(year)检查year是否为闰年。

答案 1 :(得分:1)

如果您想避开内置模块并推送自己的代码,并且将kt更改为逻辑变量,则可以使用

k = (1 <= b <= 12) and (1 <= a <= [31,29,31,30,31,30,31,31,30,31,30,31][b])
t = (c%4 == 0) and (c%100 != 0 or c%400 == 0)

根据他人的建议,您还应该更改变量名称以使其更清晰。请注意,这不会测试变量是否为整数。

答案 2 :(得分:0)

这是检查输入年份是否为闰年的另一种更简单,更有效的方法。

year = int(input("Type a year: ")) 

if year % 4 == 0 and year %100 != 0 or year % 400 == 0:

    print ("\nIs a leap-year")

else:
    print ("\nIs not a leap-year")
相关问题