Python购物订单功能异常:商品匹配与循环逻辑问题排查
Python购物下单函数异常问题排查与修复
问题背景
实现了用于顾客购物的place_order函数,从groceries_list.txt读取商品列表供用户选购。预期逻辑:
- 提示用户输入商品名称
- 检查商品是否存在于文件行中:
- 存在则执行购物流程
- 不存在则提示
Product not in list
但实际运行结果与预期完全相反,出现两类异常:
异常情况
- 空输入异常:用户输入为空时,未进入不存在分支,反而匹配所有商品行,自动执行购物流程直到遍历完所有商品,累计所有商品价格,并将
['','','','']写入order_list_c.txt - 正确输入异常:输入列表中存在的商品时,会多次输出
Product not in list;选择继续购物后,无法累计多次选购的总价,仅将最后一次选购的商品写入order_list_c.txt
完整函数代码
def place_order(): try: fileHandler= open('groceries_list.txt','r') except: print('File cannot be opened.') exit() gro=fileHandler.readlines() if len(gro) == 0: print("Sorry! There are no groceries in our store yet.") else: repeat = True while repeat == True: try: fo= open('groceries_list.txt') fr= fo.readlines() except: print('File cannot be read.') order_list=[] total=0 view_gro() # 假设该函数用于展示商品列表 ################################################################# product= input('Please enter groceries name you want to purchase: ').upper() for line in fr: line= line.rstrip() if product in line: print(line) line=line.split(",") print('The price for',product,'is RM',str(line[3])) line[3]= float(line[3]) total=total+line[3] order_list.append(product) print('Product successful added to you shopping cart!') again= input('Do you need anything else? YES for continue or NO for quit.').upper() if again == 'YES': continue elif again == 'NO': print("Here's your shopping cart item") print(order_list) print('Total amount for your purchasing is RM',total) try: while True: pay=int(input('You pay: RM ')) balance= total-pay if balance == 0: print('Pay successfully! Thanks for your purchasing') fw= open('order_list_c.txt','w') fw.write(str(order_list)) fw.write('\n') fw.close() repeat=False break else: print('Pay unsuccessfully! Please try again.') continue except ValueError: print('Please enter numeric proper amount.') continue else: print('Please enter YES or NO') print('==============================') continue else: print('Product not in list.') continue fo.close() fileHandler.close()
商品列表文件内容(groceries_list.txt)
['FOOD', 'vege', 2022, 40.0, 'fresh'] ['CANDY', 'mentos', 2030, 10.0, 'sweet'] ['BEVERAGES', 'sprite', 2025, 50.0, 'sweet'] ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy']
空输入异常输出
['FOOD', 'vege', 2022, 40.0, 'fresh'] ['CANDY', 'mentos', 2030, 10.0, 'sweet'] ['BEVERAGES', 'sprite', 2025, 50.0, 'sweet'] ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy'] Please enter groceries name you want to purchase: ['FOOD', 'vege', 2022, 40.0, 'fresh'] The price for is RM 40.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.no Here's your shopping cart item [''] Total amount for your purchasing is RM 40.0 You pay: RM 40 Pay successfully! Thanks for your purchasing ['CANDY', 'mentos', 2030, 10.0, 'sweet'] The price for is RM 10.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.no Here's your shopping cart item ['', ''] Total amount for your purchasing is RM 50.0 You pay: RM 50 Pay successfully! Thanks for your purchasing ['BEVERAGES', 'sprite', 2025, 50.0, 'sweet'] The price for is RM 50.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.no Here's your shopping cart item ['', '', ''] Total amount for your purchasing is RM 100.0 You pay: RM 100 Pay successfully! Thanks for your purchasing ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy'] The price for is RM 300.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.no Here's your shopping cart item ['', '', '', ''] Total amount for your purchasing is RM 400.0 You pay: RM 400 Pay successfully! Thanks for your purchasing
正确输入异常输出
['FOOD', 'vege', 2022, 40.0, 'fresh'] ['CANDY', 'mentos', 2030, 10.0, 'sweet'] ['BEVERAGES', 'sprite', 2025, 50.0, 'sweet'] ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy'] Please enter groceries name you want to purchase: candy Product not in list. ['CANDY', 'mentos', 2030, 10.0, 'sweet'] The price for CANDY is RM 10.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.yes Product not in list. Product not in list. ['FOOD', 'vege', 2022, 40.0, 'fresh'] ['CANDY', 'mentos', 2030, 10.0, 'sweet'] ['BEVERAGES', 'sprite', 2025, 50.0, 'sweet'] ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy'] Please enter groceries name you want to purchase: pills Product not in list. Product not in list. Product not in list. ['MEDICINE', 'PILLS', 2030, 300.0, 'allergy'] The price for PILLS is RM 300.0 Product successful added to you shopping cart! Do you need anything else? YES for continue or NO for quit.no Here's your shopping cart item ['PILLS'] Total amount for your purchasing is RM 300.0 You pay: RM 300 Pay successfully! Thanks for your purchasing
问题分析
- 空输入异常原因:空字符串
''会匹配任何字符串,因此遍历商品行时,所有行都会触发if product in line条件,导致每个商品都被加入购物车。 - 正确输入异常原因:
- 遍历所有商品行时,每遇到不匹配的行就会输出
Product not in list,而非只在所有行都不匹配时提示一次; order_list和total在while repeat == True循环内初始化,每次继续购物都会重置这两个变量,导致无法累计之前的选购记录;continue关键字使用错误:在again == 'YES'时执行continue,会继续遍历剩余的商品行,而非重新进入下一轮购物输入。
- 遍历所有商品行时,每遇到不匹配的行就会输出
修复后的代码
def place_order(): try: fileHandler = open('groceries_list.txt', 'r') except: print('File cannot be opened.') exit() gro = fileHandler.readlines() fileHandler.close() # 提前关闭文件,避免资源占用 if len(gro) == 0: print("Sorry! There are no groceries in our store yet.") return repeat = True order_list = [] total = 0 while repeat: try: with open('groceries_list.txt') as fo: fr = fo.readlines() except: print('File cannot be read.') return view_gro() # 假设该函数用于展示商品列表 product = input('Please enter groceries name you want to purchase: ').strip().upper() # 处理空输入 if not product: print('Product not in list.') continue product_found = False for line in fr: line = line.strip() if not line: continue # 解析商品行,提取商品名称(假设第二个元素是商品名) try: item = eval(line) item_name = item[1].upper() if product == item_name: product_found = True print(line) price = float(item[3]) print(f'The price for {product} is RM {price}') total += price order_list.append(product) print('Product successfully added to your shopping cart!') break except: print('Invalid product format in file.') continue if not product_found: print('Product not in list.') continue # 询问是否继续购物 while True: again = input('Do you need anything else? YES for continue or NO for quit.').strip().upper() if again == 'YES': break elif again == 'NO': print("Here's your shopping cart item") print(order_list) print(f'Total amount for your purchasing is RM {total}') # 支付流程 while True: try: pay = float(input('You pay: RM ')) balance = total - pay if balance == 0: print('Pay successfully! Thanks for your purchasing') with open('order_list_c.txt', 'w') as fw: fw.write(str(order_list)) fw.write('\n') repeat = False break elif balance < 0: print(f'Your change is RM {-balance}. Pay successfully! Thanks for your purchasing') with open('order_list_c.txt', 'w') as fw: fw.write(str(order_list)) fw.write('\n') repeat = False break else: print('Pay unsuccessfully! Please pay enough amount.') except ValueError: print('Please enter numeric proper amount.') break else: print('Please enter YES or NO') print('==============================')
修复说明
- 空输入处理:提前判断输入是否为空,直接提示不存在;
- 商品匹配逻辑优化:解析每行商品,精确匹配商品名称(而非模糊匹配字符串),避免误判;
- 累计变量初始化调整:将
order_list和total移到while循环外,确保多次购物能累计记录; - 提示逻辑修正:仅在遍历完所有商品都未找到时,才输出一次
Product not in list; - 资源管理优化:使用
with语句自动管理文件打开/关闭,避免资源泄漏; - 支付逻辑完善:支持超额支付并找零,提升用户体验;
- 错误处理增强:增加商品行格式异常的处理,提升代码健壮性。
内容的提问来源于stack exchange,提问作者W C
相关产品推荐
相关产品推荐

