how to keep adding the value of an item?

Question:

menu = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00
}

while True:
    # keep adding to the price if user prompts another item
    # i know the operation won't work its just what i want to happen
    try:
        x = input("Item: ")
        y = 0
        if x in menu:
            z = x + y
            print(f"Total: ${z}")
    # If u want to ctrl+d out and get ur price
    except (EOFError):
        print(f"Total: ${menu[x]}")
        break
    # so code can handle wrong inputs
    except (KeyError):
        pass

can’t find a way to make items add up

Asked By: omen

||

Answers:

Define a total outside and increment that value.

menu = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00
}

total = 0.0
while True:
    try:
        x = input("Item: ")
        if x in menu:
             total += menu[x]   # Notice that you're just adding the menu item price here
             print(f"Total: ${total}")
...
Answered By: Chrispresso

Things you need to do:

  1. Define a variable for storing total outside the loop otherwise the variable will be overridden everytime
  2. Get the price from the menu dictionary and add it to the total

If both changes are done, the code should look something like this

total = 0
while True:
    try:
        x = input("Item: ")
        if x in menu:
             total = total + menu[x]
             print(f"Total: ${total}")
    # If u want to ctrl+d out and get ur price
    except (EOFError):
        print(f"Total: ${menu[x]}")
        break
    # so code can handle wrong inputs
    except (KeyError):
        pass
Answered By: KingWealth
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.