当前位置: 首页 > news >正文

python笔记之判断月份有多少天

1、通过随机数作为目标月份

import random
month = random.randint(1,12)

2、判断对应的年份是闰年还是平年

因为2月这个特殊月份,闰年有29天,而平年是28天,所以需要判断对应的年份属于闰年还是平年,代码如下

# 判断年份是闰年还是平年
def guess_year(year):
    if year % 400 == 0:
        return True
    elif year % 100 != 0 and year % 4 == 0:
        return True
    return False

3、返回对应月份的天数

若是大月,对应31天;小月则是30天;2月根据是闰年还是平年返回29或者28天

3.1、判断当前月是哪种类型

big_month = [1, 3, 5, 7, 8, 10, 12]
big_month_days = 31
big_month_type = 1

small_month = [4, 6, 9, 11]
small_month_days = 30
small_month_type = 2

special_month = [2]
special_month_type = 3

# 判断月份是大月、小月还是平月
def guess_month_type(month):
    match month:
        case month if month in big_month:
            return big_month_type
        case month if month in small_month:
            return small_month_type
        case month if month in special_month:
            return special_month_type
        case _:
            raise Exception("Invalid month")

3.2、根据月份的类型和年份类型,返回目标月份的天数

# 返回一个月的天数
def get_month_days(year, month):
    # 获取月份类型
    month_type = guess_month_type(month)
    match month_type:
        case month_type if month_type == big_month_type:
            return big_month_days
        case month_type if month_type == small_month_type:
            return small_month_days
        case month_type if month_type == special_month_type:
            # 2月判断年份是闰年还是平年
            if guess_year(year):
                return 29
            else:
                return 28
        case _:
            raise Exception("Invalid month type")

4、测试代码

if __name__ == "__main__":
    year = int(input("请输入年份:"))
    month = random.randint(1,12)
    month_days = get_month_days(year, month)
    print(f'{month}月有{month_days}天')

相关文章:

  • 【商城实战(72)】解锁用户评价与晒单功能开发秘籍
  • 【第2月_day10】Pandas数据查看与选择
  • MySQL查询语句的使用
  • TypeScript实现二分查找算法:原理剖析与最佳实践
  • 网页的性能优化
  • 一. 相机模组摆放原理
  • OpenAI深夜直播「偷袭」谷歌!GPT-4o原生图像生成:奥特曼带梗图,AGI战场再燃战火
  • 阶段二:面向对象编程
  • 生活电子常识——cmd不能使用anaconda的python环境,导致输入python打开应用商店
  • 文件上传绕过的小点总结(6)
  • Linux之 权限提升(Linux Privilege Escalation)
  • 进程间通信 命名管道 ─── Linux第24课
  • 同旺科技USB to SPI 适配器 ---- 指令之间延时功能
  • SpringBoot分布式项目实战:观察者模式的高阶应用与避坑指南
  • JWT应用样例
  • 【Android】Activity 生命周期(详细介绍)
  • Mac 常用命令
  • 《Git江湖录·分支篇》
  • 二叉树进阶
  • 【leetcode刷题日记】lc.560-和为 K 的子数组
  • 新任国防部新闻发言人蒋斌正式亮相
  • 今年有望投产里程已近3000公里,高铁冲刺谁在“狂飙”?
  • 俄谈判代表团已抵达土耳其,谈判预计在莫斯科时间10时左右开始
  • 苏轼“胡为适南海”?
  • 广东省人大教科文卫委原主任委员梁万里被开除党籍:退休后受贿仍不知止
  • 新剧|《藏海传》定档,《折腰》《人生若如初见》今日开播