if-branch for x ==“N”或“No”始终运行

时间:2013-01-16 02:14:14

标签: python if-statement syntax or-operator

  

可能重复:
  Why does `letter==“A” or “a”` always evaluate to True?

当我在我的程序中运行它时,问题就会出现,但无论答案如何,“No”选项始终会运行。如果我切换选项顺序,“Y”选项将仅运行,它将始终直接启动。我确定我错过了一些简单的东西,我只是不知道是什么。

infoconf = raw_input("Is this information correct? Y/N: ")

    if infoconf == "N" or "No":
        print "Please try again."
    elif infoconf == "Y" or "Yes":
        start()
    else:
        print "That is not a yes or no answer, please try again."

4 个答案:

答案 0 :(得分:3)

原来是

infoconf = raw_input("Is this information correct? Y/N: ")

#you wrote:  infoconf == "N" or "No" but should be:
if infoconf == "N" or infoconf == "No": 
  print "Please try again."
#you wrote: infoconf == "Y" or "Yes" but should be
elif infoconf == "Y" or infoconf == "Yes": 
  start()
else:
  print "That is not a yes or no answer, please try again."

简短说明:

when value of x = 'N'
x == 'N' or 'No' will return True
when value of x = 'Y'
x == 'N' or 'No' will return 'No' i believe this is not what you want

在另一边

when value of x = 'N'
x == 'N' or x == 'No' will return True
when value of x = 'Y'
x == 'N' or x == 'No' will return False i believe this is what you want

答案 1 :(得分:2)

Python会以不同于您的想法来解释infoconf == "N" or "No"。这有点是“运算符优先级”的情况,其中您的条件被解析为(infoconf == "N") or ("No")

现在,infoconf == "N"可能是也可能不是,但"No"是“某事”,当被视为逻辑时,评估为真。实际上,您的条件infoconf == "N" or true将始终为真。

正如许多其他人所建议的那样,在第二个逻辑术语中比较infoconf"No"就行了。

答案 2 :(得分:1)

就个人而言,我会做这样的事情:

infoconf = raw_input("Is this information correct? Y/N: ")

if infoconf.lower().startswith('n'):
   # No
elif infoconf.lower().startswith('y'):
   # Yes
else:
   # Invalid

这意味着用户可以回答“Y / y / yes / yeah”为“是”,“N / n / no / nah”为“否”。

答案 3 :(得分:1)

在Python中,这样做更容易:

infoconf = raw_input("Is this information correct? Y/N: ")

if infoconf in ["N", "No"]:
    print "Please try again."
elif infoconf in ["Y", "Yes"]:
    start()
else:
    print "That is not a yes or no answer, please try again."

正如其他人所说,if infoconf == "N" or "No"if (infoconf == "N") or "No"是等价的,并且由于"No"(作为非空字符串)的计算结果为True,因此该语句将始终为真。

另外,为了对输入稍微挑剔,你可能希望在进行测试之前做infoconf = infoconf.strip().lower()(然后与小写版本进行比较)。