如何在Python循环中返回主菜单且不终止程序?
解决Aria宠物店POS系统返回主菜单的问题
你已经找对方向啦!你的代码里已经用了while not done这个外层循环来维持主菜单的运行——只要不修改done的值或者直接终止程序,处理完每个选项后,程序会自动回到主菜单,根本不需要额外的“返回”操作。
现在的问题只是每个选项里的pass是占位符,你只需要把对应的功能逻辑填进去就行。比如处理「添加商品到购物车」(选项1)时,写完添加逻辑后,代码会自然执行到循环末尾,然后重新进入循环,再次显示主菜单。
我给你修改了代码,添了一些实用的示例功能,你可以参考:
done = False # 初始化购物车列表,方便后续操作 cart = [] while not done: print('=========================================') print(' Aria\'s Pet Store Point of Sale System') print('=========================================') print('[1] Add Products to Cart') print('[2] Remove Products to Cart') print('[3] View Cart') print('[4] Generate Receipt') print('[5] Logout') print('[6] Exit') print('=========================================') choice = input('Choice: ') if choice == '1': # 实现添加商品到购物车的逻辑 product_name = input("Enter product name: ").strip() try: quantity = int(input("Enter quantity: ").strip()) if quantity <= 0: print("Quantity must be a positive number!") else: cart.append({"name": product_name, "quantity": quantity}) print(f"✅ Added {quantity} x {product_name} to cart!") except ValueError: print("⚠️ Invalid quantity! Please enter a number.") # 无需额外操作,代码会自动回到循环开头显示主菜单 elif choice == '2': # 实现移除商品的逻辑 if not cart: print("🛒 Cart is empty, nothing to remove!") else: product_name = input("Enter product name to remove: ").strip() # 查找并移除购物车里的商品 for item in cart: if item["name"].lower() == product_name.lower(): cart.remove(item) print(f"❌ Removed {product_name} from cart!") break else: print(f"❌ {product_name} not found in cart!") elif choice == '3': # 实现查看购物车的逻辑 print("\n🛒 Current Cart:") if not cart: print(" Empty") else: for idx, item in enumerate(cart, 1): print(f" {idx}. {item['quantity']} x {item['name']}") print() # 空行分隔 elif choice == '4': # 实现生成收据的逻辑 if not cart: print("🛒 Cart is empty, can't generate receipt!") else: print("\n=========================================") print(" Aria's Pet Store Receipt") print("=========================================") print("Items:") total = 0 # 模拟商品价格映射,实际可以改成从数据库/配置读取 price_map = {"dog food": 15.99, "cat litter": 12.50, "fish tank": 49.99} for item in cart: price = price_map.get(item["name"].lower(), 9.99) # 默认价格9.99 subtotal = price * item["quantity"] total += subtotal print(f" {item['quantity']} x {item['name']} - ${subtotal:.2f}") print("-----------------------------------------") print(f"Total: ${total:.2f}") print("=========================================") print(" Thank you for shopping with us! 🐾") print() elif choice == '5': # 实现登出逻辑,比如清空购物车 cart.clear() print("👋 Logged out successfully! Cart has been cleared.") elif choice == '6': # 用更优雅的方式退出,替代直接exit() print("👋 Exiting the system... Have a nice day!") done = True else: print("⚠️ Invalid Input! Please enter a number from 1 to 6.")
核心关键点说明:
- 外层的
while not done循环是核心机制:只要done保持False,程序就会不断重复显示主菜单。 - 每个选项处理完成后,代码会执行到循环的末尾,然后自动回到循环开头,重新打印主菜单——完全不需要额外的“返回”语句。
- 选项6我改成了设置
done = True来终止循环,比直接调用exit(0)更符合Python的优雅风格,也方便后续扩展清理逻辑。
内容的提问来源于stack exchange,提问作者Arjay Abrenica
相关产品推荐
相关产品推荐

