Python编写一个简单的命令行日历应用程序
发布时间:2023-12-04 20:58:02
下面是一个简单的命令行日历应用程序的Python代码,并附带一个使用例子:
import calendar
def print_calendar(year, month):
# 打印指定年份和月份的日历
cal = calendar.monthcalendar(year, month)
month_name = calendar.month_name[month]
print(f"
{month_name} {year}")
print("-" * 20)
print("Mon Tue Wed Thu Fri Sat Sun")
for week in cal:
week_str = ""
for day in week:
if day == 0:
week_str += " "
else:
week_str += f"{day:2d} "
print(week_str)
def get_user_input():
# 获取用户输入的年份和月份
year = int(input("请输入年份: "))
month = int(input("请输入月份: "))
return year, month
# 示例代码
year, month = get_user_input()
print_calendar(year, month)
这个程序使用了Python内置的calendar模块来生成日历。print_calendar函数接受年份和月份作为参数,并打印出该月的日历。get_user_input函数用于获取用户输入的年份和月份。在示例代码中,先调用get_user_input函数获取用户输入,并将结果赋值给变量year和month,然后调用print_calendar函数打印出指定年份和月份的日历。
使用例子:
请输入年份: 2022
请输入月份: 1
January 2022
--------------------
Mon Tue Wed Thu Fri Sat Sun
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
在这个例子中,用户输入了年份2022和月份1,程序打印出了2022年1月份的日历。
