Python if语句不能按预期工作

时间:2011-10-02 00:18:41

标签: python printing random if-statement

我目前有代码:

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,但我继续得到结果“你没能逃跑!”谁能告诉我为什么会这样呢?

5 个答案:

答案 0 :(得分:9)

表达式fleechance == 1 or 2相当于(fleechance == 1) or (2)。数字2始终被视为“真实”。

试试这个:

if fleechance in (1, 2):

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

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

答案 1 :(得分:3)

尝试

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 :(得分:1)

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

最简单的解决方法是:

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

答案 3 :(得分:1)

因为您没有询问fleechance是1还是fleechance是2;你问是否

  1. fleechance是1,或
  2. 2非零。
  3. 当然,条件的第二部分总是如此。尝试

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

答案 4 :(得分:1)

你编写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!"