3

(使用 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。谢谢!

4

5 回答 5

17

你需要and

while input != 10 and input != 20:

想一想:如果inputis 10,那么第一个表达式是false,导致 Python 计算第二个表达式input != 2010是不同的形式20,所以这个表达式的计算结果为true。As false or true == true,整个表达式是true
20.

于 2011-04-15T19:14:57.227 回答
10

....或另一种表达方式,对您来说可能更自然:

while input not in (10, 20):
    # your code here...
于 2011-04-15T19:17:25.023 回答
0

你的意思是有betinput?而且我认为您的意思是如果输入不是 10 而不是 20。

input = int(raw_input())
while input != 10 and input != 20:
    print 'Incorrect value, try again'
    input = int(raw_input())
于 2011-04-15T19:15:21.003 回答
0

我想你想要一个and那里。

while input != 10 or input != 20:

这将永远重复 - 如果input是 10,则第一个条件为假。如果input为 20,则第二个条件为假。input不能同时是 10 和 20,所以这相当于true.

于 2011-04-15T19:15:40.457 回答
0

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

于 2011-04-15T19:15:58.100 回答