KnowledgeBoat Logo
|

Computer Science

Write a program that repeatedly asks the user to enter product names and prices. Store all of these in a dictionary whose keys are the product names and whose values are the prices.

When the user is done entering products and prices, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in the dictionary.

Python

Python Dictionaries

20 Likes

Answer

d = {}
ans = "y"
while ans == "y" or ans == "Y" :
    p_name = input("Enter the product name: ")
    p_price = float(input("Enter product price: "))
    d[p_name] = p_price
    ans = input("Do you want to enter more product names? (y/n): ")

ans = "y"
while ans == "y" or ans == "Y" : 
    p_name = input("Enter the product name to search: ")
    print("Price:", d.get(p_name, "Product not found"))
    ans = input("Do you want to know price of more products? (y/n): ")

Output

Enter the product name: apple
Enter product price: 165.76
Do you want to enter more product names? (y/n): y
Enter the product name: banana
Enter product price: 75
Do you want to enter more product names? (y/n): y
Enter the product name: guava
Enter product price: 48.5
Do you want to enter more product names? (y/n): n
Enter the product name to search: apple
Price: 165.76
Do you want to know price of more products? (y/n): y
Enter the product name to search: tomato
Price: Product not found
Do you want to know price of more products? (y/n): n

Answered By

6 Likes


Related Questions