Python 为什么代码总是执行第一个if条件?

Python 为什么代码总是执行第一个if条件?,python,if-statement,expression,Python,If Statement,Expression,我还在试验if、elif和else。我不明白为什么第一个if条件被执行,即使你没有选择蓝色作为你最喜欢的颜色 我尝试更改缩进,但总是出现语法错误 color = input("Whats your favorite color?\n") if color == 'blue' or 'Blue': print("Blue is a great color") print(f"{color} is your favorite color") elif color == 'yello

我还在试验if、elif和else。我不明白为什么第一个if条件被执行,即使你没有选择蓝色作为你最喜欢的颜色

我尝试更改缩进,但总是出现语法错误

color = input("Whats your favorite color?\n")

if color == 'blue' or 'Blue':
    print("Blue is a great color")
    print(f"{color} is your favorite color")
elif color == 'yellow' or 'Yellow':
    print(f"{color} is your color")
    print("Yellow is awesome!")
else:
    print("Choose something")
例如,当我输入随机字母“sdfd”时,我应该得到“选择真实颜色”的结果,而不是 蓝色是很好的颜色 sdfd是您最喜欢的颜色

这是因为
if-color=='blue'或'blue':
类似于
if(color=='blue')或('blue'):

'Blue'
是一个非空字符串,其计算结果为
True


如果在['Blue','Blue']中使用颜色,您可以执行
或者更好的操作:
如果color.lower()='Blue':
您的测试条件有一个错误。如果颜色='blue'或'blue':,则不应这样做:

if color == 'blue' or color == 'Blue':
这应该行得通!(别忘了也更改其他条件!) 最终结果应该是:

color = input("Whats your favorite color?\n")

if color == 'blue' or color == 'Blue':
    print("Blue is a great color")
    print(f"{color} is your favorite color")
elif color == 'yellow' or color == 'Yellow':
    print(f"{color} is your color")
    print("Yellow is awesome!")
else:
    print("Choose something")

对于本例,使用text方法可能更容易

可以正确地表示为:

if color.lower() == 'blue':
如果有人输入“蓝色”或“蓝色”,这也会捕获


这将更易于阅读和调试。

一般答案

对于Python中任何带有多个条件的if…else语句,每个条件都必须显式且清晰地声明。因此,使用
if color==“blue”或“blue”
语句,您没有清楚地说明这两个条件。第一部分,
如果color==“blue”
是完全正确的,但是,在or比较器之后,您必须完整地陈述下一个条件

代码应该如下所示:
如果颜色='blue'或颜色='blue':

可能的改进:


您还可以通过在代码中合并.upper()、.title()和其他各种字符串来实现字符串操作,从而改进这一点。这将帮助您减少if…else语句中的条件数

如果颜色=='blue'或color=='blue':Python将您的代码解释为
如果颜色=='blue'或'blue':
如果(颜色=='blue')或('blue'):,其中字符串“blue”(非空)被认为是正确的。@blorgbeard非常感谢您语法错误
color==“蓝色”或color==“蓝色”
if color.lower()==“蓝色”:
非常感谢。信息量很大,太好了!非常感谢。吹毛求疵:“可以简化为”并不准确。“可以正确地表达为”更像它。@Blorgbeard-我同意-更新答案,谢谢
if color.lower() == 'blue':