Search code examples
pythonpython-3.xwhile-loopconditional-statements

A program where it requires the user to ONLY type a Yes or No answer, otherwise repeat the whole question


while True:

#SOME CODE...

    ch = input("\nWould you like to try again? Y/N: ").upper()

    if ch == 'Y':
        continue # continue the whole program
    elif:
        print("Thanks for using the program.")
        break # stops the program
    else:
        # repeats the Y or N question only; and prints 'Please input Y or N only'

I tried using continue statement on the else part but it loops back to the whole program and that's not what I want the program to do. Just only want the Y or N question to be looped if none of the conditions is met


Solution

  • You would use a second loop to validate the input before acting on one of the two valid inputs.

    while True:
        # do something
    
        while True:
           ch = input("Try again").upper()
           if ch in ['YES', 'NO']:
               break
           print("Please enter yes or no")
    
        if ch == "NO":
            print("Thanks for using the program.")
            break