我目前有代码:
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,但我继续得到结果“你没能逃跑!”谁能告诉我为什么会这样呢?
答案 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;你问是否
fleechance
是1,或当然,条件的第二部分总是如此。尝试
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!"