处理两个 != 子句的 OR 语句 Python

发布于 2024-11-02 07:02:53 字数 313 浏览 0 评论 0原文

(使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

怀念你的温柔 2024-11-09 07:02:53

您需要

while input != 10 and input != 20:

想一想:如果输入10,那么第一个表达式是false,导致 Python 计算第二个表达式 input != 201020 不同,因此该表达式的计算结果为 true。由于 false 或 true == true,整个表达式为 true
20 也是如此。

You need and:

while input != 10 and input != 20:

Think it through: If the input is 10, then the first expression is false, causing Python to evaluate the second expression input != 20. 10 is different form 20, so this expressions evaluates to true. As false or true == true, the whole expression is true.
Same for 20.

愁杀 2024-11-09 07:02:53

....或者另一种对你来说可能更自然的表达方式:

while input not in (10, 20):
    # your code here...

....or a different way to express it that may seem more natural to you:

while input not in (10, 20):
    # your code here...
微暖i 2024-11-09 07:02:53

您的意思是让下注成为输入吗?我想你的意思是说如果输入不是 10 也不是 20。

input = int(raw_input())
while input != 10 and input != 20:
    print 'Incorrect value, try again'
    input = int(raw_input())

Did you mean to have the bet be input. And I think you meant to say if input if not 10 and is not 20.

input = int(raw_input())
while input != 10 and input != 20:
    print 'Incorrect value, try again'
    input = int(raw_input())
几味少女 2024-11-09 07:02:53

我想你想要一个 and

while input != 10 or input != 20:

这将永远重复 - 如果 input 为 10,则第一个条件为 false。如果 input 为 20,则第二个条件为 false。 input 永远不能同时为 10 和 20,因此这相当于 true

I think you want an and there.

while input != 10 or input != 20:

This will repeat forever - if input is 10, then the first condition is false. if input is 20, the second condition is false. input can never be both 10 and 20, so that's equivalent to true.

迷鸟归林 2024-11-09 07:02:53

你想要“和”而不是“或”。考虑一下你的布尔逻辑。

You want "and" and not "or". Think about your boolean logic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文