天天看點

python每日一題_Python:每日一題004

題目:

輸入某年某月某日,判斷這一天是這一年的第幾天?

程式分析:

以3月5日為例,應該先把前兩個月的加起來,然後再加上5天即本年的第幾天,特殊情況,閏年且輸入月份大于2時需考慮多加一天

個人的思路及代碼:

month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 ]

while True:

year = input("請輸入年份:").strip()

month = input("請輸入月:").strip()

day = input("請輸入天:").strip()

if not year.isdigit() or not month.isdigit() or not day.isdigit():

print("您的輸入有誤請重新輸入!")

continue

else:

year = int(year)

month = int(month)

day = int(day)

if month > 12 or day > 31 or day < 0:

print("您的輸入有誤請重新輸入!")

continue

if (year % 4 == 0 and year %100 != 0) or year % 400 == 0:

if month > 2:

index_day = sum(month_days[:month-1]) + day + 1

else:

index_day = sum(month_days[:month-1]) + day

else:

index_day = sum(month_days[:month-1]) + day

print("這一天是一年中的第%s天" % index_day)

分析:這裡考慮了大部分輸入異常的情況,但是還是有輸入錯誤但是不能檢測出來的情況,比如輸入4月31日不能檢測出日期不正确。

再次修改增加判斷條件,檢測大小月和2月的問題

month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 ]

while True:

year = input("請輸入年份:").strip()

month = input("請輸入月:").strip()

day = input("請輸入天:").strip()

if not year.isdigit() or not month.isdigit() or not day.isdigit():

print("您的輸入有誤請重新輸入!")

continue

else:

year = int(year)

month = int(month)

day = int(day)

if month > 12 or day > 31 or day < 0:

print("您的輸入有誤請重新輸入!")

continue

elif month in [4,6,9,11] and day > 30 or month == 2 and day > 29:

print("您的輸入有誤請重新輸入!")

continue

if (year % 4 == 0 and year %100 != 0) or year % 400 == 0:

if month > 2:

index_day = sum(month_days[:month-1]) + day + 1

else:

index_day = sum(month_days[:month-1]) + day

else:

if month == 2 and day > 28:

print("您的輸入有誤請重新輸入!")

continue

index_day = sum(month_days[:month-1]) + day

print("這一天是一年中的第%s天" % index_day)

其他參考解答:

參考1

def leapyear(n):

return True if (n % 4 == 0 and n % 100 != 0) or n % 400 == 0 else False

days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ]

year, month, day = [int(x) for x in input('input year/month/day: ').split('/')]

#直接用清單解析式擷取三個資料

day2 = sum(days[:month - 1]) + day

if leapyear(year) and month > 2:

day2 += 1

print(day2)

參考2

import datetime

x=int(input("請輸入年份xxxx:"))

y=int(input("請輸入月份xx:"))

z=int(input("請輸入日xx:"))

n1=datetime.date(x,y,z)

n2=datetime.date(x,1,1)

n3=n1-n2

n3=int(n3.days)+1

print("這是這一年的第%s天"%n3)

分析:這裡用datetime子產品避免了輸入日期不正确的情況,如果輸入不正确則直接報錯。

(本文編号004,首發于2018年9月14日,修改于2018年9月15日)