制作年历,无需导入日历

2024-05-15 06:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个给定的函数:

  1. 一年

  2. 一周中的某一天。

函数应该打印该年的年度日历

示例: enter image description here

也可以考虑闰年。一年可以被4整除,但不能被100整除,这就是闰年!但如果能被400整除,那就是闰年了。 1900可以被4和100整除,但不是闰年。 2000年可被4和100“及400”整除,是闰年。

在制作这个日历时考虑闰年。


Tags: 函数示例年度历时
1条回答
网友
1楼 · 发布于 2024-05-15 06:32:57

我想这差不多就可以了。

# List of tuples for Months and date ranges
# + 1 added to avoid confusion of max day range
calender = [('January', range(1, 31 + 1)),
            ('Feburary', range(1, 28 + 1)),
            ('March', range(1, 31 + 1)),
            ('April', range(1, 30 + 1)),
            ('May', range(1, 31 + 1)),
            ('June', range(1, 30 + 1)),
            ('July', range(1, 31 + 1)),
            ('August', range(1, 31 + 1)),
            ('September', range(1, 30 + 1)),
            ('October', range(1, 31 + 1)),
            ('November', range(1, 30 + 1)),
            ('December', range(1, 31 + 1))]

week = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

def make_calendar(year, start_day):
    """
    make_calendar(int, str) --> None
    """
    # Determine current starting position on calendar
    start_pos = week.index(start_day)

    # if True, adjust Feburary date range for leap year | 29 days
    if is_leap(year):
        calender[1] = ('Feburary', range(1, 29 + 1))

    for month, days in calender:
        # Print month title
        print('{0} {1}'.format(month, year).center(20, ' '))
        # Print Day headings
        print(''.join(['{0:<3}'.format(w) for w in week]))
        # Add spacing for non-zero starting position
        print('{0:<3}'.format('')*start_pos, end='')

        for day in days:
            # Print day
            print('{0:<3}'.format(day), end='')
            start_pos += 1
            if start_pos == 7:
                # If start_pos == 7 (Sunday) start new line
                print()
                start_pos = 0 # Reset counter
        print('\n')

def is_leap(year):
    """Checks if year is a leap year"""
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False
yr=int(input('Enter Year'))
strtday=input('Enter start day of the year Mo,Tu,We,Th,Fr,Sa,Su')
make_calendar(yr,strtday)

相关问题 更多 >

    热门问题