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

Python购物车程序执行操作后如何返回def menu菜单

购物车程序故障修复方案

现存问题定位

  • 菜单无法循环返回:首次读取用户选项后,循环内没有重新拉取新的用户输入,也没有重新打印菜单,程序会一直用第一次输入的选项值执行分支逻辑,比如首次选1就会无限重复添加商品的流程
  • 删除商品逻辑失效:当前代码用两个平行列表存储商品名(字符串类型)和价格,分支里写的item[new_item]是尝试对字符串做键索引,运行时会直接抛出类型错误;就算忽略报错,临时列表temp最终也没有赋值回原商品列表,也没有同步处理价格列表,删除操作完全不生效
  • 总价计算逻辑错误:同样错误地将字符串类型的商品名当成字典,尝试读取不存在的id/price/quantity字段会直接报错;总价打印语句写在内层循环里,且格式化占位符写死为0,无法输出正确计算结果
  • 分支判断逻辑冲突:所有功能分支都用独立if判断,无效选项的判断条件写为option >=5,会和退出选项5冲突,还会出现多分支同时执行的逻辑穿透问题

修正后完整代码

保持原有双平行列表的存储逻辑,不额外重构数据结构,方便对照原有代码理解:

cart_items = []
price_items = []

print("Welcome to the Shopping Cart Program!")
print()

def menu():
        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Remove an item of the shopping cart")
        print("4. Compute total of the items in the shopping cart")
        print("5. Quit")

def display_content():
    for i in range(0, len(cart_items)):
        print(f"{cart_items[i]} - ${price_items[i]:.2f}")

menu()
option = int(input("Please, enter an action: "))

while option != 5:
    if option == 1:
        new_item = input("What item would you like to add? ")
        price_item = float(input(f"What is the price of the {new_item}? "))
        cart_items.append(new_item)
        price_items.append(price_item)
        print(f"{new_item} has been added to the cart.")
    elif option == 2:
        print("The content of the shopping cart are:")
        display_content()
    elif option == 3:
        remove_item = input("Which item would you like to remove? ")
        if remove_item in cart_items:
            item_idx = cart_items.index(remove_item)
            cart_items.pop(item_idx)
            price_items.pop(item_idx)
            print(f"{remove_item} has been removed from the cart.")
        else:
            print("Item not found in cart.")
    elif option == 4:
        total = sum(price_items)
        print(f'The total price of the items in the shopping cart is ${total:.2f}')
    else:
        print("Invalid option, please, try again.")
    
    # 每次操作完成后回到菜单
    print()
    menu()
    option = int(input("Please, enter an action: "))

print("Thank you for using the shopping cart program. Good bye!")

关键修改说明

  • 把原来独立的if分支改成if/elif/else结构,避免多分支同时执行的穿透问题,无效选项统一放到else分支处理,不会和退出选项冲突
  • 在while循环末尾补上和你之前简易版本一致的「打印菜单+读取新选项」逻辑,执行完任意操作后都会回到菜单选择环节,解决无限卡单功能的问题
  • 重写删除商品逻辑:先判断待删除商品是否存在,找到对应索引后同步从商品名列表、价格列表中删除对应位置的元素,避免类型错误
  • 简化总价计算逻辑:直接对价格列表求和即可,不需要多余的嵌套循环,输出时保留两位小数符合日常价格显示习惯
  • 修复了商品展示、总价打印时的格式错误

内容的提问来源于stack exchange,提问作者Víctor Martínez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:09:20