1

我是 Python 的一个真正的菜鸟,我正在编写一个程序来输出给定日期是否是有效的日历日期。我确信有更优雅的方式来做到这一点。

在这一点上,我试图弄清楚如何添加一个变量来创建一个while循环,如果它是闰年或不是闰年,它将处理日期。不过,所有建议都非常受欢迎。

我已将代码尝试的问题区域放在 <> 中。这是我到目前为止的代码:

def main():
print("This program tests the validity of a given date")

date = (input("Please enter a date (mm/dd/yyyy): "))
month, day, year = date.split("/")
month = int(month)
day = int(day)
year = int(year)
Mylist31 = [1, 3, 5, 7, 8, 10, 12]
Mylist30 = [4, 6, 9, 11]

#Calculates whether input year is a leap year or not
if year >= 100 and year % 4 == 0 and year % 400 == 0:
    <it is a leap year>
elif year >= 0 and year <100 and year % 4 == 0:
    <it is a leap year>
else: 
    <it is not leapyear>


while <it is a leapyear>:
    if month in Mylist31 and day in range(1, 32):
        print("Valid date")
    elif month in Mylist30 and day in range(1,31):
        print("Valid date")
    elif month == 2 and day in range(1,30):
        print("Valid date")
    else:
        print("Not a Valid date")  
while <it is not a leapyear>:
etc...

主要的()

4

1 回答 1

1

我已经稍微完成了你的代码。希望从那里你可以继续改进它,朝着你想要的方向发展。

def main():
    print("This program tests the validity of a given date")

    date = (raw_input("Please enter a date (mm/dd/yyyy): "))
    month, day, year = date.split("/")
    month = int(month)
    day = int(day)
    year = int(year)
    Mylist31 = [1, 3, 5, 7, 8, 10, 12]
    Mylist30 = [4, 6, 9, 11]

    ##Calculates whether input year is a leap year or not
    if year >= 100 and year % 4 == 0 and year % 400 == 0:
        is_leap_year = True
    elif year >= 0 and year <100 and year % 4 == 0:
        is_leap_year = True
    else:
        is_leap_year = False

    if is_leap_year:
        if month in Mylist31 and day in range(1, 32):
            print("Valid date")
        elif month in Mylist30 and day in range(1,31):
            print("Valid date")
        elif month == 2 and day in range(1,30):
            print("Valid date")
        else:
            print("Not a Valid date")
    else:
        #TODO: validate non-leap-year date
        pass

main()
于 2013-03-21T10:21:53.090 回答