python 2.7 链接条件 If Else 不工作。怎么了?
python 2.7 chained conditions If Else not working. What's wrong?
我不明白为什么以下内容不起作用。
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer == "Yes":
print "Yes indeed!"
elif answer == "yes" or "y":
print "Oh yeah!"
elif answer == "No":
print "No it isn't!"
elif answer == "no" or "n":
print "Not really!"
else:
print "Say what?"
当我删除 或 时,它确实有效。我做错了什么?
-编辑-
我已经有了,非常感谢!
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer in "Yes":
print "Yes indeed!"
elif answer in ("yes", "y"):
print "Oh yeah!"
elif answer in "No":
print "No it isn't!"
elif answer in ("no", "n"):
print "Not really!"
else:
print "Say what?"
我看到的一个问题是:
elif answer == "yes" or "y":
字面翻译为 "if answer is yes or True",结果始终为 True。
你可以这样写:
elif answer in ("yes", "y"):
elif answer == "yes" or answer == "y":
elif answer == "No" or answer == "n":
使用 elif answer == "yes" or "y":
等。你基本上是在检查 if bool("n")
而不是比较 answer
是否等于 "n"
所以你的陈述将始终评估为 True:
任何非空字符串的计算结果总是为真:
In [38]: bool("n")
Out[38]: True
In [39]: bool("y")
Out[39]: True
In [40]: bool("")
Out[40]: False
如果要检查多个值,也可以使用 in 来测试成员资格:
elif answer in {"yes", "y"}:
改变这个:
answer == "Yes" or "y"
至:
answer == "Yes" or answer == "y"
甚至:
answer in ("Yes", "y")
我不明白为什么以下内容不起作用。
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer == "Yes":
print "Yes indeed!"
elif answer == "yes" or "y":
print "Oh yeah!"
elif answer == "No":
print "No it isn't!"
elif answer == "no" or "n":
print "Not really!"
else:
print "Say what?"
当我删除 或 时,它确实有效。我做错了什么?
-编辑- 我已经有了,非常感谢!
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer in "Yes":
print "Yes indeed!"
elif answer in ("yes", "y"):
print "Oh yeah!"
elif answer in "No":
print "No it isn't!"
elif answer in ("no", "n"):
print "Not really!"
else:
print "Say what?"
我看到的一个问题是:
elif answer == "yes" or "y":
字面翻译为 "if answer is yes or True",结果始终为 True。
你可以这样写:
elif answer in ("yes", "y"):
elif answer == "yes" or answer == "y":
elif answer == "No" or answer == "n":
使用 elif answer == "yes" or "y":
等。你基本上是在检查 if bool("n")
而不是比较 answer
是否等于 "n"
所以你的陈述将始终评估为 True:
任何非空字符串的计算结果总是为真:
In [38]: bool("n")
Out[38]: True
In [39]: bool("y")
Out[39]: True
In [40]: bool("")
Out[40]: False
如果要检查多个值,也可以使用 in 来测试成员资格:
elif answer in {"yes", "y"}:
改变这个:
answer == "Yes" or "y"
至:
answer == "Yes" or answer == "y"
甚至:
answer in ("Yes", "y")