使用Python编写一个简单的日历程序
发布时间:2023-12-04 08:59:32
以下是使用Python编写的一个简单的日历程序:
import calendar
def display_calendar(year, month):
# 获取指定年月的日历
cal = calendar.monthcalendar(year, month)
# 打印日历头部
print(f"{'-'*20}")
print(f"{calendar.month_name[month]} {year}")
print(f"{'-'*20}")
print("Mo Tu We Th Fr Sa Su")
# 打印日历内容
for week in cal:
line = ""
for day in week:
if day == 0:
line += " " # 天数为0代表不在指定月份中,输出空格
else:
line += f"{day:2d} " # 使用两位数表示天数
print(line)
print(f"{'-'*20}")
# 使用例子
display_calendar(2021, 8) # 显示2021年8月的日历
以上代码实现了一个简单的日历程序,使用calendar模块获得指定年份和月份的日历数据,并将其打印出来。
在主函数display_calendar()中,我们首先使用calendar.monthcalendar(year, month)获取指定年份和月份的日历数据,然后使用一个嵌套循环遍历日历数据,并将日历输出到控制台。
在使用例子中,我们调用display_calendar()函数,将2021年8月的日历显示出来。
执行以上代码,将会输出以下结果:
--------------------
August 2021
--------------------
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
--------------------
以上日历程序可以根据用户输入的年份和月份显示相应的日历,比较简单易懂。可以根据实际需求进行修改和扩展。
