万年历系统:Python 实现及算法分析

这个万年历系统的主要难点在于如何计算某一年的某一个月的日历,以及如何控制输出的格式和行数。我们可以借助 Python 中的 datetime 模块和 calendar 模块来实现这一功能。

datetime 模块可以用来获取当前时间以及具体的年、月、日等信息,而 calendar 模块可以用来生成日历。

解题思路:

  1. 导入相关模块
import datetime
import calendar
  1. 定义函数 get_calendar(year, month),用来获取指定年月的日历
def get_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    month_name = calendar.month_name[month]
    print('{:^20}'.format(month_name + ' ' + str(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 += '{:>2}  '.format(day)
        print(week_str)
    print('
')
  1. 定义函数 get_year_calendar(year),用来获取指定年份的 12 个月份的日历
def get_year_calendar(year):
    for month in range(1, 13):
        get_calendar(year, month)
  1. 定义主函数 main(),用来获取用户输入的年份和月份,并调用相应的函数来显示日历
def main():
    while True:
        try:
            year = int(input('请输入年份:'))
            if year < 0:
                raise ValueError
            break
        except ValueError:
            print('年份输入有误,请重新输入!')

    while True:
        try:
            month = int(input('请输入月份(不输入则显示整年):'))
            if month < 0 or month > 12:
                raise ValueError
            break
        except ValueError:
            print('月份输入有误,请重新输入!')

    if month == 0:
        get_year_calendar(year)
    else:
        get_calendar(year, month)
  1. 在主函数中加入调用 get_year_calendar() 函数的代码,以实现获取指定年份的 12 个月份的日历的功能。

完整代码如下:

import datetime
import calendar


def get_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    month_name = calendar.month_name[month]
    print('{:^20}'.format(month_name + ' ' + str(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 += '{:>2}  '.format(day)
        print(week_str)
    print('
')


def get_year_calendar(year):
    for month in range(1, 13):
        get_calendar(year, month)


def main():
    while True:
        try:
            year = int(input('请输入年份:'))
            if year < 0:
                raise ValueError
            break
        except ValueError:
            print('年份输入有误,请重新输入!')

    while True:
        try:
            month = int(input('请输入月份(不输入则显示整年):'))
            if month < 0 or month > 12:
                raise ValueError
            break
        except ValueError:
            print('月份输入有误,请重新输入!')

    if month == 0:
        get_year_calendar(year)
    else:
        get_calendar(year, month)


if __name__ == '__main__':
    main()

需要注意的是,这个程序中的日历是按照 ISO 8601 标准显示的,即每周从星期一开始,并且每周有 7 天。如果需要按照其他标准显示日历,可以在 get_calendar() 函数中修改输出格式。

万年历系统:Python 实现及算法分析

原文地址: https://www.cveoy.top/t/topic/oRw2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录