Python 3.x点餐程序for循环未累加全部总价,仅计算最后一项商品总价的问题求助
Fixing Your Restaurant Order Total Calculation
Hey there! I see the issue with your order total—let’s break it down and fix it step by step.
What’s Going Wrong
- Resetting Totals Every Time: In your loop, every time you select one item, you’re setting all the other
totalXvariables to 0. For example, if you first order Macaroni Pizza (total1=30), then Garlic Bread, theelseclause fororder=="1"will set total1 back to 0. By the end of the loop, only the last item’s total has a value, others are 0. - Not Accumulating a Running Total: You’re trying to combine the
totalXvariables into a tuple at the end (total_price = total1, total2...) instead of adding them up. Even if the variables weren’t reset, this would just show a list of numbers, not the sum. - Overwriting Variables in the Loop: Each iteration of the loop reuses the same
totalXvariables, so previous order data gets lost.
Here’s the Fixed Code
Let’s simplify things with a dictionary to store menu items (makes the code cleaner) and use a single running total:
import sys print("Welcome to Terry's Restaurant!") # Store menu items in a dictionary for easier access menu = { "1": {"name": "Macaroni Pizza", "price": 15}, "2": {"name": "Garlic Bread", "price": 6}, "3": {"name": "Coca Cola", "price": 4}, "4": {"name": "Onion Rings", "price": 4}, "5": {"name": "Fries", "price": 4}, "0": {"name": "Cancel Order", "price": 0} } print("""Please choose items from : 1. Macaroni Pizza 2. Garlic Bread 3. Coca Cola 4. Onion Rings 5. Fries 0. To exit shop/cancel order""") # Initialize running total total_price = 0 num_items = int(input("Please enter 1-4 items to be ordered, type 0 to cancel order: ")) if num_items == 0: print("Cancelling Order. Thank you come again") sys.exit() for _ in range(num_items): while True: order = input("\nPlease enter your desired item using 1-5 (0 to cancel): ") if order in menu: break print("Please enter a valid item (1-5 or 0 to cancel)") if order == "0": print("Cancelling Order. Thank you come again") sys.exit() item = menu[order] quantity = int(input(f"How many would you like of {item['name']}? ")) item_total = quantity * item["price"] print(f"{quantity} {item['name']} ${item_total}") # Add this item's total to the running total total_price += item_total print(f"\nYour order total is ${total_price}")
Key Improvements
- Running Total: We start with
total_price = 0and add each item’s total to it every time an order is placed—no more losing previous values. - Menu Dictionary: This replaces all the repetitive
if-elseblocks, making the code easier to read and update (you can add new menu items just by updating the dictionary). - Input Validation: The
while Trueloop ensures the user enters a valid menu option before proceeding, so no more invalid input messages popping up incorrectly. - Cleaner Variable Usage: No more separate
total1,total2variables—we calculate each item’s total on the fly and add it to the main total.
Why Your Original Code Failed
Let’s recap with an example: if you ordered 2 Macaroni Pizza (total1=30) then 1 Garlic Bread:
- First loop: total1=30, total2-5=0
- Second loop: the
elsefororder=="1"sets total1=0, then total2=6 - At the end,
total_price = (0,6,0,0,0)—which is why you only saw the last item’s value.
With the fixed code, each item’s total gets added to total_price immediately, so you end up with 30+6=36 as the final total.
内容的提问来源于stack exchange,提问作者WRonin
相关产品推荐
相关产品推荐

