Reputation: 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...
Upvotes: 0
Views: 2378
Reputation: 46759
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.
Upvotes: 1
Reputation: 1325
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!
Upvotes: 2
Reputation: 915
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.
Upvotes: 1