Python if 语句没有按预期工作

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

最佳答案

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

关于Python if 语句没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7623818/

相关文章:

python - 如何删除 beautifulsoup 中的换行符?

Python机器学习: Using Multinomial Naive Bayes gives Multiprocessing exception

printing - 通过 libcups 以编程方式打印双面打印的正确方法是什么?

java - 嵌套循环中的随机不同数字

python - 如何使用正则表达式来匹配至少包含一个大写字母但不全部为小写字母的特定单词?

css - 使用浏览器的 "Shrink to page width"打印

javascript - 使用 print.css 样式表删除打印时出现的元素

c - 通过赔率生成随机数

c++ - C++11 中的随机字节生成

python - graphlab创建sframe合并两列