Python if语句不能按预期工作

Dan*_*Doe 3 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!"
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*rin 9

表达式fleechance == 1 or 2相当于(fleechance == 1) or (2).该数字2始终被视为"真实".

试试这个:

if fleechance in (1, 2):
Run Code Online (Sandbox Code Playgroud)

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

if fleechance <= 2:
    print "You failed to run away!"
else:
    print "You got away safely!"
Run Code Online (Sandbox Code Playgroud)