【发布时间】: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