1. 程式人生 > 實用技巧 >python之(14)求第幾天

python之(14)求第幾天

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

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

year=int(input("請輸入年份:\n"))
month=int(input("請輸入月份:\n"))
day=int(input("請輸入天數:\n"))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 <month <=12:
    sum=months[month-1]
else:
    print("輸入錯誤!!")
sum 
+=day 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(year,month,day,'是%dth 天.' % sum)

結果是:

C:\Anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pydev\pydevconsole.py" --mode=client --port=58506
import sys; print
('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['C:\\app\\PycharmProjects', 'C:/app/PycharmProjects']) Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.12.0 -- An enhanced Interactive Python. Type '
?' for help. PyDev console: using IPython 7.12.0 Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] on win32 runfile('C:/app/PycharmProjects/tensorflow/test.py', wdir='C:/app/PycharmProjects/tensorflow') 請輸入年份: 2020 請輸入月份: 10 請輸入天數: 20 2020 10 20 是294th 天.