今天的Python题目是:输入某年某月某日,判断这一天是这一年的第几天?这个题目很有意思,假如输入【2019年1月1日】,会反馈给我该天是2019年的第一天。
我们来分析一下:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
先输入年月日:
year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n'))
定义一个months列表,用于表示该月之前月的日数:
months = [0,31,59,90,120,151,181,212,243,273,304,334]
我们判断输入的月份是否正确输入,如果正确输入,我们先求出在该月之前的日数,如果输入错误,则打印警告信息:
if 0 <= month <= 12: s= months[month - 1] else: print('data error')
我们将计算得到的日数和输入的日数相加得到天数的初值:
s= s+ day
接下来我们需要判断是否是润年,如果是闰年且输入月份大于3时需考虑多加一天:
leap = 0 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1 if (leap == 1) and (month > 2): s+= 1
完整代码如下:
year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n')) s = 0 months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] if 0 <= month <= 12: s = months[month - 1] else: print('data error') s += day leap = 0 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1 if (leap == 1) and (month > 2): s += 1 print('it is the %dth day.' % s)