# 打印萬年歷的條件:
# 1)閏年條件:能被4整除且不能被100整除,或者能被400整除
# 2)1900年1月1日 是周一
# 注意:這個題不要調用系統函數或庫。
# 代碼注意封裝,一個函數實現一個功能。注意分析實現打印萬年歷的功能步驟:
# 判斷閏年;
# 判斷當月有多少天;
# 這個月的1號是從周幾開始的;
# 格式化打印日歷。
#從鍵盤輸入年份 月份
def inputYearAndMonts():
year = input("輸入年份")
month = input("輸入月份")
year = int(year)
month = int(month)
orignalDay(year,moths=month)
#輸入年份 月份 、得到這個月第一天是星期幾
def orignalDay(years:int,moths:int):
temp = abs(years - 1990)
erpetualNumber = 0
beginYear = 0
endYear = 0
if years-1990<0:
beginYear = years
endYear = 1990
else:
beginYear = 1990
endYear = years
for i in range(beginYear,endYear):
if (i%100 != 0) and (i%4 == 0):
erpetualNumber = erpetualNumber+1
if (i%100 == 0) and (i%400 == 0):
erpetualNumber = erpetualNumber+1
totalDays = (temp - erpetualNumber)*365 + erpetualNumber*366
isLeapYear = False
leapYearMonths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
nomalYearMoths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if years % 4 == 0 and years % 100 != 0:
isLeapYear = True
for i in range(0,(moths-1)):#注意這里是0不是1
if isLeapYear==True:
totalDays = totalDays+leapYearMonths[i]
else:
totalDays = totalDays + nomalYearMoths[i]
#上面得到的是 上個月的最后一天。 是第多少天
#則這個月的第一天 在上面的基礎上加一
totalDays = totalDays+1
print("天數:%d"%totalDays)
beginWeek = 0
if years>=1990:
beginWeek = totalDays%7#月初第一天是星期幾
#print("這個月的第一天是:星期%d"%(totalDays%7))
else:
beginWeek = 7-totalDays%7#月初第一天是星期幾
#print("這個月的第一天是:星期%d" % (7 -totalDays % 7))
currentMoths = 0
if isLeapYear:
currentMoths = leapYearMonths[moths]
else:
currentMoths = nomalYearMoths[moths]
#打印萬年歷
print("下面是%d年%d月" %(years,moths))
printPerpetualCalendar(currentMoths,beginWeek)
#打印萬年歷
#傳入 當月月份 和 第一天星期幾
def printPerpetualCalendar(months:int, begin:int):
#先輸出萬年歷的 頭部
week = ["日","一","二","三","四","五","六"]
print("日\t一\t二\t三\t四\t五\t六")
#循環輸出每一月的具體日期
for i in range(1,months+begin+1):
if i<=begin:#當這個月第一天不是星期一時,輸出占位符
print(" \t",end="")
continue
print(i-begin,end="")#end=""可以不輸出換行。
print("\t", end="")
if i%7==0:#七天一換行
print()#只是為了換行
#printPerpetualCalendar()
#開始運行
inputYearAndMonts()
最后的結果圖:
捕獲.PNG