while循环输入验证异常:符合条件输入仍提示错误求排查
问题排查与修复
问题根源
你的代码中Number_List定义在while循环外部,每次输入不合法值后,后续输入的内容会被追加到列表中,导致验证逻辑始终读取第一次输入的前三个元素。比如:
- 第一次输入
5 6 7,列表变为[5,6,7],验证不通过; - 第二次输入
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
相关产品推荐
相关产品推荐

