Python练习题-004

题目-004:输入某年某月某日,判断这一天是这一年的第几天?

  • 分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
    #    这个是否要清楚每个月各是多少天,其中31天的是1、3、5、7、8、10、12月,30天的是4、6、9、11月,2月闰年是29天,平年是28天
    #    闰年/平年判定:年份数(末两位不是00)能被4整除的是闰年(如1988、1996)、年份数(末两位数是00的)能被400整除是也是闰年(如2000年,4000年).其余为平年.
  • Python版本:Python 3.6.5

    代码1:基本代码,根据输入输出判断内容

#! usr/bin/python
#! -*- coding: utf-8 -*-
def getday():
    year = int(input("1.please input year:"))
    month = int(input("2.please input month:"))
    day = int(input("3.please input day:"))
    count_arr = [0,31,59,90,120,151,181,212,243,273,304,334]
    count = count_arr[month-1] + day
    if  (month > 2) and (((year%100 != 0) and (year%4 ==0)) or ((year%100 == 0) and (year%400) == 0)):
        count = count + 1
    print("%d-%d-%d is the %dth day of the year"%(year,month,day,count))

while True:
    getday()
1.please input year:2000
2.please input month:3
3.please input day:1
2000-3-1 is the 61th day of the year
1.please input year:1998
2.please input month:3
3.please input day:1
1998-3-1 is the 60th day of the year

    代码2:根据代码1,做一些优化,主要是增加了月份和日期的判断,如果月份和日期输入不正确,会进行错误提示

#! usr/bin/python
#! -*- coding: utf-8 -*-
def getday():
    year = int(input("1.please input year:"))
    month = int(input("2.please input month:"))
    day = int(input("3.please input day:"))
    month_check,day_check = True,True
    flag = False
    count_arr = [0,31,59,90,120,151,181,212,243,273,304,334]
    day_arr = [31,28,31,30,31,30,31,31,30,31,30,31]
    if ((year%100 != 0) and (year%4 ==0)) or ((year%100 == 0) and (year%400) == 0):
        day_arr[1] = 29
        for i in range(2,12):
            count_arr[i]+=1
        flag = True
    if month not in range(1,13):
        print("month check error.please input the month between 1 and 12")
        month_check = False
    elif day not in range(1, day_arr[month - 1] + 1):
            print("day check error. month %d not have the day" % month)
            day_check = False
    if [month_check,day_check] == [True,True]:
        count = count_arr[month-1] + day
        print("%d-%d-%d is the %dth day of the year"%(year,month,day,count))

while True:
    getday()
1.please input year:2000
2.please input month:00
3.please input day:00
month check error.please input the month between 1 and 12
1.please input year:2000
2.please input month:13
3.please input day:32
month check error.please input the month between 1 and 12
1.please input year:2000
2.please input month:2
3.please input day:29
2000-2-29 is the 60th day of the year
1.please input year:1998
2.please input month:2
3.please input day:29
day check error. month 2 not have the day


你可能感兴趣的:(python)