Can someone please tell me what I am doing wrong. I know this is easy, but I haven't managed to make it work properly.

overwrite = None
while overwrite != 'Y'.lower() or overwrite != 'N'.lower():
    overwrite = raw_input("Do you want to overwrite (Y/N)? ")

It doesn't exit the while loop.

Thanks.

You are creating a situation where the while loop exit condition is always True. Test this ...

overwrite = None
while overwrite != 'y' or overwrite != 'n':
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    print overwrite != 'y'
    print overwrite != 'n'
    # overall condition
    print False or True

Easier to understand is this approach ...

while True:
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    if overwrite == 'y' or overwrite == 'n':
        break

... or even simpler ...

while True:
    overwrite = raw_input("Do you want to overwrite (Y/N)? ").lower()
    if overwrite in 'yn':
        break

Edited 7 Years Ago by vegaseat: n/a

Comments
thanks for such a great answer to my question!

For future coding conundrums, an "or" can be viewed as an if / elif, and "and" can be viewed as two nested if statements, which you would adapt to while() statements.

while overwrite != 'Y'.lower() or overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    do something
elif overwrite != 'N'.lower():
    do the same thing

For completeness, the 'and' would be
if overwrite != 'Y'.lower() and overwrite != 'N'.lower():  becomes
if overwrite != 'Y'.lower():
    if overwrite != 'N'.lower():
       do something

Hopefully this will help sort out the and/or's in the future.

Comments
very good post. explained in great detail.

What woooee said was correct:

overwrite=""
while(overwrite!="Y".lower() and overwrite!="N".lower()):
    overwrite=raw_input()
Comments
clear answer!

Thanks vegaseat, woooee and sravan953. You were all very helpful. :icon_wink:

What woooee said was correct:

overwrite=""
while(overwrite!="Y".lower() and overwrite!="N".lower()):
    overwrite=raw_input()

Here "Y".lower() does not make any sense since it is simply 'y'

This question has already been answered. Start a new discussion instead.