一、代码
# 月份名称数组
months = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"
]
# 每月天数数组
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]# 判断是否是闰年
def leap_year(y):if (y % 100 != 0 and y % 4 == 0) or (y % 400 == 0):month_days[1] += 1# 计算某年某月某日到该年第一月第一日的日数
def year_days(y, m, d):all_days = 0# 判断是否是闰年,闰年二月有29天leap_year(y)# 计算总日数for i in range(m - 1):all_days += month_days[i]all_days += dreturn all_days# 得到某年某月某日是星期几
def week(y, m, d):all_days = 0if y == 1940:all_days = year_days(y, m, d) - 1else:# 计算总天数,包括闰年的额外一天for i in range(1940, y):all_days += 365 + ((y % 100 != 0 and y % 4 == 0) or (y % 400 == 0))all_days += year_days(y, m, d) - 1get = (all_days + 1) % 7return get# 打印某月的日历
def show_month(y, m):# 判断是否是闰年,闰年二月有29天leap_year(y)week1 = week(y, m, 1)print('{}\n---------------------------'.format(month_days[m - 1]))print("Sun Mon Tue Wed Thu Fri Sat")date = 1# 遍历星期和日期while date <= week1 + month_days[m - 1]:flag = [0] * 7# 遍历一周的每一天for a in range(7):if date <= (week1 + month_days[m - 1]):if date < week1:flag[a] = -1else:flag[a] = date - week1else:flag[a] = -1date += 1# 打印一周的日期print(" ".join(f"{-1 if x == 0 else x:<4}" for x in flag))print()# 主函数
def main():print("输入要查找的年月份")year = input("年:")month = input("月:")if not (year.isdigit() and month.isdigit()):print('请输入一个合法的日期!!!')else:show_month(int(year), int(month))if __name__ == "__main__":
main()