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

Python月天数查询函数报错求助:输入无响应且逻辑有误

原代码问题分析

你这段代码没法正常工作的原因如下:

  • 函数定义的months和days参数完全多余,你在函数内部又重新赋值了,根本没用到传入的参数
  • input()获取的是字符串类型,你直接和列表里的整数比较,永远不会匹配成功,必须先转成int类型
  • 列表不能用months[0,2,4,6,7,9,11]这种语法取多个元素,而且就算写法正确,单个月份数字和一个包含多个元素的列表也不可能相等
  • 代码逻辑混乱,你想返回对应单个月份的天数,但写法却是返回一堆天数,完全不符合需求
  • 最后你只定义了函数,但没有调用它,所以运行代码后根本不会触发输入逻辑
几种可行的实现思路

思路1:字典映射(最直观简洁)

用字典把月份和天数一一对应,直接通过键取值,逻辑清晰:

def month_days():
    month = int(input("请输入1-12的数字:"))
    day_dict = {
        1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
        7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    }
    # 新增输入合法性校验
    if 1 <= month <= 12:
        return day_dict[month]
    else:
        return "请输入1-12范围内的数字"

# 调用函数并打印结果
print(month_days())

思路2:列表索引匹配(利用位置对应关系)

月份是1-12,列表索引是0-11,将输入的月份减1就能直接对应到列表的天数位置:

def month_days():
    try:
        month = int(input("请输入1-12的数字:"))
        days_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if 1 <= month <= 12:
            return days_list[month - 1]
        else:
            return "请输入1到12之间的有效数字"
    except ValueError:
        return "请输入纯数字"

print(month_days())

这里加了try-except捕获输入非数字的情况,避免程序直接报错崩溃。

思路3:分组条件判断(适合新手理解逻辑)

按天数把月份分成三组,用in判断输入的月份属于哪一组:

def month_days():
    try:
        month = int(input("请输入1-12的数字:"))
        if month in [1, 3, 5, 7, 8, 10, 12]:
            return 31
        elif month in [4, 6, 9, 11]:
            return 30
        elif month == 2:
            return 28
        else:
            return "输入的月份无效"
    except ValueError:
        return "请输入有效的数字"

print(month_days())

进阶思路:考虑闰年的2月天数

如果需要更严谨的逻辑,可以加入年份判断,处理闰年2月的29天:

def month_days():
    try:
        year = int(input("请输入年份:"))
        month = int(input("请输入1-12的数字:"))
        if month == 2:
            # 闰年判断规则:能被4整除但不能被100整除,或者能被400整除
            if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
                return 29
            else:
                return 28
        elif month in [1, 3, 5, 7, 8, 10, 12]:
            return 31
        elif month in [4, 6, 9, 11]:
            return 30
        else:
            return "月份输入无效"
    except ValueError:
        return "请输入有效的数字"

print(month_days())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:22:06