调用分区选择函数后代码终止,如何实现超市购物流程循环?
问题解决思路
你的程序存在两个核心问题:
find_section_choice函数没有返回选中的分区数据,导致后续代码无法获取有效的section_choice变量- 输入"back"调用函数后直接break退出循环,没有重新进入产品展示的流程
修复后的代码示例
import items_and_section # 初始化购物车用列表存储,比字符串更方便管理 cart = [] def find_section_choice(): # 先展示所有可选分区 print("Available sections:", ", ".join(items_and_section.sections.keys())) while True: user_choice = input("Pick a section: ").strip() # 验证输入的分区是否存在 if user_choice in items_and_section.sections: # 返回选中分区对应的产品字典 return items_and_section.sections[user_choice], user_choice else: print("Invalid section name, try again.") # 外层循环控制整体流程:选分区→操作产品→返回选分区 while True: # 获取选中的分区产品和分区名称 section_choice, section_name = find_section_choice() print(f'\nWelcome to the {section_name} section. What do you want to add to cart?') print("*Type 'back' to return to section selection*") print("*Type 'cart' to check your cart*") # 展示当前分区的产品和价格 for product, price in section_choice.items(): print(f'{product}: ${price}') # 产品选择的内层循环 while True: product_choice = input("> ").strip().lower() if product_choice == "back": # 跳出内层产品循环,回到外层的分区选择环节 break elif product_choice == "cart": # 展示购物车,为空时提示 print(f'Your cart: {", ".join(cart) if cart else "Empty"}') elif product_choice in section_choice: cart.append(product_choice) print(f'{product_choice} added to cart successfully') else: print("This product isn't in this section, try another one.")
关键修改说明
- 让
find_section_choice函数返回选中的分区产品字典和分区名称,确保后续代码能拿到有效数据 - 增加外层循环,实现「选分区→操作产品→返回选分区」的循环逻辑,解决调用函数后直接退出的问题
- 把购物车改成列表存储,比字符串拼接更便于管理商品
- 增加输入验证:检查分区、产品是否存在,同时处理大小写问题(比如输入"Back"也能识别)
- 优化购物车展示逻辑,为空时给出明确提示
注:假设你的items_and_section模块结构如下(可根据实际情况调整):
# items_and_section.py sections = { "Fruit": {"Apple": 1.99, "Banana": 0.99}, "Vegetable": {"Carrot": 0.59, "Tomato": 1.29}, "Snack": {"Chips": 2.49, "Candy": 1.49} }
内容的提问来源于stack exchange,提问作者Captain_Wiz08
相关产品推荐
相关产品推荐

