Python If / Else 语句未按预期工作

Python If / Else statement not working as expected

input1 = raw_input("").lower()
if input1 == "no":
    print "no"
if input1 == "yes":
    print "yes"
else:
    print "nothing"

这是我遇到的问题的简化版本,我知道它为什么会发生,但不知道如何解决它,也不知道该寻找什么。每次除了最后一个 if 语句是 运行 它总是打印 else 以及它。

示例:如果我将 'no' 放入其中,它会打印 'no' 和 'nothing',但如果输入 'yes',它只会打印 'yes'。

您有两个if条件。第二个应该是 elif。改变你的

if input1 == "yes":

elif input1 == "yes":

你有一个 if 与一个 if/else 分开;第一个测试可以通过,第二个测试仍然执行(如果失败则执行 else 条件)。将测试更改为:

if input1 == "no":
    print "no"
elif input1 == "yes":  # <-- Changed if to elif so if input1 == "no" we don't get here
    print "yes"
else:
    print "nothing"

你的原始代码的英文描述是"If input1 equals 'no', then print 'no'. If input1 equals 'yes', print 'yes', but if it's not equal 'yes', print 'nothing'." 注意这两句话是怎么断开的;是否打印 nothingno.

的测试无关

旁注:您可以稍微简化此代码:

if input1 in ("no", "yes"):
    print input1
else:
    print "nothing"

这完全避免了这个问题(当然,你的真实代码可能更复杂,所以你不能使用这个技巧)。

你有两个单独的 if 语句。所以代码会检查input1是否等于"no",然后每次都会检查是否等于"yes"。如果你把它改成这样:

  input1 = raw_input("").lower()
  if input1 == "no":
    print "no"
  elif input1 == "yes":
    print "yes"
  else:
    print "nothing"

然后这将是一条语句,首先检查 'no',如果为假,它将检查 'yes',最后,如果为假,它将打印 'nothing'.