Python 程序显示一个月的日历


2022年3月17日, Learn eTutorial
2216

在这个简单的 Python 程序中,我们需要显示一个月的日历。这是一个初学者级别的 Python 程序。

要理解这个例子,您应该了解以下 Python 编程主题

解释 Python 中的 Calendar 模块?

为了显示日历,Python 中有一个预定义模块叫做 calendar,它用于显示日历。calendar 模块的语法是 (calendar.month(yy,mm)),其中:

  • yy 是年份
  • mm 是月份。

在 Python 语言中,我们对这个 calendar 模块有许多预定义操作。例如,

  • firstweekday():返回一周的第一天数字。
  • isleap (year):用于检查给定年份是否为闰年。
  • Leap days (year1, year2):返回两年限制内的闰日数。
  • Month (year, month ):此程序中使用了此方法,它打印特定年份的特定月份。

还有更多与 calendar 模块一起使用的方法,这些方法在 calendar 模块教程中有所描述。

如何使用 Python 语言打印日历?

在这个简单的 Python 程序中,我们从用户那里获取年份和月份的值,并导入 calendar 模块。最后,我们调用 print 函数并调用 calendar 模块来打印年份和月份 print(calendar.month(yy,mm))。让我们分解一下代码:

算法

步骤 1: 导入 Python 内置模块 calendar,该模块具有我们上面描述中讨论的许多可接受的操作方法。

步骤 2: 使用 input 方法从用户那里获取年份和月份的值(作为字符串),并使用 Python 语言中的 int 将其转换为整数。

步骤 3: 只需使用 month(yy, mm) 操作和 calendar 模块,例如 calendar. month(yy, mm) 来打印特定年份的特定月份。

Python 源代码

                                          import calendar  

yy = int(input("Enter year: "))  

mm = int(input("Enter month: "))  
  
print(calendar.month(yy,mm))
                                      

输出

Enter year: 2020
Enter month: 5
      May 2020
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31