简体   繁体   English

如何解决代码中的 KeyError,我是初学者

[英]How can I solve a KeyError in my code, I'm a begginer

I'm resolving a basic problem consisting of make a list of products, the user choose the product and the amount of the product and the total price is printed.我正在解决一个基本问题,包括制作产品清单、用户选择产品和产品数量以及打印总价。 I get a keyerror in the line 22.我在第 22 行得到一个键错误。

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)

The error displayed is显示的错误是

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'

In this case I choose the product code "5".在这种情况下,我选择产品代码“5”。

When you use input it returns a string, not an integer.当您使用input它返回一个字符串,而不是一个整数。 You can see this because the error message shows '5' , not 5 .您可以看到这一点,因为错误消息显示'5' ,而不是5 The keys to your dictionary are integers, though, so the key you are providing in the statement ( code ) is not found.但是,字典的键是整数,因此找不到您在语句 ( code ) 中提供的键。 You could instead use你可以改用

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

A better format, at least in Python 3.6 and later, would be至少在 Python 3.6 及更高版本中,更好的格式是

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

for line 26, the problem is similar.对于第 26 行,问题类似。 Just convert to integers (or float, if there's a decimal point)只需转换为整数(或浮点数,如果有小数点)

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

or或者

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

input in python receives data as a string, you need to typecast it python中的input以字符串形式接收数据,您需要对其进行类型转换

it is something along:它是一些东西:

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

I think you should also follow the Python idiom EAFP (Easier to ask for forgiveness than permission) here when asking for user input as he could write literally everything but integers you expect:我认为在请求用户输入时,您还应该遵循 Python 习语EAFP(请求宽恕比许可更容易) ,因为他可以写除您期望的整数之外的所有内容:

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
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)

you need to take the input as integer because the input() take the default as a string so you can type it like quantify = int(input("Enter amount: ")) or another method is to use int() in the place where the calculations are like totalPrice = float(relation[int(code)] * int(quantify))您需要将输入作为 integer 因为 input() 将默认值作为字符串,因此您可以像 quantify quantify = int(input("Enter amount: "))或另一种方法是在该地方使用 int()其中计算类似于totalPrice = float(relation[int(code)] * int(quantify))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM