1.输入任何年份,输入月份
2.格式化输出本月的日历
3.思路
3.1,首先1970年是Unix系统诞生的时间,1970年成为Unix的元年,1970年1月1号是星期四,现在大多的手机的
日历功能只能显示到1970年1月1日这一天;以1970年一月一号作为参考。
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号是星期几;
如果是小于1970年,可以打印,同理。
3.3, 判断本月的总天数;
3.4, 打印日历;
4.运行效果图1:
运行效果图2:
运行效果图3:
5.代码实现
# 定义判断闰年的函数,是闰年返回True,不是返回False def isLeapYear(year):if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):return Trueelse:return False# 定义计算从1970年到截止到今年的 年天数的函数 def yearsDays(year):totalDays = 0if year >= 1970:for i in range(1970, year):# print("%d年" % i)if isLeapYear(i):totalDays += 366else:totalDays += 365else:for i in range(year, 1970):# print("%d年" % i)if isLeapYear(i):totalDays += 366else:totalDays += 365return 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 = dayselse:if month == 1:days = 0elif month == 2:days == 31else:days = days - 1return 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 31elif isLeapYear(year) and month == 2:return 29elif (not isLeapYear(year)) and month == 2:return 28else:return 30# 计算本月一号是星期几的函数 def week(year, month):thisDay = 0yDays = yearsDays(year)mDays = monthsDays(year, month)# 计算出来年天数和月天数的总和if year >= 1970:sumDays = yDays + mDaysif sumDays % 7 == 0:thisDay = 4else:if sumDays % 7 + 4 > 7:thisDay = abs(sumDays % 7 - 3)else:thisDay = sumDays % 7 + 4else:sumDays = yDays - mDaysif sumDays % 7 == 0:thisDay = 4else:lastDay = sumDays % 7thisDay = 4 - lastDayif thisDay < 0:thisDay += 7return thisDay# 定义打印顶部标题栏函数 def printTitle(year, month):print("-" * 36, "%s年%d月" % (year, month), "-" * 36)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)