Python 在这个if语句中,当我在原始输入中键入no时,它将通过yes部分。我怎么修理它?

Python 在这个if语句中,当我在原始输入中键入no时,它将通过yes部分。我怎么修理它?,python,python-2.7,Python,Python 2.7,当我在终端的输入中键入no时。它通过if选项==“yes”部分。 我想让它通过另一个。请帮忙 choice=raw_input("Will you help us? Yes or no?") if choice == "yes" or "Yes": print "Yeah! You are a hero!" name = raw_input("What is your name?") print "Alright, " + str(name) + " ,let's go

当我在终端的输入中键入no时。它通过if选项==“yes”部分。 我想让它通过另一个。请帮忙

choice=raw_input("Will you help us? Yes or no?")

if choice == "yes" or "Yes":
    print "Yeah! You are a hero!"
    name = raw_input("What is your name?")
    print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."

else:
    print "You're a coward. :("
    quit()
怎么了

choice=raw_input("Will you help us? Yes or no?")

if choice == "yes" or choice == "Yes":
    print "Yeah! You are a hero!"
    name = raw_input("What is your name?")
    print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."

else:
    print "You're a coward. :("
    quit()
以上是正确的格式。您没有正确设置逻辑。注意以下几点:

a = 1
if a == 2 or 3 :
    print 'OK'
它打印“OK”。为什么?


原因是python值是以从左到右的方式计算的。如果任何值为true,则返回该值。但是,如果所有值都为false,则返回最后一个值,在您的示例中为“Yes”。据我所知,这就是造成你问题的原因。您基本上需要两个“或”条件,而不是一个……

错误在这行代码中:

if choice == "yes" or "Yes":
Python将此视为两个条件的“或”:

if (choice == "yes") or ("Yes"):
这与:

if (choice == "yes") or True:
因为非空字符串总是True。 这最终归结为:

if True:
as“or”与True的匹配总是计算为True

这将为您提供所需的结果:

if choice == "yes" or choice == "Yes":
但是,这被认为是C风格,比较多个值的python方法是:

if choice in ("yes", "Yes"):
但在本例中,您只需要进行不区分大小写的匹配。因此,正确的方法是:

if choice.lower() == "yes":

这甚至可以处理“是”或“是”等输入中的奇怪大写字母。

谢谢,这很有效,但在我说“不”之后,它又问了一个问题,这对我来说很好。但它仍然问了一个问题,我不知道出了什么问题。它仍然问输入twice@Mariba请用当前代码发布新问题。