处理两个 != 子句的 OR 语句 Python
(使用 Python 2.7)我知道这是非常基本的,但为什么以下语句不能按书面方式工作:
input = int(raw_input())
while input != 10 or input != 20:
print 'Incorrect value, try again'
bet = int(raw_input())
基本上我只想接受 10 或 20 作为答案。现在,无论“输入”如何,即使是 10 个或 20 个,我都会得到“值不正确”。这些条款是否自相矛盾?我认为只要其中一个子句正确,OR 语句就会说“OK”。谢谢!
(Using Python 2.7) I understand this is pretty elementary but why wouldn't the following statement work as written:
input = int(raw_input())
while input != 10 or input != 20:
print 'Incorrect value, try again'
bet = int(raw_input())
Basically I only want to accept 10 or 20 as an answer. Now, regardless of 'input', even 10, or 20, I get 'Incorrect value'. Are these clauses self conflicting? I thought that the OR statement would say OK as long as one of the clauses was correct. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要
和
:想一想:如果
输入
是10
,那么第一个表达式是false
,导致 Python 计算第二个表达式input != 20
。10
与20
不同,因此该表达式的计算结果为true
。由于false 或 true == true
,整个表达式为true
。20
也是如此。You need
and
:Think it through: If the
input
is10
, then the first expression isfalse
, causing Python to evaluate the second expressioninput != 20
.10
is different form20
, so this expressions evaluates totrue
. Asfalse or true == true
, the whole expression istrue
.Same for
20
.....或者另一种对你来说可能更自然的表达方式:
....or a different way to express it that may seem more natural to you:
您的意思是让
下注
成为输入
吗?我想你的意思是说如果输入不是 10 也不是 20。Did you mean to have the
bet
beinput
. And I think you meant to say if input if not 10 and is not 20.我想你想要一个
and
。这将永远重复 - 如果
input
为 10,则第一个条件为 false。如果input
为 20,则第二个条件为 false。input
永远不能同时为 10 和 20,因此这相当于true
。I think you want an
and
there.This will repeat forever - if
input
is 10, then the first condition is false. ifinput
is 20, the second condition is false.input
can never be both 10 and 20, so that's equivalent totrue
.你想要“和”而不是“或”。考虑一下你的布尔逻辑。
You want "and" and not "or". Think about your boolean logic.