0

This is probably a simple problem that requires a simple answer...but I have been scratching my head why this happens. It's a problem on the loop that I am testing. Here's the loop:

done = False
while done==False:
    checkUser = input("Do you want to continue?\nType Y or y to continue; any other char to quit\nType here: ")
    print(checkUser) # just to check the input

    if checkUser =='Y' or 'y':
        print ('Yes, I want to continue.')
        done = False
        break

    else:
        print('No. I want to quit now.')
        done = True
        sys.exit()

When I run this script on PyCharm, I get the outputs below:

Do you want to continue?
Type Y or y to continue; any other char to quit
Type here: y
y
Yes, I want to continue

Do you want to continue?
Type Y or y to continue; any other char to quit
Type here: n
n
Yes, I want to continue

Question: why is the "else" option ignored?

I tried so many variations like removing sys.exit() and so forth, but the loop still behaves the same way.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • dupe of [Why does checking a variable against multiple values with \`OR\` only check the first value?](https://stackoverflow.com/questions/18212574/why-does-checking-a-variable-against-multiple-values-with-or-only-check-the-fi) and many more – underscore_d Jun 01 '21 at 09:03

2 Answers2

0

change the line if checkUser =='Y' or 'y': to if checkUser =='Y' or checkUser == 'y': code worked as your expectation. if checkUser =='Y' or 'y': means check if checkUser is 'Y' or 'y' is true which is true for any input.

Alimur Razi Rana
  • 338
  • 3
  • 15
0

It's not necessary to add break at the end of the if-condition as the while loop is already controlled by done variable. And your if-condition is not written properly such that the machine interprets as:

if (checkUser == 'Y') or ('y')

so the conditions become:

condition_1: checkUser = 'Y'?
condition_2: 'y'?

if 'y' will always generate true so the while loop will go forever. You should do:

if checkUser == 'Y' or checkUser == 'y'

see if it helps you.

Dharman
  • 30,962
  • 25
  • 85
  • 135
NiC
  • 55
  • 4