ha9u63a7
ha9u63a7

Reputation: 6862

Python raw_input with while isn't working properly

I am trying to get a character input from the user using raw_input() and see if this is Y or N. The code that is supposed to do the job is given below:

#
# Things I have done before
#
c = ""
while c.capitalize() != "Y" or c.capitalize() != "N":
    c = raw_input("\n\n If you wish to continue, press Y (or N to terminate) ")

if c.capitalize() == "N":
    system.exit("Stopped script......check your files if necessary\n\n");
else:
    #Other things to do

At the moment, I am repeatedly getting the prompt even when I press Y or N. Don't know what's wrong with it. I tried to use input() instead of raw_input() but I think I am using an older version of python (2x) and that's why need to use raw_input.

Any help is appreciated.

Upvotes: 0

Views: 137

Answers (2)

fredtantini
fredtantini

Reputation: 16586

Your condition is wrong:
if c=='N', then the first part (c!=Y) is true, so you will loop (and conversely, if c=='Y', c won't be equals to 'N')

Change to

while (c.capitalize() != "Y" and c.capitalize() != "N"):

or better:

while (c.capitalize() not in ['Y','N']):

Upvotes: 1

Carsten
Carsten

Reputation: 18446

There's a fault in your logic:

while c.capitalize() != "Y" or c.capitalize() != "N":

If I enter "Y", the first term is False, but the second one is True. False or True is True, and the while block is executed. Same thing if I enter "N". You have to use and:

while c.capitalize() != "Y" and c.capitalize() != "N":

Upvotes: 4

Related Questions