Use Python function to write a perpetual calendar

You can adjust the final output according to the formatted printing characters, but some Chinese seems to be difficult to adjust, you can change to the words of the week, which should be better, the format() function can be used to format the printed characters, format() You can use a string to call, or you can use it alone.
You can click into the formatted print characters to understand

# 判断是否闰年
def isleap(year):
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

# 判断月的天数
def month_days(year,month):
    if month in [1,3,5,7,8,10,12]:
        return 31
    if month == 2:
        if isleap(year):
            return 29
        else:
            return 28
    return 30

# 1900年到输入年份的总天数
def total_days(year):
    s = 0
    for i in range(1900,year):
        if isleap(i):
            s += 366
        else:
            s += 365
    return s

# 1月到输入月份的天数
def days(year,month):
    s = 0
    for i in range(1,month):
        s += month_days(year,i)
    return s

# 获取某年某月的日历
def monthcalendar(year,month):
    total = total_days(year) + days(year, month)
    a = total % 7
    print('星期日'.center(8, ' '), end='')
    print('星期一'.center(8, ' '), end='')
    print('星期二'.center(8, ' '), end='')
    print('星期三'.center(8, ' '), end='')
    print('星期四'.center(8, ' '), end='')
    print('星期五'.center(8, ' '), end='')
    print('星期六'.center(8, ' '), end='')
    print()
    count = 0
    for i in range(0, month_days(year, month) + a + 1):
        if i <= a:
            print(format(' ','10'), end='')
            count += 1
        else:
            print(format(str(i - a),'^10'), end='')
            count += 1
        if count == 7:
            count = 0
            print()
    print()

# 输出某年一年的日历
def yearcalendar(year):
    for i in range(1,13):
        print(f'{i}月:')
        monthcalendar(year,i)
        print()

# 开始函数
def start():
    while True:
        print('-------欢迎来到万历表查询页面-------')
        print('1.查询某年的日历\n2.查询某年某月的日历\n3.退出查询')
        print('---------------------------------')
        n = int(input('请输入你的操作:'))
        if n == 1:
            year = int(input('请输入要查询的年份:'))
            yearcalendar(year)
        elif n == 2:
            year = int(input('请输入要查询的年份:'))
            month = int(input('请输入1-12:'))
            monthcalendar(year,month)
        elif n == 3:
            print('退出成功')
            break
        else:
            print('指令错误,请重新输入!!!')
if __name__ == '__main__':
    start()
Demonstrate by yourself

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112910277