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

如何在输入无效时触发错误并重启循环?现有Python代码无法生效

问题分析与修复方案

原代码没法触发错误重启循环,核心问题有三个:

  • str(input(...))不管输入啥都不会抛出ValueError,所以except ValueError永远不会执行
  • 没有对输入的颜色做合法性校验,随便输入乱码都会直接进入else分支跳出循环
  • 字典里的键重复了(两个color2),会导致第一个颜色数据被覆盖

修正后的代码

while True:
    try:
        color1 = input("What should the color of the broken window be, Purple or Sky Blue? > ").lower().strip()
        # 校验color1是否在允许的选项里,不符合就抛错
        if color1 not in ["purple", "sky blue"]:
            raise ValueError("Invalid color for first window")
        
        color2 = input("What should the color of the broken window be, White, Yellow or Pink? > ").lower().strip()
        # 校验color2是否合法
        if color2 not in ["white", "yellow", "pink"]:
            raise ValueError("Invalid color for second window")
        
        user_info = {"color1": color1, "color2": color2}
    except ValueError:
        print("Choose a valid input please...")
        continue
    else:
        break

# 可选:输出最终选择的颜色
print("Your selected colors:", user_info)

关键修改点

  • 去掉多余的str():input()本身返回的就是字符串,没必要再转换
  • 增加颜色合法性校验:用in判断输入是否在指定列表里,不符合就主动抛出ValueError
  • 修正字典重复键的问题:把第一个键改成color1,避免数据被覆盖
  • 修正第二个输入提示的语法错误:调整为White, Yellow or Pink,语义更清晰

现在只要输入不在指定颜色范围内,就会触发ValueError,程序打印提示后重启循环,直到输入合法才跳出循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:20:20