Search code examples
dictionaryfor-loopif-statementwhile-loopkey-value

PYTHON - How to update the counter by adding Dictionary values based on Input?


Created a Dictionary with 'items' as keys and 'prices' as values. Ask the user to input an item's name and print the corresponding price. When the user input second item, the price of second item is added to the price of first item and print the total price in the end. But here from my code I'm getting the price of only one item at a time. The counter is not updating the value ( Second item's price is not getting added to the First item's price.)

This is my code:

while True:
    # Make a dictionary of items with corresponding prices.
    items = {
                "banana": 1.00,
                "avocado": 2.50,
                "tomato": 1.00,
                "cabbage": 5.00,
                "cauliflower": 4.50,
                "salad bowl": 6.50,
                "spinach": 3.50,
                
            }      
    # Ask the user for item name
    item = input("Item: ").lower()
    
    # After each item display total cost of all items inputted thusfar.
    total = 0
    if item in items.keys():
        total += items[item]
        
    print(total)

And my Output is:

Item: banana
1.0
Item: avocado
2.5
Item: tomato
1.0
Item: 

Also tried this:

# After each item display total cost of all items inputted thus far.
    total = 0
    for key in items.keys():
        if item == key:
            total += items.get(item)
        
    print(total)

Output:

Item: banana
1.0
Item: banana
1.0
Item: avocado
2.5
Item: 

I want the 'total' to output the total of all the items inputted. For Ex- if I input 'banana' and 'banana' it should output 2.00 & if I enter 'banana' and 'avocado' the output should be 3.50. I want to use for loop and if statements only to solve the problem, still learning basics. Any help appreciated. Thanks in advance.


Solution

  • Define the items and total outside the loop. Also, add a condition to exit the infinite loop (for example let user just press Enter):

    # define item costs outside the loop:
    items = {
        "banana": 1.00,
        "avocado": 2.50,
        "tomato": 1.00,
        "cabbage": 5.00,
        "cauliflower": 4.50,
        "salad bowl": 6.50,
        "spinach": 3.50,
    }
    
    
    # define total cost outside the loop:
    total = 0
    
    while True:
        # Ask the user for item name
        item = input("Item (type just Enter for exit): ").lower()
        if not item:
            break
    
        total += items[item]
        print('Total cost so far:', total)
    

    Prints (for example):

    Item (type just Enter for exit): banana
    Total cost so far: 1.0
    Item (type just Enter for exit): avocado
    Total cost so far: 3.5
    Item (type just Enter for exit): tomato
    Total cost so far: 4.5
    Item (type just Enter for exit):