输入正确颜色仍提示无效值?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!")
修复说明
- 存储颜色时统一转为小写,无论用户输入大写、混合大小写都能统一格式,避免匹配失败。
- 第二个循环中使用
user_input.lower()作为判断依据,确保用用户的实际输入去检查列表,而不是无效的未定义变量。
内容的提问来源于stack exchange,提问作者Bobby Cox
相关产品推荐
相关产品推荐

