0

可能重复:
为什么 `letter==“A” 或 “a”` 总是评估为 True?

当我在我的程序中运行它时,问题会通过,但是无论答案如何,“否”选项总是会运行。如果我切换选项顺序,“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

4 回答 4

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
于 2013-01-16T02:18:27.933 回答
2

Python 的解释infoconf == "N" or "No"与你想象的不同。这在某种程度上是“运算符优先级”的情况,您的条件被解析为(infoconf == "N") or ("No").

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

正如许多其他人所建议的那样,与您的第二个逻辑术语进行比较就可以了infoconf"No"

于 2013-01-16T02:38:07.603 回答
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”表示否。

于 2013-01-16T02:41:26.927 回答
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()在进行测试之前执行此操作(然后与小写版本进行比较)。

于 2013-01-16T02:53:08.603 回答