用Python编写一个简单的日历应用程序
发布时间:2023-12-04 07:58:31
以下是一个简单的日历应用程序的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("Mo Tu We Th Fr Sa Su")
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_date():
while True:
try:
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if year < 0 or month < 1 or month > 12:
raise ValueError()
return year, month
except ValueError:
print("输入无效,请重新输入.")
def main():
year, month = get_date()
print_calendar(year, month)
if __name__ == '__main__':
main()
该程序使用了calendar模块来获取指定年份和月份的日历,并打印出来。用户首先需要输入年份和月份,然后程序会调用calendar.monthcalendar()函数获取日历信息,并通过循环将日历打印到控制台上。
以下是该程序的使用例子:
请输入年份: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
在使用例子中,用户输入了2021年7月,程序首先打印出了指定月份的日历。可以看到,每周以星期一开始,并且行末的空格用于对齐。
此外,该程序还进行了一些输入校验,确保用户输入的年份和月份是有效的。如果用户输入非法的值,程序会显示错误信息,并要求重新输入。
