利用python實(shí)現(xiàn)萬年歷的查詢
今天要用python做一個小功能,那就是實(shí)現(xiàn)萬年歷的查詢。
首先看一下整體感覺

實(shí)現(xiàn)代碼:
def is_leap_year(year): if year/4==0 and year/400 !=0: return True elif year/100 == 0 and year/400 ==0 : return True else: return False
首先判斷是否是閏年,因?yàn)橛?jì)算2月是否有29天有用。
def getMonthDays(year,month): days = 31 #31天居多,設(shè)置為默認(rèn)值 if month == 2 : #2月份要判斷是否是閏年 if is_leap_year(year): days=29 else: days=28; elif month in [4,6,9,11]: #判斷小月,只有30天 days=30 return days
由年和月份獲取指定年月的月份有多少天。
def getTotalDays(year,month): totalDays=0 for i in range(1990,year): #使用range來循環(huán),算出多少年多少天 if is_leap_year(i): #判斷是否是閏年 totalDays += 366 else: totalDays += 365 for i in range(1,month): #使用range循環(huán),算出今年前面幾個月過了多少天 totalDays +=getMonthDays(year,i) return totalDays
獲取1990-01-01離現(xiàn)在有多少天,1990-01-01是星期一,以這個為標(biāo)準(zhǔn)來判斷。
if __name__ == '__main__':
while True:
print "××××××××××python實(shí)現(xiàn)萬年歷××××××××"
year = raw_input("請輸入年份(如:1990):")
month = raw_input("請輸入月份:如:1")
try:
year = int(year)
month = int(month)
if month <1 or month >1:
print "年份或者月份輸入錯誤,請重新輸入!"
continue
except:
print "年份或者月份輸入錯誤,請重新輸入!"
continue
break
print "日\t一\t二\t三\t四\t五\t六"
iCount = 0#計(jì)數(shù)器來判斷是否換行
for i in range(getTotalDays(year,month)%7):
print '\t', #輸出空不換行
iCount+=1
for i in range(1,getMonthDays(year,month)):
print i,
print '\t',
iCount +=1
if iCount%7 == 0 : #計(jì)數(shù)器取余為0,換行
print ''
最后只需要輸入年份和月份,就能把完整的整個月份的日歷打出來。無論是查詢以前的日歷還是查詢未來的日歷,都是可以計(jì)算出來的。
到此這篇關(guān)于利用python實(shí)現(xiàn)萬年歷的查詢的文章就介紹到這了,更多相關(guān)python實(shí)現(xiàn)萬年歷的查詢內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信