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

while循环输入验证异常:符合条件输入仍提示错误求排查

问题排查与修复

问题根源

你的代码中Number_List定义在while循环外部,每次输入不合法值后,后续输入的内容会被追加到列表中,导致验证逻辑始终读取第一次输入的前三个元素。比如:

  1. 第一次输入5 6 7,列表变为[5,6,7],验证不通过;
  2. 第二次输入9 10 11,列表变为[5,6,7,9,10,11],此时判断Number_List[0]还是5(小于8),所以依然触发错误提示。

修复后的代码

while (True):
    Number_List = []  # 每次循环重置为空列表,仅保留当前输入
    try:
        Number_List.extend(map(int, input("Enter the length, width, and height of the room: ").split()))
    except ValueError:
        print("\nIncorrect Input. \nPlease try again. \n")
        continue

    # 额外判断:确保输入了三个数值(可选,避免输入少于/多于三个数的情况)
    if len(Number_List) != 3:
        print("\nIncorrect Input. Please enter exactly three integers. \nPlease try again. \n")
        continue

    if (Number_List[0] < 8) or (Number_List[1] < 8) or (Number_List[2] < 8):
        print("\nIncorrect Input. \nPlease try again. \n")
        continue
    else:
        break

关键修改说明

  • 将Number_List = []移到while循环内部,每次循环都会重新创建空列表,确保只处理当前一次的输入内容,不会被之前的错误输入干扰。
  • 新增了输入数量验证(可选),避免用户输入少于或多于三个数值的情况,让验证逻辑更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:08:18