Python 如果x的分支==";";或;否";总是跑

Python 如果x的分支==";";或;否";总是跑,python,if-statement,syntax,or-operator,Python,If Statement,Syntax,Or Operator,可能重复: 当我在我的程序中运行这个选项时,问题会通过,但是无论答案是什么,“否”选项总是运行。如果我切换选项顺序,“Y”选项将只运行,它将始终直接启动。我肯定我错过了一些简单的东西,我只是不知道是什么 infoconf = raw_input("Is this information correct? Y/N: ") if infoconf == "N" or "No": print "Please try again." elif infoconf ==

可能重复:

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

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

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

现在,
infoconf==“N”
可能是真的,也可能不是真的,但是
“No”
是“某物”,当作为逻辑变量处理时,计算结果为真。实际上,您的条件
infoconf==“N”或true
将始终为true


正如许多其他人所建议的,在第二个逻辑术语中将
infoconf
中的“No”
进行比较就可以了

我个人会这样做:

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”表示否。在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."
正如其他人所说,
如果infoconf==“N”或“No”
等同于
如果(infoconf==“N”)或“No”
,并且由于
“No”
(作为非空字符串)的计算结果为True,因此该语句将始终为True


另外,为了减少对输入的挑剔,您可能希望在进行测试之前先执行
infoconf=infoconf.strip().lower()
(然后与小写版本进行比较)。

x==a或b
相当于
(x==a)或b
。使用
x==a或x==b
获得所需的结果。重复项太多..或较短的版本:
如果infoconf处于(“N”,“No”):
请参阅我的更新答案。希望这不会让你再困惑了。