使用Python实现一个简单的日历程序
发布时间:2023-12-04 17:48:04
以下是使用Python实现一个简单的日历程序的代码:
import calendar
def display_calendar(year, month):
"""
显示指定年份和月份的日历
:param year: 年份
:param month: 月份
"""
cal = calendar.monthcalendar(year, month)
month_name = calendar.month_name[month]
year_str = str(year)
month_str = str(month)
print(f" {month_name} {year_str}")
print("Mo Tu We Th Fr Sa Su")
for week in cal:
week_str = ""
for day in week:
if day == 0:
week_str += " "
else:
day_str = str(day)
week_str += " "*(2-len(day_str)) + day_str
week_str += " "
print(week_str)
# 使用例子
display_calendar(2021, 7)
运行以上代码,会输出2021年7月的日历:
July 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
该程序使用了Python中的calendar模块,其中的monthcalendar函数可以返回指定年份和月份的日历。程序使用循环遍历每一行的日期,并拼接成字符串,然后进行输出。月份名称和年份通过calendar.month_name和str函数获取和转换。
你可以根据需要修改display_calendar函数中的年份和月份参数来显示不同的日历。代码中还包含了一个使用例子,显示了2021年7月的日历。
