代碼如下:#!/usr/bin/env python2
#-*- coding:utf-8 -*-
__author__ = 'jalright'
"""
使用python實現萬年歷
"""
def is_leap_year(year):
"""
判斷是否是閏年,返回boolean值
"""
if year/4==0 and year/400 !=0:
return True
elif year/100 == 0 and year/400 ==0 :
return True
else:
return False
def getMonthDays(year,month):
"""
獲取指定年月的月份有多少天
"""
days = 31 #31天居多,設置為默認值
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):
"""
獲取1990-01-01離現在有多少天,1990-01-01是星期一,以這個為標準來判斷星期
"""
totalDays=0
for i in range(1990,year): #使用range來循環,算出多少年多少天
if is_leap_year(i): #判斷是否是閏年
totalDays += 366
else:
totalDays += 365
for i in range(1,month): #使用range循環,算出今年前面幾個月過了多少天
totalDays +=getMonthDays(year,i)
return totalDays
if __name__ == '__main__':
while True: #循環判斷是否輸入錯誤的格式
print "××××××××××python實現萬年歷××××××××"
year = raw_input("請輸入年份(如:1990):")
month = raw_input("請輸入月份:如:1")
try: #捕捉輸入異常格式和月份的正確
新聞熱點
疑難解答