I have a question for Python Dictionary

Asked 2 years ago, Updated 2 years ago, 86 views

dic={}

for i in range(0,5):
    a = input('product name:')
    price = input('price:')
    dic[a] = price
print(dic)

for i in dic:
    sangpum = input ("product to be purchased: ")

    if sangpum in dic:
        print(dic[price])

    else:
        print(sangpum+" has no/!")
        break

This is the code I made. I want to print out the price of each product when I print it out in the if section, but I think it's fixed at the last input value.

line 13, in <module>
    print(dic[price])
KeyError: '4500' 

This error appears.

python dictionary

2022-09-20 16:28

2 Answers

It must be dic[sangpum].


2022-09-20 16:28

There is a way to use sum, but I just added it because was annoying.

dic={}

for i in range(0,5):
    a = input('product name:')
    price = int(input('price:')
    dic[a] = price
print(dic)

total_price = 0
while True:
    sangpum = input ("product to purchase: ")
    if sangpum in dic:
        total_price += dic[sangpum]
        print(dic[sangpum])
    else:
        print(sangpum+" has no/!")
        print(total_price)
        break


2022-09-20 16:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.