本文介绍了Python if语句不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有代码:
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,但我继续得到结果你没能跑远! ,谁能告诉我为什么会这样?
fleechance is constantly printing as 3 or 4, but I continue to get the result "You failed to run away!" ,can anyone tell me why this is happening?
推荐答案
表达式 fleechance == 1或2
相当于(fleechance == 1)或(2)
。数字 2
始终被视为真实。
The expression fleechance == 1 or 2
is equivalent to (fleechance == 1) or (2)
. The number 2
is always considered "true".
试试这个:
if fleechance in (1, 2):
编辑:在你的情况下(只有2种可能性),以下情况会更好:
In your situation (only 2 possibilities), the following will be even better:
if fleechance <= 2:
print "You failed to run away!"
else:
print "You got away safely!"
这篇关于Python if语句不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!