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

输入正确颜色仍提示无效值?Python代码问题排查

问题原因与修复方案

核心错误点

你的代码存在两个关键问题,导致输入正确颜色仍会触发错误提示:

  • 未使用用户输入做判断:第二个循环里的判断条件写的是if green in colors_list:,这里的green是未定义的变量(没有加引号,Python会将其视为变量名而非字符串),完全没用到用户输入的user_input。
  • 大小写不兼容:第一个循环中用户输入的颜色是原样存入列表的,若第二个循环输入时大小写与列表内的不一致(比如列表里是"Green",输入"green"),就会匹配失败。

修复后的代码

colors_list = []

while True:
    user_input = input("Enter a color to add to the list(or type 'done' to finish): ")
    if user_input.lower() == 'done':
        break
    # 统一转小写存入,消除大小写差异
    colors_list.append(user_input.lower())

    print('Here is the list:')
    print(colors_list)

while True:
    user_input = input("Enter a color:")
    # 用用户输入的小写版本匹配列表内容
    if user_input.lower() in colors_list:
        print('Yes!', user_input, 'is in the list')
        break
    else:
        print("You didn't give me a valid value, please try again!")

修复说明

  1. 存储颜色时统一转为小写,无论用户输入大写、混合大小写都能统一格式,避免匹配失败。
  2. 第二个循环中使用user_input.lower()作为判断依据,确保用用户的实际输入去检查列表,而不是无效的未定义变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:45:59