-1

I'm finding it difficult to break a while loop when a user inputs an 'N', it only accepts a 'Y'. Inputting an 'N' will still activate the second while loop.

How do I write such that once user inputs N, the while loop breaks? Thank you in advance :)

choice = 'Y'
while choice == 'Y':

    choice = input('Would you like to continue? (y/n): ').upper()
    # it breaks at this point  

    while (choice != 'Y') or (choice != 'N'):
        choice = input('Please choose Y for yes, or N for no!: ').upper()
  • 1
    Use the `break` statement :) – jkr May 23 '20 at 16:30
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wjandrea May 23 '20 at 16:32
  • `(choice != 'Y') or (choice != 'N')` is always true. Any value of `choice` is either not equal to `'Y'` or not equal to `'N'`. You mean `and` instead of `or`. – khelwood May 23 '20 at 16:37

2 Answers2

1
choice = 'Y'
while choice == 'Y':
    choice = input('Would you like to continue? (y/n): ').upper()
    while (choice != 'Y') and (choice != 'N'): # and, not or!
        choice = input('Please choose Y for yes, or N for no!: ').upper()
Błotosmętek
  • 12,717
  • 19
  • 29
  • 1
    oh thank you so much, its such a simple solution. I've only started self learning a week ago, thank you @Blotosmetek for your help – Luqman Buang May 23 '20 at 16:39
1

The other answer provided was fantastic but I want to give an example using the "break" statement.

  while True:
        user_input = input("Run more y/n?")
        if user_input == 'y':
            print("I'm still running in the loop")
        elif user_input == 'n':
            print("I am no longer running and have broken from the while loop.")
            break
        else:
            print("The input is invalid but I'm still running in the loop. Try again")
Brett La Pierre
  • 493
  • 6
  • 15