Python购物车程序无法删除列表指定索引元素问题排查
Python购物车程序问题修复
首先明确:你代码里的list.append()使用没有问题,添加商品模块能正常运行已经验证了这部分逻辑的正确性。你遇到的核心问题集中在移除商品模块,另外还有几处可以优化的代码写法,具体如下:
移除商品模块的核心错误
- 变量引用错误:你接收用户输入的商品序号存在
num变量中,但后续判断、删除操作都误用了其他逻辑块里的临时变量i,完全没有用到用户输入的值 - 索引规则不匹配:展示商品时你用
enumerate(list, start=1)生成了从1开始的用户端序号,但Python列表原生索引是从0开始计数的,直接用用户输入的序号调用pop()会出现错位 - 判断逻辑错误:
i in list是判断某个元素值是否存在于列表中,你实际需要校验的是用户输入的序号是否在「1到当前购物车商品总数」的合法区间内 - 变量覆盖错误:
list.pop(i)的返回值是被删除的单个元素,你将这个返回值重新赋值给存储列表的list变量,会直接把原列表覆盖为单个值,后续所有列表操作都会触发报错 - 数据不同步:你将商品名称、价格分别存在
list和costs两个平行列表中,删除商品时没有同步删除costs对应位置的价格,后续计算总价会出现数值错误 - 边界场景缺失:没有处理购物车为空时的移除请求,会直接触发索引越界错误
其他可优化的点
- 不要用
list作为变量名:list是Python内置的列表类型关键字,作为自定义变量名会覆盖内置能力,容易触发隐性bug,建议改名为cart - 查看购物车的空判断可以移到循环外,不需要在每次遍历商品时重复判断列表是否为空
修正后可直接运行的完整代码
a = True cart = [] # 替换原list变量名,避免覆盖内置类 costs = [] while a == True: print('Select from the following list:\n1. Add Item\n2. View Cart\n3. Remove Item\n4. Compute Total\n5. Quit') choice = int(input('Please enter a number: ')) print() if choice == 1: item = input('What item would you like to add? ').capitalize() cost = float(input(f'What is the cost of the {item}? ')) print(f'{item} has been added to cart.\n') cart.append(f'{item} ${cost:.2f}') costs.append(cost) elif choice == 2: if len(cart) == 0: print('The Cart is Empty\n') else: # 自动对齐序号显示宽度 line = "{{: >{}}}. {{}}\n".format(len(str(len(cart)))) for i, item in enumerate(cart, start=1): print(line.format(i, item), end='') print() elif choice == 3: # 提前处理空购物车场景 if len(cart) == 0: print('The Cart is Empty, cannot remove items\n') continue print('Which item would you like to remove?') num = int(input()) # 校验用户输入的序号是否在合法范围 if 1 <= num <= len(cart): # 转换为列表0基索引 del_index = num - 1 # 同步删除商品和对应价格,不要给原列表变量重新赋值 cart.pop(del_index) costs.pop(del_index) print('Item Removed\n') else: print('Invalid Input\n') elif choice == 4: total = sum(costs) print(f'Your total is ${total:.2f}\n') elif choice == 5: print('Thank you for playing.') a = False
内容的提问来源于stack exchange,提问作者tNashm
相关产品推荐
相关产品推荐

