You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python月份天数查询程序简化实现方案问询

更简洁的月份天数查询实现方案

优化后的代码

# 定义各月份天数,索引对应1-12月(索引0占位)
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 有效月份名称列表,用于输入验证
valid_month_names = ['january', 'february', 'march', 'april', 'may', 'june', 
                     'july', 'august', 'september', 'october', 'november', 'december']

# 循环获取有效月份输入,直到用户输入正确
while True:
    month_input = input("请输入月份:").strip().lower()
    if month_input in valid_month_names:
        month_idx = valid_month_names.index(month_input) + 1  # 转换为1-12的月份索引
        break
    print("无效月份,请重新输入。")

# 处理二月的闰年判断逻辑
if month_input == 'february':
    year = int(input("请输入年份:"))
    is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
    days = 29 if is_leap else 28
    print(f"这是{'闰年' if is_leap else '平年'}的二月,有{days}天。")
else:
    # 直接通过索引从列表取对应月份天数
    print(f"{month_input.capitalize()}有{month_days[month_idx]}天。")

优化说明

  • 用列表替代字典:利用月份的固定顺序,用列表索引对应1-12月的天数,避免了字典重复键值对的冗余定义,代码更简洁。
  • 完善输入验证:新增while True循环,确保用户输入无效月份时会被要求重新输入,符合题目要求。
  • 简化逻辑结构:把常量定义(月份列表、天数列表)放在循环外,避免重复创建;用变量is_leap简化闰年判断的可读性。
  • 统一输出格式:用格式化字符串让输出语句更简洁一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:08:25