今天做的一个练习,题目:输入某年某月某日,判断这一天是这一年的第几天?

第一种方式:

程序分析: 先确定确定平年每月天数,再进行平闰年的判断,如果是闰年,二月份要多加一天

将每月的天数进行相加,就可得到结果

#输入某年某月某日,判断这一天是这一年的第几天?

year=int(input('请输入年份:'))
mouth=int(input('请输入月份:'))
day=int(input('请输入日期:'))
mouths=[0,31,28,31,30,31,30,31,31,30,31,30,31]
if year%400==0 or year%4==0:
    mouths[3]=mouths[3]+1

if 0<mouth<=12:
    days=0

    for item in range(mouth):
        sum=mouths[item]
        days=days+sum

    day_s=days+day
    print(f'今天是今年的第{day_s}天')
else:
    print('输入日期超出范围')

第二种方式:

程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年 的第几天,特殊情况,闰年且输入月份大于 3 时需考虑多加一天

#输入某年某月某日,判断这一天是这一年的第几天?

year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
day = int(input('请输入日期:'))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 <= month <= 12:
    sum = months[month -1]
    sum+=day
else:
    print ('您输入的日期超出范围!!')

leap = 0
if (year % 400 == 0) or ((year %4==0) and (year % 100 !=0)):
    leap=1
if (leap == 1) and (month > 2):
    sum += 1
print ('今天是今年的第%s天.' % sum)

今日目标完成,希望对广大python初学者有帮助。共同进步。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐