Prompting user for multiple items and calculating total cost in Python

108 views Asked by At

I'm working on a Python program that allows users to place an order by inputting items, one per line, until they press Ctrl+D to end their input. After each input, I want to display the total cost of all items inputted once the user presses Ctrl+D, with a dollar sign ($) prefix and formatted to two decimal places. The user's input should be case-insensitive, and I want to ignore any input that is not a valid item from a predefined menu.Here's a simplified version of my code:

food_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
    }

cost = []

while True:
    try:
        item = input("Item: ").title()
        if item in food_menu:
            cost.append(food_menu\[item\])
        else:
            continue
    except EOFError:
        print()
        break

total = sum(cost)
print("Total: $", f"{total:.2f}", sep="")

The issue I'm facing is that if I want to input multiple instances of the same item, such as "taco", "taco" and "quesadilla," I have to press Enter after each item and then when I'm prompted for the fourth time I'm able to press Ctrl+D and get the total amount. Ideally, I would like to be able to input "taco", "taco" and "quesadilla" with just two enters and one Ctrl+D, i.e. I'm only prompted thrice and use Ctrl-D instead of thrid 'enter'. How can I modify my code to achieve this behavior?

1

There are 1 answers

2
DTNGNR On

Here is my attempt for the script:

  • The input can now contain multiple items (separated with spaces)
  • Partial matching - as long as it only matches one item on the list (i.E. "Bo" for "Bowls")
  • Matching of uppercase letters (i.e.: TS for "Tortilla Salad")
  • Added "exit" for ending the script without Ctrl+D
import re

# Get the Uppercase characters of a string (i.E.: "Tortilla Salad" => "TS")
def getUpperChars(string):
    return "".join([char for char in string if char.isupper()]).upper()

food_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
}

cost = []
loop = True
while loop:
    try:
        items = input("Enter items from the menu (separated by blanks) (or 'exit' to quit): ")

        # Split at \s but don't split at "Super"
        entered_items = re.split(r'(?<!Super)\s', items)

        for item in entered_items:
            uppercase_match = [key for key in food_menu if (item == getUpperChars(key))]
            matching_keys = [key for key in food_menu if (item.lower() in key.lower())]
            
            if item.lower() == "exit":
                loop = False
                break
            elif item.title() in food_menu:
                chosen_item = item.title()
            elif len(uppercase_match) == 1:
                chosen_item = uppercase_match[0]
            elif len(matching_keys) == 1:
                chosen_item = matching_keys[0]
            else:
                print("Invalid item. Please try again.")
                print(f"The keys containing '{item}': {matching_keys}")
                continue

            cost.append(food_menu[chosen_item])
            print(f"Added {chosen_item} for {food_menu[chosen_item]} to the list.")
    except EOFError:
        print()
        break
    
total_cost = sum(cost)
print(f"\nTotal: ${total_cost:.2f}")

When entered taco taco quesadilla the result is:

Added Taco for 3.0 to the list.
Added Taco for 3.0 to the list.
Added Quesadilla for 8.5 to the list.

Total: $14.50