【问题标题】:How can I solve a KeyError in my code, I'm a begginer如何解决代码中的 KeyError,我是初学者
【发布时间】:2019-07-19 00:56:45
【问题描述】:

我正在解决一个基本问题,包括制作产品清单、用户选择产品和产品数量以及打印总价。我在第 22 行得到一个 keyerror。

def main():
   print("Choose a product: ")
    print("")
    print("Products: ")
    print("")
    print("Samsung Galaxy S10+.............1")
    print("Samsung Galaxy S10..............2")
    print("OnePlus 7 Pro...................3")
    print("OnePlus 7.......................4")
    print("OnePlus 6t......................5")
    print("Huawei P30 Pro..................6")
    print("Huawei Mate 20 Pro..............7")
    print("Google Pixel 3XL................8")
    print("Gooogle Pixel 3A XL.............9")
    print("Oppo Reno 10x Zooom............10")
    print("")

    relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}

    code = input("Enter the product code: ")
    print("")
    print("The price is $", relation[code])
    quantify = input("Enter amount: ")
    print("")

    totalPrice = float(relation[code] * quantify)

    print("The total price is: $", totalPrice)

显示的错误是

Traceback (most recent call last):
  File "main.py", line 30, in <module>
    main()
  File "main.py", line 22, in main
    print("The price is $", relation[code])
KeyError: '5'

在这种情况下,我选择产品代码“5”。

【问题讨论】:

  • int(input("Enter amount: "))input 函数返回一个字符串,但您的字典键是整数。

标签: python python-3.x keyerror


【解决方案1】:

当你使用input 时,它返回一个字符串,而不是一个整数。您可以看到这一点,因为错误消息显示'5',而不是5。但是,您的字典的键是整数,因此找不到您在语句 (code) 中提供的键。 你可以改用

print("The price is $", relation[int(code)])

至少在 Python 3.6 及更高版本中,更好的格式是

print(f"The price is ${relation[int(code)]}")

对于第 26 行,问题类似。只需转换为整数(或浮点数,如果有小数点)

totalPrice = float(relation[int(code)] * int(quantify))

totalPrice = relation[int(code)] * float(quantify)

【讨论】:

  • 我解决了第 22 行的问题,但现在我在第 26 行遇到了同样的问题 (keyerror) :(
  • 非常感谢您的帮助
【解决方案2】:

input在python中接收数据为字符串,需要进行类型转换

这是一起的东西:

print("The price is $", relation[int(code)])

【讨论】:

    【解决方案3】:

    我认为在询问用户输入时,您还应该在此处遵循 Python 习惯用法EAFP (Easier to ask for forgiveness than permission),因为他可以写除您期望的整数之外的所有内容:

    while True:
        code = input("Enter the product code: ")
    
        try:
            price = relation[int(code)]
        except (ValueError, KeyError):
            print("Error: Incorrect code value, try again!")
        else:
            break
    

    【讨论】:

      【解决方案4】:
      def main():
          print("Choose a product: ")
          print("")
          print("Products: ")
          print("")
          print("Samsung Galaxy S10+.............1")
          print("Samsung Galaxy S10..............2")
          print("OnePlus 7 Pro...................3")
          print("OnePlus 7.......................4")
          print("OnePlus 6t......................5")
          print("Huawei P30 Pro..................6")
          print("Huawei Mate 20 Pro..............7")
          print("Google Pixel 3XL................8")
          print("Gooogle Pixel 3A XL.............9")
          print("Oppo Reno 10x Zooom............10")
          print("")
      
          relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
      
         code = input("Enter the product code: ")
         print("")
         print("The price is $", relation[code])
         quantify = input("Enter amount: ")
         print("")
      
         totalPrice = float(relation[int(code)] * quantify)
      
         print("The total price is: $", totalPrice)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-21
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 2022-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多