You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python购物车菜单重复打印问题求助:无效输入时重复输出菜单

Python购物车菜单重复显示问题修复

问题描述

我编写的Python购物车代码存在问题:当输入非菜单选项的无效字符时,程序会重复打印整个菜单,而预期仅需提示用户重新选择选项,无需重复输出菜单。

测试输入

John John
Febuary 1, 2016
o
q

预期输出

Enter customer's name:
Enter today's date:

Customer Name: John John
Today's Date: Febuary 1, 2016
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
Choose an option:
Choose an option:

实际输出

Enter customer's name:
Enter today's date:

Customer name: John Doe
Today's date: February 1, 2016

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:

我的代码

class ItemToPurchase:

    def __init__(self, item_name='none', item_description='none', item_price=0, item_quantity=0):
        self.item_name = item_name
        self.item_description = item_description
        self.item_price = item_price
        self.item_quantity = item_quantity

    def print_item_description(self):
        print(f'{self.item_name}: {self.item_description}')


class ShoppingCart:
    def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=None):
        if cart_items is None:
            cart_items = []
        self.customer_name = customer_name
        self.current_date = current_date
        self.cart_items = cart_items

    def add_item(self, purchased_item):
        self.cart_items.append(purchased_item)

    def remove_item(self, target_item):
        for stuff in self.cart_items:
            if stuff.item_name == target_item:
                self.cart_items.remove(stuff)
            else:
                print('Item not found in cart. Nothing modified.')

    def modify_item(self, item_modify):
        for stuff in self.cart_items:
            if stuff.item.item_name == item_modify.item_name:
                stuff.item_quantity = item_modify.item_quantity
                break
        else:
            print('Item not found in cart. Nothing modified')

    def get_num_items_in_cart(self):
        number_of_items = sum(stuff.item_quantity for stuff in self.cart_items)
        return number_of_items

    def get_cost_of_cart(self):
        cart_cost = 0
        for cart_item in self.cart_items:
            cost_of_item = cart_item.item_price * cart_item.item_quantity
            cart_cost += cost_of_item

        return cart_cost

    def print_total(self):
        print(f"{self.customer_name}'s Shopping Cart - {self.current_date}")
        print("Number of Items: ", self.get_num_items_in_cart())

        if len(self.cart_items) == 0:
            print("SHOPPING CART IS EMPTY")
        else:
            for stuff in self.cart_items:
                stuff.print_item_cost()
                total = stuff.item_price * stuff.item_quantity
                print(f'{stuff.item_name} {stuff.item_quantity} @ ${stuff.item_price} = ${total}')
            print(f"{self.get_cost_of_cart()}")

    def print_description(self):
        print(f"{self.customer_name}'s Shopping Cart - {self.current_date}\nItem Descriptions")
        for stuff in self.cart_items:
            print(f"{stuff.item_name}: {stuff.item_description}")


if __name__ == "__main__":
    name_of_customer = input("Enter customer's name:\n")
    date_of_today = input("Enter today's date:\n")
    print(f"\nCustomer name: {name_of_customer}")
    print(f"Today's date: {date_of_today}\n")
    s_cart = ShoppingCart(name_of_customer, date_of_today)


    def print_menu(shop_cart):
        user_option = ''
        while user_option not in ['a', 'r', 'c', 'i', 'o', 'q']:
            print("MENU")
            print('a - Add item to cart')
            print('r - Remove item from cart')
            print('c - Change item quantity')
            print("i - Output items' descriptions")
            print("o - Output shopping cart")
            print("q - Quit\n")

            user_option = input("Choose an option:\n")

        if user_option == 'a':
            print("ADD ITEM TO CART")
            added_item_name = input("Enter the item name:\n")
            added_description = input("Enter the item description:\n")
            added_item_price = int(input('Enter the item price:\n'))
            added_item_quantity = int(input("Enter the item quantity:\n"))

            new_item = ItemToPurchase(added_item_name, added_description, added_item_price, added_item_quantity)
            shop_cart.add_item(new_item)

        elif user_option == 'r':
            remove_item_name = input("Enter name of item to remove:")
            shop_cart.remove_item(remove_item_name)
        elif user_option == 'c':
            changed_name = input("Enter the item name:\n")
            change_quantity = int(input("Enter the new quantity"))
            changed_item = ItemToPurchase(changed_name, '', 0, change_quantity)
            shop_cart.modify_item(changed_item)
        elif user_option == 'i':
            shop_cart.print_description()
        elif user_option == 'o':
            shop_cart.print_total()
        elif user_option == 'q':
            quit()

    print_menu(s_cart)

修复方向

核心问题原因

当前代码将菜单打印逻辑放在了输入验证循环内部,每次用户输入无效选项时,循环都会重新执行菜单打印代码,导致菜单重复显示。同时,print_menu函数仅执行一次,处理完一个有效选项后就退出,无法持续响应用户操作。

具体修复步骤

  1. 分离菜单打印与输入循环:仅在程序启动时打印一次完整菜单,后续无效输入只提示重新选择。
  2. 重构循环逻辑:让菜单持续运行直到用户选择q退出,循环内仅处理输入验证和操作执行。
  3. 修复辅助方法的逻辑漏洞:
    • remove_item方法:原代码遍历删除元素会导致漏检,且多次提示未找到,改为遍历一次找到后删除,否则仅提示一次。
    • modify_item方法:原代码错误访问stuff.item.item_name,改为直接访问stuff.item_name,无需创建新的ItemToPurchase对象。
    • print_total方法:删除未定义的print_item_cost调用。

修复后的关键代码示例

def print_menu(shop_cart):
    # 仅打印一次完整菜单
    print("MENU")
    print('a - Add item to cart')
    print('r - Remove item from cart')
    print('c - Change item quantity')
    print("i - Output items' descriptions")
    print("o - Output shopping cart")
    print("q - Quit\n")
    
    while True:
        user_option = input("Choose an option:\n")
        if user_option in ['a', 'r', 'c', 'i', 'o', 'q']:
            # 处理有效选项
            if user_option == 'a':
                print("ADD ITEM TO CART")
                added_item_name = input("Enter the item name:\n")
                added_description = input("Enter the item description:\n")
                added_item_price = int(input('Enter the item price:\n'))
                added_item_quantity = int(input("Enter the item quantity:\n"))
                new_item = ItemToPurchase(added_item_name, added_description, added_item_price, added_item_quantity)
                shop_cart.add_item(new_item)
            elif user_option == 'r':
                remove_item_name = input("Enter name of item to remove: ")
                found = False
                for idx, item in enumerate(shop_cart.cart_items):
                    if item.item_name == remove_item_name:
                        del shop_cart.cart_items[idx]
                        found = True
                        break
                if not found:
                    print('Item not found in cart. Nothing modified.')
            elif user_option == 'c':
                changed_name = input("Enter the item name:\n")
                change_quantity = int(input("Enter the new quantity: "))
                found = False
                for item in shop_cart.cart_items:
                    if item.item_name == changed_name:
                        item.item_quantity = change_quantity
                        found = True
                        break
                if not found:
                    print('Item not found in cart. Nothing modified')
            elif user_option == 'i':
                shop_cart.print_description()
            elif user_option == 'o':
                shop_cart.print_total()
            elif user_option == 'q':
                return  # 退出菜单循环
        else:
            # 无效选项,仅重新提示输入,不重复打印菜单
            continue

内容的提问来源于stack exchange,提问作者BlackRose_94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 02:07:03