You need to enable JavaScript to run this app. 如何编写按数字输入月份输出对应天数的Python程序
优惠活动
大模型
产品
解决方案
定价
更多

如何编写按数字输入月份输出对应天数的Python程序

实现方案一:纯逻辑硬编码实现(无第三方/标准库依赖)

这种方案适合完全不想引入任何外部模块的极简场景,核心逻辑梳理:

  • 固定天数映射:1、3、5、7、8、10、12月固定31天;4、6、9、11月固定30天;2月默认28天
  • 可选闰年适配:如果需要精确匹配2月的实际天数,可增加年份参数,按照「能被4整除但不能被100整除,或能被400整除为闰年」的规则判断,闰年2月为29天
  • 必须增加输入合法性校验,避免用户输入超出1-12范围的数字导致程序异常

示例代码:

def calculate_month_days(month: int, year: int = None) -> int:
    # 范围校验
    if month not in range(1, 13):
        raise ValueError("月份输入不合法,请输入1-12之间的整数")
    # 固定天数对照表
    days_table = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    total_days = days_table[month - 1]
    # 闰年分支处理2月
    if month == 2 and year:
        leap_flag = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
        total_days = 29 if leap_flag else 28
    return total_days

# 交互逻辑
if __name__ == "__main__":
    user_input = int(input("请输入对应月份的数字:"))
    print(f"该月份的天数为:{calculate_month_days(user_input)}天")
实现方案二:Python标准库简化实现

这种方案不用手动维护天数对照表和闰年判断逻辑,直接调用内置calendar模块的现成方法,减少逻辑出错的概率:

  • 核心方法calendar.monthrange(year, month)会返回一个元组,第一个值是当月第一天的星期偏移量,第二个值就是当月的总天数
  • 适配所有平年、闰年的特殊场景,不需要手动写判断分支

示例代码:

import calendar

def calculate_month_days(month: int, year: int = 2024) -> int:
    if month not in range(1, 13):
        raise ValueError("月份输入不合法,请输入1-12之间的整数")
    # 直接取返回元组的第二个元素即为当月天数
    return calendar.monthrange(year, month)[1]

# 交互测试
if __name__ == "__main__":
    user_month = int(input("请输入对应月份的数字:"))
    print(f"该月份的天数为:{calculate_month_days(user_month)}天")

注意:如果你的需求只需要返回不区分闰年的默认值,可以跳过年份参数传递,2月统一返回28天即可,大幅简化交互流程。

内容的提问来源于stack exchange,提问作者zimgold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 07:15:08