繁体   English   中英

Python if 语句不能按预期工作

[英]Python if statement doesn't work as expected

我目前有代码:

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

飞跃不断地打印为 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!"

尝试

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

if语句按设计工作,问题是操作顺序导致此代码执行您想要的操作。

最简单的解决方法是说:

if fleechance == 1 or fleechance == 2:
    print "You failed to run away!"
elif fleechance == 3 or fleechance == 4:
    print "You got away safely!"

因为你不是在问fleechance是 1 还是fleechance是 2; 你问是否

  1. fleechance为 1,或
  2. 2 非零。

当然,条件的第二部分始终为真。 尝试

if fleechance == 1 or fleechance == 2:
    ...

您编写 if 语句的方式是错误的。 你告诉 python 检查 leechance 等于 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!"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM