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

Python公交票总价计算代码报错KeyError: '1',请求排查问题

公交票计费代码问题分析与解决

问题描述

需求:编写代码实现让用户输入所需公交票数量及单张票价,计算总费用。
提交的代码如下:

items = {
    "1 tickets" : 1.49, 
    "2 tickets" : 2.50, 
    "3 tickets" : 3.50, 
    "4 tickets" : 5.50, 
    "5 tickets" : 6.50, 
    "6 tickets" : 7.70
    }


shopping_cart = {}
total_cost = 0

while True:
    option = int(input("how much tickets would you like to buy: "))
    if option == 0: break

    elif option == 1: ticket = "1" 
    elif option == 2: ticket = "2"
    elif option == 3: ticket = "3" 
    elif option == 4: ticket = "4"
    elif option == 5: ticket = "5" 
    elif option == 6: ticket = "6"
    else:
        print("Not found")
        continue

    print(ticket)
    qnty = int(input("Enter the quantity: "))
    shopping_cart[ticket] = qnty

    total = qnty*items[ticket]
    total_cost += total
    print("The price for these ticket(s) is: " + str(total))
    print('The total price is: %.2f' % total_cost)
    

print("\nThe total price  is %.2f " % total_cost)
print("hope you have a good journey")

运行后持续出现如下报错:

Traceback (most recent call last):
  File "C:/Users/Home/Downloads/python.py", line 32, in <module>
    total = qnty*items[ticket]
KeyError: '1'

报错原因

出现KeyError: '1'的核心原因是字典键不匹配:

  • 你定义的items字典中,键是类似 "1 tickets" 这种包含空格和复数形式的字符串
  • 但代码中ticket变量赋值的是纯数字字符串(比如"1"),用这个值去items字典中查找键,自然找不到对应条目,触发键错误。

修复方案

有两种简单的修复方式,选其一即可:

方式一:修改ticket变量的赋值,匹配字典键

把每个elif分支里的ticket赋值改成和items字典键一致的格式:

elif option == 1: ticket = "1 tickets" 
elif option == 2: ticket = "2 tickets"
elif option == 3: ticket = "3 tickets" 
elif option == 4: ticket = "4 tickets"
elif option == 5: ticket = "5 tickets" 
elif option == 6: ticket = "6 tickets"

方式二:优化字典键为数字(更推荐)

直接把items字典的键改成整数,这样和输入的option类型一致,代码更简洁:

items = {
    1: 1.49, 
    2: 2.50, 
    3: 3.50, 
    4: 5.50, 
    5: 6.50, 
    6: 7.70
}

同时简化后续的ticket赋值逻辑,不用一堆elif,直接:

if 1 <= option <=6:
    ticket = option
else:
    print("Not found")
    continue

优化后的完整代码(方式二)

items = {
    1: 1.49, 
    2: 2.50, 
    3: 3.50, 
    4: 5.50, 
    5: 6.50, 
    6: 7.70
}

shopping_cart = {}
total_cost = 0

while True:
    try:
        option = int(input("请选择要购买的票种(1-6张,输入0结束):"))
        if option == 0:
            break
        if not 1 <= option <=6:
            print("无效选项,请输入1-6之间的数字")
            continue
        
        qnty = int(input("请输入购买数量:"))
        if qnty <=0:
            print("数量不能为负数或0")
            continue
        
        shopping_cart[option] = qnty
        current_total = qnty * items[option]
        total_cost += current_total
        print(f"该票种本次费用:{current_total:.2f}")
        print(f"当前累计总费用:{total_cost:.2f}")
    
    except ValueError:
        print("请输入有效的数字")

print(f"\n最终总费用:{total_cost:.2f}")
print("祝您旅途愉快")

优化点说明:

  • 改用数字键简化逻辑,去掉冗余的elif分支
  • 增加输入异常处理(比如输入非数字的情况)
  • 增加数量合法性校验(不能为负或0)
  • 改用f-string格式化输出,更简洁易读
  • 提示文字改为中文,更友好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:16:00