Python if 语句不按预期工作

3 投票
5 回答
3611 浏览
提问于 2025-04-17 03:30

我现在有这段代码:

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 个回答

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

试试这个

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!"
9

这个表达式 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!"

撰写回答