Python实例教程之检索输出月份日历表

(编辑:jimmy 日期: 2024/9/21 浏览:2)

一、题目要求与分析

根据输入的年和月,打印该月的日历。如图所示:

Python实例教程之检索输出月份日历表

题目分析:复杂的问题往往很简单,只需要找到拆分点即可,就像这种题可以分为三个函数:

"text-align: center">Python实例教程之检索输出月份日历表

为了方便起见,我们在这里直接把函数的名字给定一下:

"htmlcode">

def day(y, m, d):#计算y年m月d日是星期几

 y0 = y - (14 - m)//12
 x = y0 + y0//4 - y0//100 + y0 //400
 m0 = m + 12*((14 - m)//12) - 2
 d0 = (d + x + 31*m0//12) % 7
 return d0 #注意,周日是0

def isLeapYear(year): #判断year年是否闰年
 isLeapYear = True 
 if year % 4 ==0: #整除可不是等于0,天
 if year % 100 ==0:
 if year % 400 ==0:
 isLeapYear = True
 else:
 isLeapYear = False
 else:
 isLeapYear = True 
 else:
 isLeapYear = False #注意是一个等号还是两个等号
 return isLeapYear

def calendar(y, m): #打印y年m月日历
 print(' {}年{}月'.format(y,m))
 print('Su\tM\tTu\tW\tTh\tF\tSa')
 # 请在下面编写代码
 # ********** Begin ********** #
 month_1 = [1,3,5,7,8,10,12]
 month_2 = [4,6,9,11]
 momth_number = 0
 if isLeapYear(y): #计算这个月有多少天
 if m == 2:
 month_number = 29
 else:
 if m in month_1:
 month_number = 31
 if m in month_2:
 month_number = 30
 else:
 if m == 2:
 month_number = 28
 else:
 if m in month_1:
 month_number = 31
 if m in month_2:
 month_number = 30 
 
 table = day(y, m, 1) #空格 排列输出
 for j in range (1,month_number + 1): #注意加一
 if j == 1:
 print("\t" * table,end = '')
 j = str(j)
 print(j + "\t",end = '')
 j = eval(j)
 if (j + day(y, m, 1)) % 7 == 0:
 print("\r")
 print("\r")
 
for (y,m) in [(2020,12), (2017,2), (2016,2)]:
 calendar(y, m)
 print('---------------------------')

三、我们来逐个fenxi

(1) day(y, m, d)函数

这个函数没有什么实质性的技术含量,因为这里涉及到一个数学的问题,比如,直接用数学公式,下边我提供一下本函数用的三个数学公式:

Python实例教程之检索输出月份日历表

假如给定了y,m,d,则上边的d0就是要求的星期几。

注意:星期日代表的数字是0,切记,但别问我咋知道的。

函数就这样出来了:

def day(y, m, d):
 y0 = y - (14 - m)//12
 x = y0 + y0//4 - y0//100 + y0 //400
 m0 = m + 12*((14 - m)//12) - 2
 d0 = (d + x + 31*m0//12) % 7
 return d0 

(2) disLeapYear(year)函数

关于判断闰年这件事想必很好知晓,这里我提供一张流程结构图仅供参考:

Python实例教程之检索输出月份日历表

"htmlcode">

def isLeapYear(year): #判断year年是否闰年
 isLeapYear = True 
 if year % 4 ==0: #整除可不是等于0,天
 if year % 100 ==0:
  if year % 400 ==0:
  isLeapYear = True
  else:
  isLeapYear = False
 else:
  isLeapYear = True 
 else:
 isLeapYear = False #注意是一个等号还是两个等号
 return isLeapYear

(3) calendar(y, m)函数

Python实例教程之检索输出月份日历表

这里要解决两个问题,也就是本次程序的核心:

"text-align: center">Python实例教程之检索输出月份日历表

1 . 这个月有多少天?

"text-align: center">Python实例教程之检索输出月份日历表

"htmlcode">

 table = day(y, m, 1) #求空格数
 for j in range (1,month_number + 1): #注意加一
 if j == 1:
  print("\t" * table,end = '')
 j = str(j)
 print(j + "\t",end = '')
 j = eval(j)
 if (j + day(y, m, 1)) % 7 == 0:
  print("\r")
 print("\r")

注意:

"text-align: center">Python实例教程之检索输出月份日历表

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。