[Python基础]在控制台打印某年的日历

直接上代码

# encoding:utf-8
from datetime import datetime


class Calendar:
    def __init__(self, year):
        """
        初始化
        :param year:
        """
        self.year = year

    def is_leap_year(self):
        """
        判断是否为闰年
        :return: 是否为闰年
        """
        year = self.year
        return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

    def get_days_month(self, month):
        """
        计算月份天数
        :param month:月份
        :return:
        """
        if month < 1 or month > 12:
            return 0
        if month == 2:
            if self.is_leap_year():
                return 29
            else:
                return 28
        elif month == 4 or month == 6 or month == 9 or month == 11:
            return 30
        else:
            return 31

    def get_week_data(self, month, day):
        """
        根据日期获取星期数
        :param month: 月份
        :param day: 天
        :return: 星期数
        """
        data = datetime.date(datetime(self.year, month, day))
        return int(data.strftime("%w"))

    def get_month(self, month):
        """
        显示月历
        :param month: 月份
        :return: null
        """
        print(f"{self.year}年{month}月")
        print('日\t一\t二\t三\t四\t五\t六')
        # 计算1号星期数,根据星期数显示\t
        day_of_week = self.get_week_data(month, 1)
        for i in range(0, day_of_week):
            print('\t', end='')
        # 计算当月天数并在同一行显示
        days = self.get_days_month(month)
        for i in range(1, days + 1):
            print(str(i) + '\t', end='')
            # 每周六换行
            if self.get_week_data(month, i) == 6:
                print()

    def show_calendar(self):
        """
        显示年历
        :return: null
        """
        for i in range(1, 13):
            self.get_month(month=i)
            print()


def main():
    ca = Calendar(2021)
    ca.show_calendar()


if __name__ == '__main__':
    main()


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值