简体   繁体   中英

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.

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".

When you use input it returns a string, not an integer. You can see this because the error message shows '5' , not 5 . The keys to your dictionary are integers, though, so the key you are providing in the statement ( code ) is not found. You could instead use

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

A better format, at least in Python 3.6 and later, would be

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

for line 26, the problem is similar. 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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