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,但我继续得到结果“你逃跑失败!” ,谁能告诉我为什么会这样?
I currently have the code:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
表达式
fleechance == 1 or 2
等价于(fleechance == 1) or (2)
。数字2
始终被视为“true”。试试这个:
编辑:根据你的情况(只有两种可能性),以下内容会更好:
The expression
fleechance == 1 or 2
is equivalent to(fleechance == 1) or (2)
. The number2
is always considered “true”.Try this:
EDIT: In your situation (only 2 possibilities), the following will be even better:
尝试
或者,如果这些是唯一的可能性,你可以这样做
Try
Alternatively, if those are the only possibilites, you can do
if
语句按设计工作,问题是操作顺序导致此代码执行与您想要的不同的操作。最简单的解决方法是:
The
if
statement is working as designed, the problem is that order of operations is causing this code to do something other than that you want.The easiest fix would be to say:
因为您不是在问
fleechance
是 1 还是fleechance
是 2;您询问的是fleechance
是否为 1,或者当然,条件的第二部分始终为真。尝试
Because you're not asking whether
fleechance
is 1 orfleechance
is 2; you're asking whetherfleechance
is 1, orOf course, that second part of the condition is always true. Try
您编写 if 语句的方式是错误的。
你告诉Python检查fleechance等于1是否为真或者2是否为真。
非零整数始终意味着条件为真。
你应该写:
The way you wrote your if statements is wrong.
You tell python to check if fleechance equals 1 is true or if 2 is true.
A non-zero integer always means true in a condition.
You should wrote :