用python纯手写一个日历

一、代码

# 月份名称数组
months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
]
# 每月天数数组
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]


# 判断是否是闰年
def leap_year(y):
    if (y % 100 != 0 and y % 4 == 0) or (y % 400 == 0):
        month_days[1] += 1


# 计算某年某月某日到该年第一月第一日的日数
def year_days(y, m, d):
    all_days = 0
    # 判断是否是闰年,闰年二月有29天
    leap_year(y)
    # 计算总日数
    for i in range(m - 1):
        all_days += month_days[i]
    all_days += d
    return all_days


# 得到某年某月某日是星期几
def week(y, m, d):
    all_days = 0
    if y == 1940:
        all_days = year_days(y, m, d) - 1
    else:
        # 计算总天数,包括闰年的额外一天
        for i in range(1940, y):
            all_days += 365 + ((y % 100 != 0 and y % 4 == 0) or (y % 400 == 0))
        all_days += year_days(y, m, d) - 1
    get = (all_days + 1) % 7
    return get


# 打印某月的日历
def show_month(y, m):
    # 判断是否是闰年,闰年二月有29天
    leap_year(y)
    week1 = week(y, m, 1)
    print('{}\n---------------------------'.format(month_days[m - 1]))
    print("Sun  Mon  Tue  Wed  Thu  Fri  Sat")
    date = 1
    # 遍历星期和日期
    while date <= week1 + month_days[m - 1]:
        flag = [0] * 7
        # 遍历一周的每一天
        for a in range(7):
            if date <= (week1 + month_days[m - 1]):
                if date < week1:
                    flag[a] = -1
                else:
                    flag[a] = date - week1
            else:
                flag[a] = -1

            date += 1

        # 打印一周的日期
        print(" ".join(f"{-1 if x == 0 else x:<4}" for x in flag))
    print()


# 主函数
def main():
    print("输入要查找的年月份")
    year = input("年:")
    month = input("月:")
    if not (year.isdigit() and month.isdigit()):
        print('请输入一个合法的日期!!!')
    else:
        show_month(int(year), int(month))


if __name__ == "__main__":
main()

二、运行结果

  • 17
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值