简体   繁体   English

在Python中的While语句和布尔OR

[英]While statement and boolean OR in Python

y=''
print 'y= nothing'
y = raw_input('-->')
while y!='O' or y!='X':
    print 'You have to choose either X or O'
    y = raw_input('-->')
print 'Loop exited'
print y

Could anyone explain why the above code doesn't run properly in python? 谁能解释为什么上面的代码不能在python中正常运行?

I assume that any time the user inputs something except 'X' or 'O' he gets the message and the prompt for input. 我假设,只要用户输入“ X”或“ O”以外的任何内容,他都会得到消息和输入提示。 But as soon as the user provides either 'X' or 'O', the loop should exit. 但是,只要用户提供“ X”或“ O”,循环就应该退出。 But it doesn't... Could you, guys help? 但这不是...你们可以帮忙吗? I am a novice in python... 我是python的新手...

There are several fixes to this erroneous logic flow. 此错误逻辑流有多种修复方法。 One was already mentioned by @Aanchal Sharma by having two != 's and an and within the while loop like so: @Aanchal Sharma已经提到了一个and在while循环中有两个!=和an and ,如下所示:

while y != 'O' and y != 'X':

An alternate solution is to use in which I personally find more readable: 一个替代解决方法是使用in我个人找到更多可读:

while y not in ['X', 'O']:
    print 'You have to choose either X or O'
    y = raw_input('--> ')

Hope this helped! 希望这对您有所帮助!

y=''
print 'y= nothing'
y = raw_input('-->')
while (y!='O' and y!='X'):
    print 'You have to choose either X or O'
    y = raw_input('-->')
print 'Loop exited'
print y

Use 'and' condition not 'or'. 使用“和”条件而不是“或”。 In your case, y will always be either not-equal to 'O' or not-equal to 'X'. 在您的情况下, y始终等于或等于'O'或等于'X'。 It can't be equal to both at the same time. 它不能同时等于两个。

A different way of doing this is to use a while True and a break statement: 执行此操作的另一种方法是使用while Truebreak语句:

while True:
    y = raw_input('-->')

    if  y in ['O', 'X']:
        break
    print 'You have to choose either X or O'

print 'Loop exited'
print y

For example: 例如:

-->a
You have to choose either X or O
-->b
You have to choose either X or O
-->c
You have to choose either X or O
-->O
Loop exited
O

This avoids needing to have two input statements. 这避免了需要两个输入语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM