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

镍价查询项目故障求助:屏幕仅显示单个数值问题排查

问题分析与修复方案

核心问题

你的代码逻辑错误出在str.find()的使用上:

  • find()找到子串时返回索引位置(比如匹配"jan"返回0),找不到返回**-1**
  • Python中0会被判定为False,-1会被判定为True,导致匹配目标月份的条件不执行,反而所有不匹配的条件都会触发,最终打印多个重复的0.00(视觉上可能像单个数值)

结合你的需求(输入年份后,可查询对应月份镍价;输入特定指令展示所有月份数据),以下是修复后的代码和优化说明。

修复后的代码

# 存储2015年镍价数据
nickel2015 = [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
# 月份缩写与索引映射,简化逻辑维护
month_mapping = {
    "jan": 0, "feb": 1, "mar": 2, "apr": 3,
    "may": 4, "jun": 5, "jul": 6, "aug": 7,
    "sep": 8, "oct": 9, "nov": 10, "dec": 11
}

year_input = input("请输入要查询的年份:").strip()

if "2015" in year_input:
    month_input = input("请输入月份缩写(如jan)或输入all查询所有月份:").strip().lower()
    
    # 查询所有月份数据
    if month_input == "all":
        print("2015年各月份镍价数据:")
        for month_num, price in enumerate(nickel2015, start=1):
            print(f"{month_num}月:{price}")
    # 查询单个月份数据
    elif month_input in month_mapping:
        idx = month_mapping[month_input]
        print(f"2015年{month_input}月镍价:{nickel2015[idx]}")
    # 处理无效输入
    else:
        print("输入无效,请输入正确的月份缩写或all")

关键优化点

  1. 用in替代find(),直接判断输入是否匹配目标值,逻辑更直观准确
  2. 新增month_mapping字典,替代重复的if判断,代码更简洁易维护
  3. 支持不区分大小写的输入(通过lower()转换),提升用户体验
  4. 明确区分单月份查询和全月份查询逻辑,符合需求预期
  5. 增加无效输入提示,避免程序无意义输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:43:12