input1 = raw_input("").lower()
if input1 == "no":
print "no"
if input1 == "yes":
print "yes"
else:
print "nothing"
这是我遇到的问题的简化版本,我知道它为什么会发生,但不知道如何解决它,或者寻找什么。每次运行除最后一个if语句之外的任何内容时,它总是会打印else
。
示例:如果我在其中输入'no',则会打印'no'和'nothing',但如果输入'yes',则只打印'yes'。
答案 0 :(得分:3)
你有两个单独的if语句。因此代码将检查input1是否等于“no”,然后每次检查它是否等于“是”。如果你改成它:
input1 = raw_input("").lower()
if input1 == "no":
print "no"
elif input1 == "yes":
print "yes"
else:
print "nothing"
然后它将是一个首先检查'no'的语句,如果是'false',它将检查'yes',最后,如果为false,它将打印'nothing'。
答案 1 :(得分:1)
您有一个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"
原始代码的英文描述是“如果input1等于'no',则打印'no'。如果input1等于'yes',则打印'yes',但如果它不等于'yes',则打印'nothing' “。注意这两个句子是如何断开的;是否打印nothing
与no
的测试无关。
旁注:你可以稍微简化一下这段代码:
if input1 in ("no", "yes"):
print input1
else:
print "nothing"
完全避免了这个问题(当然,你的真实代码可能更复杂,所以你不能使用这个技巧)。
答案 2 :(得分:0)