【问题标题】:If Statement and while loopIf 语句和 while 循环
【发布时间】:2013-06-09 07:28:21
【问题描述】:

我是一名自学成才的程序员,我刚开始使用 python。当我执行这段代码时,我遇到了一点问题:

x = 0
while x == 0:
  question = raw_input("Would you like a hint? ")
  if question == "y" or "yes":
    print "Ok"
    first.give_hint("Look over there")
    x = 1
  elif question == "n" or "no":
    print "Ok"
    x = 1
  else:
    print "I'm Sorry, I don't understand that"

您知道,first.give_hint("Look over there") 是在程序早期的一个类中定义的,我只是为了空间而省略了这部分。当我运行程序时,无论我输入什么,我都会得到第一个案例“往那边看”,我一直在试图找出问题所在,但我就是不明白。如果你们能帮助我,我将不胜感激。

【问题讨论】:

  • 除了答案,还可以考虑if question.lower() in ["y", "yes"]:
  • 是的,这就是“防弹”方式。

标签: python loops if-statement while-loop


【解决方案1】:

问题出在这一行:

if question == "y" or "yes":

"yes" 将始终评估为 True。

你真正想要的是:

if question == "y" or question == "yes":

必须对其他条件进行类似的更改。

【讨论】:

    【解决方案2】:

    你的 if 语句有误,应该是:

    if (question == "y") or (question == "yes"):
        print "Ok"
    

    解释:

    (question == "y" or "yes")
    

    相当于:

    (question == "y" or "yes" != 0)    # operator 'or' having the prevalence
    

    "yes" 字符串不为空,("yes" != 0) 始终返回 True,您的整个原始条件也是如此。

    【讨论】:

      【解决方案3】:

      条件错误。您有question == "y" 和一个逻辑or,字符串"yes" 始终为True。这就是为什么它每次都会评估第一个案例。

      尝试改成if question[0] == 'y'

      【讨论】:

        猜你喜欢
        • 2016-01-12
        • 2012-06-18
        • 2015-05-19
        • 1970-01-01
        • 2014-01-21
        • 2015-11-08
        • 2016-02-13
        • 2017-01-15
        • 1970-01-01
        相关资源
        最近更新 更多