OR statement handling two != clauses Python

橙三吉。 提交于 2020-02-03 10:55:52

问题


(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!


回答1:


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.




回答2:


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

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



回答3:


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())



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/5681271/or-statement-handling-two-clauses-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!