0

The code is supposed to return false if the user's input is not "Y" or "N". When the user types "Y", it ends the loop, but when the type "N" it still continues the loop. How can this be corrected?

# Ask if they want to continue
    while True:
        
        noOrYes = input(f"Do you want to continue? (Y/N)")
        if not noOrYes == "Y" or noOrYes == "N":
            print("Sorry, I didn't understand that.")
            #better try again... Return to the start of the loop
            continue
        else: 
            #firstName & lastName was successfully parsed!
            #we're ready to exit the loop.
            print(f"break")
            break
  • 1
    Use: if not (noOrYes == "Y" or noOrYes == "N"): – zvi Sep 13 '20 at 16:49
  • @zvi: Or distribute the `not` to make it `if noOrYes != "Y" and noOrYes != "N":`. Or use `in` testing to make the logic clearer, `if noOrYes not in ('Y', 'N'):` – ShadowRanger Sep 13 '20 at 16:55

3 Answers3

3

Much like mathematical operations and PEMDAS, boolean operators (and, or, ==) have an "order of operations." Right now you are asking two questions:

Is noOrYes not equal to Y?

Is noOrYes equal to N?

Fix the order of operations by using parentheses. if not (noOrYes == "Y" or noOrYes == "N")

Gbox4
  • 623
  • 2
  • 10
  • 1
    Note you might add that the current example provided is equivalent to `(not noOrYes == "Y") or (noOrYes == "N")` – Ethan Coon Sep 13 '20 at 16:56
0

you can do this instead:

while True: 
    noOrYes = input(f"Do you want to continue? (Y/N)")

    if noOrYes == "Y":
        break
    
    else : 
        print("Sorry, I didn't understand that.")

fayez
  • 370
  • 1
  • 5
0

Instead of asking "if not"s. The following code takes care of every input that's not some variation of "yes" or "no"(Ex. "yeah", "nope", etc.).

# Ask if they want to continue
while True:
    noOrYes = input(f"Do you want to continue? (Y/N)")
    if noOrYes.lower().startswith('y'):
        #User gave a proper response
        #we're ready to exit the loop.
        break
    elif noOrYes.lower().startswith('n'):
        #User gave a proper response,
        #we're ready to exit the loop.
        break
    else: 
        print("Sorry, I didn't understand that.")
        #Better try again... returning to the start of the loop
        continue