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

2024-05-15 01:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: or答案inputrawvalue错误语句条款
3条回答

你是不是想让bet成为input。我想你的意思是如果输入不是10,也不是20。

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

……或者用另一种更自然的方式表达:

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

你需要and

while input != 10 and input != 20:

仔细想想:如果input10,那么第一个表达式是false,这导致Python计算第二个表达式input != 2010不同于20,因此此表达式的计算结果为true。作为false or true == true,整个表达式是true
同样适用于20

相关问题 更多 >

    热门问题