我是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...
main()的
答案 0 :(得分: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()