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

Python字符串转小写后条件判断失效问题求助

问题分析与解决方法

你的代码无法正常工作的核心原因是没有正确调用字符串的lower()方法:

user_input_lower = user_input.lower  # 错误:仅引用方法对象,未执行方法

lower是字符串类的内置方法,必须通过()调用才能返回转换后的小写字符串。上述代码只是把方法本身赋值给了user_input_lower,而非转换后的输入内容。因此user_input_lower本质是一个方法对象,永远无法与字符串列表main_colors中的元素匹配,导致所有输入都会进入else分支。

修正后的关键代码行:

user_input_lower = user_input.lower()  # 正确:调用方法得到小写字符串

额外优化建议:将main_colors的定义移到while True循环外部,避免每次循环重复创建相同列表,提升代码效率:

main_colors = ["cian", "amarillo", "magenta"]
while True:
    user_input = input("Introduce el color (en español): ")
    user_input_lower = user_input.lower()

    if user_input_lower in main_colors:
        print("Es un color primario\n")
    else:
        print("No es un color primario\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:04:52