Python中not in操作符使用问题:原色输入错误提示异常
问题描述
我想要实现仅当输入不是原色(red、blue、yellow)时显示错误提示,但当前代码无论输入内容是什么,都会针对第一个和第二个颜色显示错误提示。我已尝试使用not in []和布尔值(color1 = False),问题仍未解决,相关代码如下:
color1 = input("Enter your first color (red, blue, yellow):").lower() color2 = input("Enter your second color (red, blue, yellow):").lower() if (color1 == "red" and color2 == "blue") or (color1 == "blue" and color2 == "red"): print("Your result is purple") elif (color1 == "red" and color2 == "yellow") or (color1 == "yellow" and color2 == "red"): print("Your result is orange") elif (color1 == "blue" and color2 == "yellow") or (color1 == "yellow" and color2 == "blue"): print("Your result is green") if color1 not in ["red" "blue" or "yellow"]: print("Error: The first color you entered is invalid.") elif color2 not in ["red" "blue" or "yellow"]: print("Error: The second color you entered is invalid.") elif color1 == color2: print("Error: The two colors you entered are the same.")
问题分析与修复
核心问题点
- 列表语法错误:
["red" "blue" or "yellow"]是无效写法。字符串之间必须用逗号分隔,且or不能放在列表内部,正确的原色列表应为["red", "blue", "yellow"]。原写法会导致Python解析逻辑混乱,使not in判断永远为真,因此无论输入什么都会触发错误提示。 - 逻辑判断顺序错误:错误判断使用
elif会导致,若第一个颜色有效则直接跳过第二个颜色的无效检查;颜色相同的判断放在最后,也会被前面的elif逻辑跳过,无法正常触发。
修正后的代码
# 定义原色列表,避免重复编写 primary_colors = ["red", "blue", "yellow"] color1 = input("Enter your first color (red, blue, yellow):").lower() color2 = input("Enter your second color (red, blue, yellow):").lower() # 先处理所有错误情况 is_valid = True if color1 not in primary_colors: print("Error: The first color you entered is invalid.") is_valid = False if color2 not in primary_colors: print("Error: The second color you entered is invalid.") is_valid = False if color1 == color2: print("Error: The two colors you entered are the same.") is_valid = False # 仅当输入完全有效时,执行颜色混合逻辑 if is_valid: if (color1 == "red" and color2 == "blue") or (color1 == "blue" and color2 == "red"): print("Your result is purple") elif (color1 == "red" and color2 == "yellow") or (color1 == "yellow" and color2 == "red"): print("Your result is orange") elif (color1 == "blue" and color2 == "yellow") or (color1 == "yellow" and color2 == "blue"): print("Your result is green")
修复说明
- 提取
primary_colors统一管理原色列表,提升代码可读性和维护性。 - 独立判断每个错误条件,确保所有无效输入都能被检测并提示。
- 用
is_valid标记输入状态,仅在输入完全合法时才执行颜色混合逻辑,避免无效输入进入正常流程。
内容的提问来源于stack exchange,提问作者Becca
相关产品推荐
相关产品推荐

