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

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}天')

http://www.kler.cn/a/611071.html

相关文章:

  • Rust从入门到精通之精通篇:24.高级异步编程
  • 做一个有天有地的css及html画的旋转阴阳鱼
  • Leetcode 188 买卖股票的最佳时机 Ⅳ
  • 【计算机网络】DHCP工作原理
  • Postman 如何发送 XML 格式的 API 请求?
  • 【redis】主从复制:单点问题、配置详解、特点详解
  • 使用 Vite 提升前端开发体验:入门与配置指南
  • 【云馨AI-大模型】自动化部署Dify 1.1.2,无需科学上网,Linux环境轻松实现,附Docker离线安装等
  • JVM类文件结构详解
  • 六级词汇量积累(day12)
  • 使用请求调用本地部署的stable-diffusion接口
  • Selenium工作原理详解
  • 为何服务器监听异常?
  • 【Python】Tensorboard (Pytorch版)用法
  • springboot+mybatisplus
  • 【git拉取冲突解决】Please move or remove them before you merge. Aborting
  • 【Unity网络编程知识】使用Socket实现简单TCP通讯
  • Walrus 经济模型 101
  • 6.1 模拟专题:LeetCode 1576. 替换所有的问号
  • linux,防火墙,firewall,常用命令