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

如何通过用户输入命令从列表选择指定项实现糖果袋选品功能

糖果袋手动选品功能实现方案

你可以按照「展示带编号的糖果列表-接收用户输入校验-存入用户糖果袋」的逻辑补全手动选糖分支,以下是可直接运行的修正版代码,同时修复了你原代码里的小问题:

import os
import random

customer_bag = []
# 修正原代码最后一项糖果的价格笔误:0,5 → 0.5
candy_types = [["Sour strings", 2], ["Red Racecars", 2], ["Raspberry Boats", 1], ["Banana Skids", 3], ["Jungle Roar", 1], ["The Oh no Candy", 0.5]]
candy_types.sort()

while True:
    os.system("cls")
    # 主菜单展示可选糖果
    print("=== 糖果店可选品类 ===")
    for idx, candy in enumerate(candy_types, start=1):
        print(f"{idx}. {candy[0]} | 售价:{candy[1]}")

    print("\n请选择服务:")
    menu_choice = int(input("1. 自主挑选糖果\n2. 随机生成糖果袋\n3. 退出\n输入对应编号:"))

    if menu_choice == 1:
        os.system("cls")
        customer_bag.clear()
        print("=== 自主选糖模式 ===")
        while True:
            # 展示当前已选糖果
            print("\n当前糖果袋内容:")
            if not customer_bag:
                print("* 空")
            else:
                for i, item in enumerate(customer_bag, start=1):
                    print(f"{i}. {item[0]}")
            # 展示可选列表
            print("\n可添加的糖果:")
            for idx, candy in enumerate(candy_types, start=1):
                print(f"{idx}. {candy[0]} | 售价:{candy[1]}")
            user_input = input("\n输入要添加的糖果编号,输入q结束选糖:")
            if user_input.lower() == 'q':
                break
            # 输入合法性校验
            if not user_input.isdigit():
                print("输入无效,请输入数字编号")
                input("按回车继续")
                os.system("cls")
                continue
            select_num = int(user_input)
            if select_num < 1 or select_num > len(candy_types):
                print(f"编号超出范围,请输入1到{len(candy_types)}之间的数字")
                input("按回车继续")
                os.system("cls")
                continue
            # 添加选中糖果到袋子
            picked = candy_types[select_num - 1]
            customer_bag.append(picked)
            print(f"已添加 {picked[0]} 到糖果袋")
            input("按回车继续")
            os.system("cls")
        # 选完展示最终糖果袋
        os.system("cls")
        print("=== 你的自定义糖果袋 ===")
        total_price = 0
        for item in customer_bag:
            print(f"- {item[0]} | 售价:{item[1]}")
            total_price += item[1]
        print(f"\n总价:{total_price}")
        input("\n按回车返回主菜单")

    elif menu_choice == 2:
        os.system("cls")
        print("=== 随机生成的糖果袋 ===")
        for _ in range(3):
            pick = random.choice(candy_types)
            print(f"- {pick[0]} | 售价:{pick[1]}")
        input("\n按回车返回主菜单")

    elif menu_choice == 3:
        break

核心实现逻辑说明

  • 用enumerate()给排序后的糖果列表生成从1开始的连续编号,匹配普通用户的输入习惯,取糖果时注意列表原生索引从0开始,需要把用户输入的编号减1再取值
  • 增加双层循环:外层循环常驻主菜单,选完糖果不需要重启程序;内层循环支持用户多次添加糖果,直到主动输入q结束选品
  • 加入输入校验逻辑,拦截非数字、超出列表范围的无效输入,避免程序直接报错崩溃
  • 选品过程中实时展示当前已选内容,交互逻辑更顺畅

内容的提问来源于stack exchange,提问作者Fenriz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:45:36