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

Python初学者运行车辆分类统计代码出现KeyError报错求助

报错原因与修复方案

核心报错原因

  • 键的大小写不匹配:你在统计计数时调用了cartype.lower()将用户输入的车型编码转为小写后作为字典的键,比如用户输入S,实际存储的键是小写的's',但你取值时使用的是大写的'S',字典中没有对应键就触发了KeyError。
  • 未处理缺失键场景:如果没有用户输入过某一类车型,这个类型的键不会被添加到字典中,哪怕大小写匹配,直接取值依然会报错。
  • 额外语法错误:原代码中cartype_count[S]里的S没有加引号,会被Python识别为未定义的变量而非字符串键,会额外触发NameError。

修复后的代码

def cartypes():
    cartype_count = {}
    while True:
        car_name = input("Enter a Car Manufacturer and Model: ")
        cartype = input("What type is it (S)UV, (SE)DAN, (M)INI-VAN, (P)ICK-UP, or (O)THER? ")
        cartype_key = cartype.lower()
        if cartype_key not in cartype_count:
            cartype_count[cartype_key] = 1
        else:
            cartype_count[cartype_key] += 1
        add_or_not = input("Do you want to add more cars (Y/N)? ")
        if add_or_not.lower() == "n":
            break
    
    print("There were", cartype_count.get('s', 0), "SUVs.")
    print("There were", cartype_count.get('se', 0), "SEDANs.")
    print("There were", cartype_count.get('m', 0), "MINI-VANs.")
    print("There were", cartype_count.get('p', 0), "PICK-UPs.")
    print("There were", cartype_count.get('o', 0), "cars that were neither SUVs, SEDANs, MINI-VANs, nor PICKUPs.")

cartypes()

改动说明

  • 存储时提前把转小写的键赋值给变量,避免重复调用lower()方法
  • 取值时改用字典.get(键, 默认值)的写法,键不存在时直接返回0,不会触发报错
  • 统一使用小写字符串作为键,和存储逻辑对齐
  • 移除了print语句中多余的大括号,避免把数值包成无意义的集合

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:06:02