简体   繁体   中英

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?

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...

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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