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

如何强制用户输入正确数据?while循环校验混凝土类型问题求助

问题修复方案

代码存在的核心问题

  • get_type函数无返回值,调用后无法获取有效输入
  • 循环判断用硬编码列表,未使用从CSV读取的list_of_types
  • 缩进不规范,部分逻辑语句缩进错误
  • 文件读取未使用上下文管理器,存在资源泄漏风险

修正后的完整代码

读取CSV并构建类型列表

import csv

# 使用with语句安全读取CSV文件,自动管理文件资源
with open('prices.csv', 'r') as f:
    reader = csv.reader(f)
    prices = {}
    for row in reader:
        # 处理空行或格式异常的行,避免报错
        if len(row) >= 2:
            k, v = row[0].strip(), row[1].strip()
            prices[k] = v
list_of_types = list(prices.keys())

获取用户输入的函数

def get_type(list_of_types):
    # 打印可用混凝土类型列表
    print("\n")
    print("list of available concrete types:")
    print(" ________________________________________")
    print(list_of_types)
    print(" ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾")

    # 循环获取有效输入,直到用户输入正确类型
    while True:
        user_input = input("Please enter the type of a concrete: ").lower().strip()
        if user_input in list_of_types:
            return user_input
        print("Sorry, that's not a valid concrete type. Please try again.")

# 调用函数获取用户选择的类型
selected_type = get_type(list_of_types)
print(f"You selected: {selected_type}")

关键修改说明

  1. 添加返回值:函数最后通过return user_input返回有效输入,确保调用方能获取结果
  2. 匹配动态类型列表:将判断条件改为user_input in list_of_types,和CSV读取的类型保持一致
  3. 简化循环逻辑:用while True无限循环,直到输入有效才跳出并返回
  4. 输入预处理:给输入增加.strip(),避免用户输入前后空格导致匹配失败
  5. 安全文件操作:使用with语句自动关闭文件,避免资源泄漏
  6. 异常行处理:增加CSV行长度检查,防止空行或格式错误导致程序崩溃
  7. 修正提示语:把模糊的提示改为明确的无效类型提示,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:25:14