While statement and boolean OR in Python

python while-loop boolean

1026 观看

3回复

3 作者的声誉

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?

I assume that any time the user inputs something except 'X' or 'O' he gets the message and the prompt for input. But as soon as the user provides either 'X' or 'O', the loop should exit. But it doesn't... Could you, guys help? I am a novice in python...

作者: Roft 的来源 发布者: 2017 年 9 月 15 日

回应 3


1

794 作者的声誉

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'. It can't be equal to both at the same time.

作者: Aanchal1103 发布者: 2017 年 9 月 15 日

2

1162 作者的声誉

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:

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

An alternate solution is to use in which I personally find more readable:

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

Hope this helped!

作者: Jerrybibo 发布者: 2017 年 9 月 15 日

1

30969 作者的声誉

决定

A different way of doing this is to use a while True and a break statement:

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.

作者: Martin Evans 发布者: 2017 年 9 月 15 日
32x32