【问题标题】:Python if statement doesn't work as expectedPython if 语句没有按预期工作
【发布时间】:2011-11-29 05:51:20
【问题描述】:

我目前有代码:

fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or 2:
    print "You failed to run away!"
elif fleechance == 4 or 3:
    print "You got away safely!"

fleechance 不断打印为 3 或 4,但我继续得到结果“你逃跑失败!” ,谁能告诉我为什么会这样?

【问题讨论】:

  • 这不等同于if fleechance == 1 or fleechance == 2。这相当于说if fleechance ==1: if 2,这将永远为真,因为if 2 为真。
  • 你用的是什么 Python 教程?你在哪里见过这样的代码?你能提供一个喜欢或参考吗?这段代码很糟糕,重要的是要知道你从哪里得到它可能有意义的想法。
  • 我有一本书,但是我没有直接从那里得到代码,只是看起来它可以工作,所以我认为这不是教程的错。跨度>

标签: python printing random if-statement


【解决方案1】:

试试

if fleechance == 1 or fleechance == 2:
    print "You failed to run away!"
elif fleechance == 4 or fleechance == 3:
    print "You got away safely!"

或者,如果这些是唯一的可能性,你可以这样做

if fleechance <= 2:
    print "You failed to run away!"
else:
    print "You got away safely!"

【讨论】:

    【解决方案2】:

    表达式fleechance == 1 or 2 等价于(fleechance == 1) or (2)。数字 2 始终被认为是“真实的”。

    试试这个:

    if fleechance in (1, 2):
    

    编辑:在您的情况下(只有两种可能性),以下情况会更好:

    if fleechance <= 2:
        print "You failed to run away!"
    else:
        print "You got away safely!"
    

    【讨论】:

      【解决方案3】:

      您编写 if 语句的方式是错误的。 你告诉python检查fleechance等于1是真的还是2是真的。 非零整数在某个条件下始终表示为真。 你应该写:

      fleechance = random.randrange(1,5)
      print fleechance
      if fleechance == 1 or fleechance == 2:
          print "You failed to run away!"
      elif fleechance == 4 or fleechance == 3:
          print "You got away safely!"
      

      【讨论】:

        【解决方案4】:

        因为你不是在问fleechance 是1 还是fleechance 是2;你问是否

        1. fleechance 为 1,或
        2. 2 非零。

        当然,条件的第二部分始终为真。试试

        if fleechance == 1 or fleechance == 2:
            ...
        

        【讨论】:

        • 感谢您的进一步解释,以后我会尽量不犯同样的错误。
        【解决方案5】:

        if 语句按设计工作,问题是操作顺序导致此代码执行您想要的操作。

        最简单的解决方法是:

        if fleechance == 1 or fleechance == 2:
            print "You failed to run away!"
        elif fleechance == 3 or fleechance == 4:
            print "You got away safely!"
        

        【讨论】:

        • 谢谢,可以,我不知道操作顺序。
        猜你喜欢
        • 1970-01-01
        • 2017-06-18
        • 2022-11-26
        • 2020-07-26
        • 2022-11-20
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        相关资源
        最近更新 更多