1. 程式人生 > >python打印萬年歷

python打印萬年歷

萬年 效果圖 格式化輸出 sda bsp 年份 range mage --

1.輸入年份,輸入月份

2.格式化輸出本月的日歷

3.思路輸入年,月,打印對應年月的日歷。

  3.1,首先1970年是Unix系統誕生的時間,1970年成為Unix的元年,1970年1月1號是星期四,現在大多的手機的日歷功能只能顯示到1970年1月1日這一天;

  3.2,要想打印某年某月的日歷,首先應該計算出這個月1號是星期幾?

    解決1號是星期幾?
    3.2.1: 先計算出年天數,即截至這一年1月1號的天數,用for循環,從1970年開始,閏年 + 366,平年 + 365;
    3.2.2: 計算出月天數,即截至本月1號的天數,用for循環,從1月份開始,算出月天數;
    3.2.3: 用年天數加月天數,求得本月1號距離1970年1月1號的總天數,用總天數來判斷本月1號是星期幾;

  3.3, 判斷本月的總天數;

  3.4, 打印日歷;

4.運行效果圖1:

技術分享

運行效果圖2:

技術分享

5.代碼實現

# 定義判斷閏年的函數,是閏年返回True,不是返回False
def isLeapYear(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False


# 定義計算從1970年到截止到今年的 年天數的函數
def yearsDays(year):
    totalDays = 0
    for i in
range(1970, year): # print("%d年" % i) if isLeapYear(i): totalDays += 366 else: totalDays += 365 return totalDays # 定義計算本年一月截止到目前月的 月天數的函數 def monthsDays(year, month): s = ("0", "31", "60", "91", "121", "152", "182", "213", "244", "274", "305", "
335") days = int(s[month - 1]) # print(month,"月") if isLeapYear(year): days = days else: if month == 1: days = 0 elif month == 2: days == 31 else: days = days - 1 return days # 定義計算本月的天數 def thisMonthDays(year, month): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: return 31 elif isLeapYear(year) and month == 2: return 29 elif (not isLeapYear(year)) and month == 2: return 28 else: return 30 # 計算本月一號是星期幾的函數 def week(year, month): thisDay = 0 yDays = yearsDays(year) mDays = monthsDays(year, month) # 計算出來年天數和月天數的總和 sumDays = yDays + mDays if sumDays % 7 == 0: thisDay = 4 else: if (sumDays % 7 + 4 > 7): thisDay = abs(sumDays % 7 - 3) else: thisDay = sumDays % 7 + 4 # print("星期%d" % thisDay) return thisDay # 定義打印頂部標題欄函數 def printTitle(year, month): print("-------------------------------------%s年%d月----------------------------------------" % (year, month)) s = ("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六") for i in s: print("%-10s" % i, end="") print() # 打印主體部分 def printMain(year, month): day1 = week(year, month) day2 = thisMonthDays(year, month) # 打印空白地方 if day1 != 7: for i in range(1, day1 + 1): s = " " print("%-13s" % s, end="") # 打印其他地方 for j in range(day1 + 1, day1 + day2 + 1): if j % 7 == 0: print("%-13d" % (j - day1)) else: print("%-13d" % (j - day1), end="") year = int(input("請輸入年份:")) month = int(input("請輸入月份:")) printTitle(year, month) printMain(year, month)

python打印萬年歷