输入某年某月某日,判断这一天是这一年的第几天。(格式 如:19870604)
from builtins import len
leap_year={'01':31,'02':29,'03':31,'04':30,'05':31,'06':30,
'07':31,'08':31,'09':30,'10':31,'11':30,'12':31} #闰年每月最大天数
comm_year={'01':31,'02':28,'03':31,'04':30,'05':31,'06':30,
'07':31,'08':31,'09':30,'10':31,'11':30,'12':31} #平年每月最大天数
while True:
num = input('请输入日期,格式如19540105:')
if num.isdigit() and len(num)==8 :
pass
else :
print('格式错误,请重新输入')
continue
year_num = int(num[:4])
month_num = num[4:6]
day_num = int(num[6:])
if (int(month_num)>12) or (int(month_num)<=0): #月份错误时,重新输入,'01'字符串转换为整数时,会舍弃0,无法遍历字典
print('月份输入错误,请重新输入。')
continue
days=0 #定义天数
if ((year_num%100==0) and (year_num%400 == 0)) or ((year_num%100 !=0) and (year_num%4 == 0)): #如果是闰年
if (day_num > leap_year[month_num]) or (day_num <= 0): #日期错误时重新输入
print('此月份中没有这一天,请重新输入。')
continue
for i in leap_year.keys(): #遍历月份
if int(i) < int(month_num):
days = days + leap_year[i]
elif int(i)==int(month_num):
days = days + day_num
else: #如果是平年
if (day_num > comm_year[month_num]) or (day_num <= 0): #日期错误时重新输入
print('此月份中没有这一天,请重新输入。')
continue
for i in comm_year.keys(): #遍历月份
if int(i) < int(month_num):
days = days + comm_year[i]
elif int(i)==int(month_num):
days = days + day_num
print('这一天是今年的第 %d 天' %days)